title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Python | os.fork() method
11 Oct, 2021 OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.All functions in os module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type, but are not accepted by the operating system. os.fork() method in Python is used to create a child process. This method work by calling the underlying OS function fork(). This method returns 0 in the child process and child’s process id in the parent process. Note: os.fork() method is available only on UNIX platforms. Syntax: os.fork()Parameter: No parameter is requiredReturn Type: This method returns an integer value representing child’s process id in the parent process while 0 in the child process. Code: Use of os.fork() method to create a child process Python3 # Python program to explain os.fork() method # importing os module import os # Create a child process# using os.fork() method pid = os.fork() # pid greater than 0 represents# the parent process if pid > 0 : print("I am parent process:") print("Process ID:", os.getpid()) print("Child's process ID:", pid) # pid equal to 0 represents# the created child processelse : print("\nI am child process:") print("Process ID:", os.getpid()) print("Parent's process ID:", os.getppid()) # If any error occurred while# using os.fork() method# OSError will be raised I am Parent process Process ID: 10793 Child's process ID: 10794 I am child process Process ID: 10794 Parent's process ID: 10793 rajeev0719singh gabaa406 python-os-module Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Oct, 2021" }, { "code": null, "e": 442, "s": 28, "text": "OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.All functions in os module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type, but are not accepted by the operating system. " }, { "code": null, "e": 657, "s": 442, "text": "os.fork() method in Python is used to create a child process. This method work by calling the underlying OS function fork(). This method returns 0 in the child process and child’s process id in the parent process. " }, { "code": null, "e": 717, "s": 657, "text": "Note: os.fork() method is available only on UNIX platforms." }, { "code": null, "e": 905, "s": 717, "text": "Syntax: os.fork()Parameter: No parameter is requiredReturn Type: This method returns an integer value representing child’s process id in the parent process while 0 in the child process. " }, { "code": null, "e": 963, "s": 905, "text": "Code: Use of os.fork() method to create a child process " }, { "code": null, "e": 971, "s": 963, "text": "Python3" }, { "code": "# Python program to explain os.fork() method # importing os module import os # Create a child process# using os.fork() method pid = os.fork() # pid greater than 0 represents# the parent process if pid > 0 : print(\"I am parent process:\") print(\"Process ID:\", os.getpid()) print(\"Child's process ID:\", pid) # pid equal to 0 represents# the created child processelse : print(\"\\nI am child process:\") print(\"Process ID:\", os.getpid()) print(\"Parent's process ID:\", os.getppid()) # If any error occurred while# using os.fork() method# OSError will be raised", "e": 1552, "s": 971, "text": null }, { "code": null, "e": 1681, "s": 1552, "text": "I am Parent process\nProcess ID: 10793\nChild's process ID: 10794\n\nI am child process\nProcess ID: 10794\nParent's process ID: 10793" }, { "code": null, "e": 1699, "s": 1683, "text": "rajeev0719singh" }, { "code": null, "e": 1708, "s": 1699, "text": "gabaa406" }, { "code": null, "e": 1725, "s": 1708, "text": "python-os-module" }, { "code": null, "e": 1732, "s": 1725, "text": "Python" } ]
Issues in the design of a code generator
13 Dec, 2019 Code generator converts the intermediate representation of source code into a form that can be readily executed by the machine. A code generator is expected to generate the correct code. Designing of code generator should be done in such a way so that it can be easily implemented, tested and maintained. The following issue arises during the code generation phase: Input to code generator –The input to code generator is the intermediate code generated by the front end, along with information in the symbol table that determines the run-time addresses of the data-objects denoted by the names in the intermediate representation. Intermediate codes may be represented mostly in quadruples, triples, indirect triples, Postfix notation, syntax trees, DAG’s, etc. The code generation phase just proceeds on an assumption that the input are free from all of syntactic and state semantic errors, the necessary type checking has taken place and the type-conversion operators have been inserted wherever necessary.Target program –The target program is the output of the code generator. The output may be absolute machine language, relocatable machine language, assembly language.Absolute machine language as output has advantages that it can be placed in a fixed memory location and can be immediately executed.Relocatable machine language as an output allows subprograms and subroutines to be compiled separately. Relocatable object modules can be linked together and loaded by linking loader. But there is added expense of linking and loading.Assembly language as output makes the code generation easier. We can generate symbolic instructions and use macro-facilities of assembler in generating code. And we need an additional assembly step after code generation.Memory Management –Mapping the names in the source program to the addresses of data objects is done by the front end and the code generator. A name in the three address statements refers to the symbol table entry for name. Then from the symbol table entry, a relative address can be determined for the name.Instruction selection –Selecting the best instructions will improve the efficiency of the program. It includes the instructions that should be complete and uniform. Instruction speeds and machine idioms also plays a major role when efficiency is considered. But if we do not care about the efficiency of the target program then instruction selection is straight-forward.For example, the respective three-address statements would be translated into the latter code sequence as shown below:P:=Q+R S:=P+T MOV Q, R0 ADD R, R0 MOV R0, P MOV P, R0 ADD T, R0 MOV R0, S Here the fourth statement is redundant as the value of the P is loaded again in that statement that just has been stored in the previous statement. It leads to an inefficient code sequence. A given intermediate representation can be translated into many code sequences, with significant cost differences between the different implementations. A prior knowledge of instruction cost is needed in order to design good sequences, but accurate cost information is difficult to predict.Register allocation issues –Use of registers make the computations faster in comparison to that of memory, so efficient utilization of registers is important. The use of registers are subdivided into two subproblems:During Register allocation – we select only those set of variables that will reside in the registers at each point in the program.During a subsequent Register assignment phase, the specific register is picked to access the variable.As the number of variables increases, the optimal assignment of registers to variables becomes difficult. Mathematically, this problem becomes NP-complete. Certain machine requires register pairs consist of an even and next odd-numbered register. For exampleM a, b These types of multiplicative instruction involve register pairs where the multiplicand is an even register and b, the multiplier is the odd register of the even/odd register pair.Evaluation order –The code generator decides the order in which the instruction will be executed. The order of computations affects the efficiency of the target code. Among many computational orders, some will require only fewer registers to hold the intermediate results. However, picking the best order in the general case is a difficult NP-complete problem.Approaches to code generation issues: Code generator must always generate the correct code. It is essential because of the number of special cases that a code generator might face. Some of the design goals of code generator are:CorrectEasily maintainableTestableEfficient Input to code generator –The input to code generator is the intermediate code generated by the front end, along with information in the symbol table that determines the run-time addresses of the data-objects denoted by the names in the intermediate representation. Intermediate codes may be represented mostly in quadruples, triples, indirect triples, Postfix notation, syntax trees, DAG’s, etc. The code generation phase just proceeds on an assumption that the input are free from all of syntactic and state semantic errors, the necessary type checking has taken place and the type-conversion operators have been inserted wherever necessary. Target program –The target program is the output of the code generator. The output may be absolute machine language, relocatable machine language, assembly language.Absolute machine language as output has advantages that it can be placed in a fixed memory location and can be immediately executed.Relocatable machine language as an output allows subprograms and subroutines to be compiled separately. Relocatable object modules can be linked together and loaded by linking loader. But there is added expense of linking and loading.Assembly language as output makes the code generation easier. We can generate symbolic instructions and use macro-facilities of assembler in generating code. And we need an additional assembly step after code generation. Absolute machine language as output has advantages that it can be placed in a fixed memory location and can be immediately executed. Relocatable machine language as an output allows subprograms and subroutines to be compiled separately. Relocatable object modules can be linked together and loaded by linking loader. But there is added expense of linking and loading. Assembly language as output makes the code generation easier. We can generate symbolic instructions and use macro-facilities of assembler in generating code. And we need an additional assembly step after code generation. Memory Management –Mapping the names in the source program to the addresses of data objects is done by the front end and the code generator. A name in the three address statements refers to the symbol table entry for name. Then from the symbol table entry, a relative address can be determined for the name. Instruction selection –Selecting the best instructions will improve the efficiency of the program. It includes the instructions that should be complete and uniform. Instruction speeds and machine idioms also plays a major role when efficiency is considered. But if we do not care about the efficiency of the target program then instruction selection is straight-forward.For example, the respective three-address statements would be translated into the latter code sequence as shown below:P:=Q+R S:=P+T MOV Q, R0 ADD R, R0 MOV R0, P MOV P, R0 ADD T, R0 MOV R0, S Here the fourth statement is redundant as the value of the P is loaded again in that statement that just has been stored in the previous statement. It leads to an inefficient code sequence. A given intermediate representation can be translated into many code sequences, with significant cost differences between the different implementations. A prior knowledge of instruction cost is needed in order to design good sequences, but accurate cost information is difficult to predict. For example, the respective three-address statements would be translated into the latter code sequence as shown below: P:=Q+R S:=P+T MOV Q, R0 ADD R, R0 MOV R0, P MOV P, R0 ADD T, R0 MOV R0, S Here the fourth statement is redundant as the value of the P is loaded again in that statement that just has been stored in the previous statement. It leads to an inefficient code sequence. A given intermediate representation can be translated into many code sequences, with significant cost differences between the different implementations. A prior knowledge of instruction cost is needed in order to design good sequences, but accurate cost information is difficult to predict. Register allocation issues –Use of registers make the computations faster in comparison to that of memory, so efficient utilization of registers is important. The use of registers are subdivided into two subproblems:During Register allocation – we select only those set of variables that will reside in the registers at each point in the program.During a subsequent Register assignment phase, the specific register is picked to access the variable.As the number of variables increases, the optimal assignment of registers to variables becomes difficult. Mathematically, this problem becomes NP-complete. Certain machine requires register pairs consist of an even and next odd-numbered register. For exampleM a, b These types of multiplicative instruction involve register pairs where the multiplicand is an even register and b, the multiplier is the odd register of the even/odd register pair. During Register allocation – we select only those set of variables that will reside in the registers at each point in the program.During a subsequent Register assignment phase, the specific register is picked to access the variable. During Register allocation – we select only those set of variables that will reside in the registers at each point in the program. During a subsequent Register assignment phase, the specific register is picked to access the variable. As the number of variables increases, the optimal assignment of registers to variables becomes difficult. Mathematically, this problem becomes NP-complete. Certain machine requires register pairs consist of an even and next odd-numbered register. For example M a, b These types of multiplicative instruction involve register pairs where the multiplicand is an even register and b, the multiplier is the odd register of the even/odd register pair. Evaluation order –The code generator decides the order in which the instruction will be executed. The order of computations affects the efficiency of the target code. Among many computational orders, some will require only fewer registers to hold the intermediate results. However, picking the best order in the general case is a difficult NP-complete problem. Approaches to code generation issues: Code generator must always generate the correct code. It is essential because of the number of special cases that a code generator might face. Some of the design goals of code generator are:CorrectEasily maintainableTestableEfficient Correct Easily maintainable Testable Efficient VishalAcharya AkashSankritya Compiler Design Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Type Checking in Compiler Design Directed Acyclic graph in Compiler Design (with examples) Data flow analysis in Compiler S - attributed and L - attributed SDTs in Syntax directed translation Difference between Compiler and Interpreter Runtime Environments in Compiler Design Input Buffering in Compiler Design Syntax Directed Translation in Compiler Design Compiler construction tools Token, Patterns, and Lexems
[ { "code": null, "e": 52, "s": 24, "text": "\n13 Dec, 2019" }, { "code": null, "e": 357, "s": 52, "text": "Code generator converts the intermediate representation of source code into a form that can be readily executed by the machine. A code generator is expected to generate the correct code. Designing of code generator should be done in such a way so that it can be easily implemented, tested and maintained." }, { "code": null, "e": 418, "s": 357, "text": "The following issue arises during the code generation phase:" }, { "code": null, "e": 4686, "s": 418, "text": "Input to code generator –The input to code generator is the intermediate code generated by the front end, along with information in the symbol table that determines the run-time addresses of the data-objects denoted by the names in the intermediate representation. Intermediate codes may be represented mostly in quadruples, triples, indirect triples, Postfix notation, syntax trees, DAG’s, etc. The code generation phase just proceeds on an assumption that the input are free from all of syntactic and state semantic errors, the necessary type checking has taken place and the type-conversion operators have been inserted wherever necessary.Target program –The target program is the output of the code generator. The output may be absolute machine language, relocatable machine language, assembly language.Absolute machine language as output has advantages that it can be placed in a fixed memory location and can be immediately executed.Relocatable machine language as an output allows subprograms and subroutines to be compiled separately. Relocatable object modules can be linked together and loaded by linking loader. But there is added expense of linking and loading.Assembly language as output makes the code generation easier. We can generate symbolic instructions and use macro-facilities of assembler in generating code. And we need an additional assembly step after code generation.Memory Management –Mapping the names in the source program to the addresses of data objects is done by the front end and the code generator. A name in the three address statements refers to the symbol table entry for name. Then from the symbol table entry, a relative address can be determined for the name.Instruction selection –Selecting the best instructions will improve the efficiency of the program. It includes the instructions that should be complete and uniform. Instruction speeds and machine idioms also plays a major role when efficiency is considered. But if we do not care about the efficiency of the target program then instruction selection is straight-forward.For example, the respective three-address statements would be translated into the latter code sequence as shown below:P:=Q+R\nS:=P+T\n\nMOV Q, R0\nADD R, R0\nMOV R0, P\nMOV P, R0\nADD T, R0\nMOV R0, S\nHere the fourth statement is redundant as the value of the P is loaded again in that statement that just has been stored in the previous statement. It leads to an inefficient code sequence. A given intermediate representation can be translated into many code sequences, with significant cost differences between the different implementations. A prior knowledge of instruction cost is needed in order to design good sequences, but accurate cost information is difficult to predict.Register allocation issues –Use of registers make the computations faster in comparison to that of memory, so efficient utilization of registers is important. The use of registers are subdivided into two subproblems:During Register allocation – we select only those set of variables that will reside in the registers at each point in the program.During a subsequent Register assignment phase, the specific register is picked to access the variable.As the number of variables increases, the optimal assignment of registers to variables becomes difficult. Mathematically, this problem becomes NP-complete. Certain machine requires register pairs consist of an even and next odd-numbered register. For exampleM a, b\nThese types of multiplicative instruction involve register pairs where the multiplicand is an even register and b, the multiplier is the odd register of the even/odd register pair.Evaluation order –The code generator decides the order in which the instruction will be executed. The order of computations affects the efficiency of the target code. Among many computational orders, some will require only fewer registers to hold the intermediate results. However, picking the best order in the general case is a difficult NP-complete problem.Approaches to code generation issues: Code generator must always generate the correct code. It is essential because of the number of special cases that a code generator might face. Some of the design goals of code generator are:CorrectEasily maintainableTestableEfficient" }, { "code": null, "e": 5329, "s": 4686, "text": "Input to code generator –The input to code generator is the intermediate code generated by the front end, along with information in the symbol table that determines the run-time addresses of the data-objects denoted by the names in the intermediate representation. Intermediate codes may be represented mostly in quadruples, triples, indirect triples, Postfix notation, syntax trees, DAG’s, etc. The code generation phase just proceeds on an assumption that the input are free from all of syntactic and state semantic errors, the necessary type checking has taken place and the type-conversion operators have been inserted wherever necessary." }, { "code": null, "e": 6081, "s": 5329, "text": "Target program –The target program is the output of the code generator. The output may be absolute machine language, relocatable machine language, assembly language.Absolute machine language as output has advantages that it can be placed in a fixed memory location and can be immediately executed.Relocatable machine language as an output allows subprograms and subroutines to be compiled separately. Relocatable object modules can be linked together and loaded by linking loader. But there is added expense of linking and loading.Assembly language as output makes the code generation easier. We can generate symbolic instructions and use macro-facilities of assembler in generating code. And we need an additional assembly step after code generation." }, { "code": null, "e": 6214, "s": 6081, "text": "Absolute machine language as output has advantages that it can be placed in a fixed memory location and can be immediately executed." }, { "code": null, "e": 6449, "s": 6214, "text": "Relocatable machine language as an output allows subprograms and subroutines to be compiled separately. Relocatable object modules can be linked together and loaded by linking loader. But there is added expense of linking and loading." }, { "code": null, "e": 6670, "s": 6449, "text": "Assembly language as output makes the code generation easier. We can generate symbolic instructions and use macro-facilities of assembler in generating code. And we need an additional assembly step after code generation." }, { "code": null, "e": 6978, "s": 6670, "text": "Memory Management –Mapping the names in the source program to the addresses of data objects is done by the front end and the code generator. A name in the three address statements refers to the symbol table entry for name. Then from the symbol table entry, a relative address can be determined for the name." }, { "code": null, "e": 8022, "s": 6978, "text": "Instruction selection –Selecting the best instructions will improve the efficiency of the program. It includes the instructions that should be complete and uniform. Instruction speeds and machine idioms also plays a major role when efficiency is considered. But if we do not care about the efficiency of the target program then instruction selection is straight-forward.For example, the respective three-address statements would be translated into the latter code sequence as shown below:P:=Q+R\nS:=P+T\n\nMOV Q, R0\nADD R, R0\nMOV R0, P\nMOV P, R0\nADD T, R0\nMOV R0, S\nHere the fourth statement is redundant as the value of the P is loaded again in that statement that just has been stored in the previous statement. It leads to an inefficient code sequence. A given intermediate representation can be translated into many code sequences, with significant cost differences between the different implementations. A prior knowledge of instruction cost is needed in order to design good sequences, but accurate cost information is difficult to predict." }, { "code": null, "e": 8141, "s": 8022, "text": "For example, the respective three-address statements would be translated into the latter code sequence as shown below:" }, { "code": null, "e": 8217, "s": 8141, "text": "P:=Q+R\nS:=P+T\n\nMOV Q, R0\nADD R, R0\nMOV R0, P\nMOV P, R0\nADD T, R0\nMOV R0, S\n" }, { "code": null, "e": 8698, "s": 8217, "text": "Here the fourth statement is redundant as the value of the P is loaded again in that statement that just has been stored in the previous statement. It leads to an inefficient code sequence. A given intermediate representation can be translated into many code sequences, with significant cost differences between the different implementations. A prior knowledge of instruction cost is needed in order to design good sequences, but accurate cost information is difficult to predict." }, { "code": null, "e": 9592, "s": 8698, "text": "Register allocation issues –Use of registers make the computations faster in comparison to that of memory, so efficient utilization of registers is important. The use of registers are subdivided into two subproblems:During Register allocation – we select only those set of variables that will reside in the registers at each point in the program.During a subsequent Register assignment phase, the specific register is picked to access the variable.As the number of variables increases, the optimal assignment of registers to variables becomes difficult. Mathematically, this problem becomes NP-complete. Certain machine requires register pairs consist of an even and next odd-numbered register. For exampleM a, b\nThese types of multiplicative instruction involve register pairs where the multiplicand is an even register and b, the multiplier is the odd register of the even/odd register pair." }, { "code": null, "e": 9825, "s": 9592, "text": "During Register allocation – we select only those set of variables that will reside in the registers at each point in the program.During a subsequent Register assignment phase, the specific register is picked to access the variable." }, { "code": null, "e": 9956, "s": 9825, "text": "During Register allocation – we select only those set of variables that will reside in the registers at each point in the program." }, { "code": null, "e": 10059, "s": 9956, "text": "During a subsequent Register assignment phase, the specific register is picked to access the variable." }, { "code": null, "e": 10318, "s": 10059, "text": "As the number of variables increases, the optimal assignment of registers to variables becomes difficult. Mathematically, this problem becomes NP-complete. Certain machine requires register pairs consist of an even and next odd-numbered register. For example" }, { "code": null, "e": 10326, "s": 10318, "text": "M a, b\n" }, { "code": null, "e": 10507, "s": 10326, "text": "These types of multiplicative instruction involve register pairs where the multiplicand is an even register and b, the multiplier is the odd register of the even/odd register pair." }, { "code": null, "e": 10868, "s": 10507, "text": "Evaluation order –The code generator decides the order in which the instruction will be executed. The order of computations affects the efficiency of the target code. Among many computational orders, some will require only fewer registers to hold the intermediate results. However, picking the best order in the general case is a difficult NP-complete problem." }, { "code": null, "e": 11140, "s": 10868, "text": "Approaches to code generation issues: Code generator must always generate the correct code. It is essential because of the number of special cases that a code generator might face. Some of the design goals of code generator are:CorrectEasily maintainableTestableEfficient" }, { "code": null, "e": 11148, "s": 11140, "text": "Correct" }, { "code": null, "e": 11168, "s": 11148, "text": "Easily maintainable" }, { "code": null, "e": 11177, "s": 11168, "text": "Testable" }, { "code": null, "e": 11187, "s": 11177, "text": "Efficient" }, { "code": null, "e": 11201, "s": 11187, "text": "VishalAcharya" }, { "code": null, "e": 11216, "s": 11201, "text": "AkashSankritya" }, { "code": null, "e": 11232, "s": 11216, "text": "Compiler Design" }, { "code": null, "e": 11330, "s": 11232, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 11363, "s": 11330, "text": "Type Checking in Compiler Design" }, { "code": null, "e": 11421, "s": 11363, "text": "Directed Acyclic graph in Compiler Design (with examples)" }, { "code": null, "e": 11452, "s": 11421, "text": "Data flow analysis in Compiler" }, { "code": null, "e": 11522, "s": 11452, "text": "S - attributed and L - attributed SDTs in Syntax directed translation" }, { "code": null, "e": 11566, "s": 11522, "text": "Difference between Compiler and Interpreter" }, { "code": null, "e": 11606, "s": 11566, "text": "Runtime Environments in Compiler Design" }, { "code": null, "e": 11641, "s": 11606, "text": "Input Buffering in Compiler Design" }, { "code": null, "e": 11688, "s": 11641, "text": "Syntax Directed Translation in Compiler Design" }, { "code": null, "e": 11716, "s": 11688, "text": "Compiler construction tools" } ]
Floor in a Sorted Array
16 Feb, 2022 Given a sorted array and a value x, the floor of x is the largest element in array smaller than or equal to x. Write efficient functions to find floor of x.Examples: Input : arr[] = {1, 2, 8, 10, 10, 12, 19}, x = 5 Output : 2 2 is the largest element in arr[] smaller than 5. Input : arr[] = {1, 2, 8, 10, 10, 12, 19}, x = 20 Output : 19 19 is the largest element in arr[] smaller than 20. Input : arr[] = {1, 2, 8, 10, 10, 12, 19}, x = 0 Output : -1 Since floor doesn't exist, output is -1. Simple MethodApproach: The idea is simple, traverse through the array and find the first element greater than x. The element just before the found element is the floor of x.Algorithm: Traverse through the array from start to end.If the current element is greater than x print the previous number and break the loop.If there is no number greater than x then print the last elementIf the first number is greater than x then print -1 Traverse through the array from start to end. If the current element is greater than x print the previous number and break the loop. If there is no number greater than x then print the last element If the first number is greater than x then print -1 C++ C Java Python3 C# PHP Javascript // C++ program to find floor of a given number// in a sorted array#include <iostream>using namespace std; /* An inefficient function to getindex of floor of x in arr[0..n-1] */int floorSearch(int arr[], int n, int x){ // If last element is smaller than x if (x >= arr[n - 1]) return n - 1; // If first element is greater than x if (x < arr[0]) return -1; // Linearly search for the first element // greater than x for (int i = 1; i < n; i++) if (arr[i] > x) return (i - 1); return -1;} /* Driver program to check above functions */int main(){ int arr[] = { 1, 2, 4, 6, 10, 12, 14 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 7; int index = floorSearch(arr, n - 1, x); if (index == -1) cout<<"Floor of "<<x <<" doesn't exist in array "; else cout<<"Floor of "<< x <<" is " << arr[index]; return 0;} // This code is contributed by shivanisinghss2110 // C/C++ program to find floor of a given number// in a sorted array#include <stdio.h> /* An inefficient function to getindex of floor of x in arr[0..n-1] */int floorSearch(int arr[], int n, int x){ // If last element is smaller than x if (x >= arr[n - 1]) return n - 1; // If first element is greater than x if (x < arr[0]) return -1; // Linearly search for the first element // greater than x for (int i = 1; i < n; i++) if (arr[i] > x) return (i - 1); return -1;} /* Driver program to check above functions */int main(){ int arr[] = { 1, 2, 4, 6, 10, 12, 14 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 7; int index = floorSearch(arr, n - 1, x); if (index == -1) printf("Floor of %d doesn't exist in array ", x); else printf("Floor of %d is %d", x, arr[index]); return 0;} // Java program to find floor of// a given number in a sorted arrayimport java.io.*;import java.util.*;import java.lang.*; class GFG { /* An inefficient function to get index of floorof x in arr[0..n-1] */ static int floorSearch( int arr[], int n, int x) { // If last element is smaller than x if (x >= arr[n - 1]) return n - 1; // If first element is greater than x if (x < arr[0]) return -1; // Linearly search for the first element // greater than x for (int i = 1; i < n; i++) if (arr[i] > x) return (i - 1); return -1; } // Driver Code public static void main(String[] args) { int arr[] = { 1, 2, 4, 6, 10, 12, 14 }; int n = arr.length; int x = 7; int index = floorSearch(arr, n - 1, x); if (index == -1) System.out.print( "Floor of " + x + " doesn't exist in array "); else System.out.print( "Floor of " + x + " is " + arr[index]); }} // This code is contributed// by Akanksha Rai(Abby_akku) # Python3 program to find floor of a# given number in a sorted array # Function to get index of floor# of x in arr[low..high]def floorSearch(arr, low, high, x): # If low and high cross each other if (low > high): return -1 # If last element is smaller than x if (x >= arr[high]): return high # Find the middle point mid = int((low + high) / 2) # If middle point is floor. if (arr[mid] == x): return mid # If x lies between mid-1 and mid if (mid > 0 and arr[mid-1] <= x and x < arr[mid]): return mid - 1 # If x is smaller than mid, # floor must be in left half. if (x < arr[mid]): return floorSearch(arr, low, mid-1, x) # If mid-1 is not floor and x is greater than # arr[mid], return floorSearch(arr, mid + 1, high, x) # Driver Codearr = [1, 2, 4, 6, 10, 12, 14]n = len(arr)x = 7index = floorSearch(arr, 0, n-1, x) if (index == -1): print("Floor of", x, "doesn't exist \ in array ", end = "")else: print("Floor of", x, "is", arr[index]) # This code is contributed by Smitha Dinesh Semwal. // C# program to find floor of a given number// in a sorted arrayusing System; class GFG { /* An inefficient function to get index of floorof x in arr[0..n-1] */ static int floorSearch(int[] arr, int n, int x) { // If last element is smaller than x if (x >= arr[n - 1]) return n - 1; // If first element is greater than x if (x < arr[0]) return -1; // Linearly search for the first element // greater than x for (int i = 1; i < n; i++) if (arr[i] > x) return (i - 1); return -1; } // Driver Code static void Main() { int[] arr = { 1, 2, 4, 6, 10, 12, 14 }; int n = arr.Length; int x = 7; int index = floorSearch(arr, n - 1, x); if (index == -1) Console.WriteLine("Floor of " + x + " doesn't exist in array "); else Console.WriteLine("Floor of " + x + " is " + arr[index]); }} // This code is contributed// by mits <?php// PHP program to find floor of// a given number in a sorted array /* An inefficient function to get index of floor of x in arr[0..n-1] */ function floorSearch($arr, $n, $x){ // If last element is smaller // than x if ($x >= $arr[$n - 1]) return $n - 1; // If first element is greater // than x if ($x < $arr[0]) return -1; // Linearly search for the // first element greater than x for ($i = 1; $i < $n; $i++) if ($arr[$i] > $x) return ($i - 1); return -1;} // Driver Code$arr = array (1, 2, 4, 6, 10, 12, 14);$n = sizeof($arr);$x = 7;$index = floorSearch($arr, $n - 1, $x);if ($index == -1) echo "Floor of ", $x, "doesn't exist in array ";else echo "Floor of ", $x, " is ", $arr[$index]; // This code is contributed by ajit?> <script> // JavaScript program to find floor of// a given number in a sorted array /* An inefficient function to get index of floorof x in arr[0..n-1] */ function floorSearch(arr, n, x) { // If last element is smaller than x if (x >= arr[n - 1]) return n - 1; // If first element is greater than x if (x < arr[0]) return -1; // Linearly search for the first element // greater than x for (let i = 1; i < n; i++) if (arr[i] > x) return (i - 1); return -1; } // Driver Code let arr = [ 1, 2, 4, 6, 10, 12, 14 ]; let n = arr.length; let x = 7; let index = floorSearch(arr, n - 1, x); if (index == -1) document.write( "Floor of " + x + " doesn't exist in array "); else document.write( "Floor of " + x + " is " + arr[index]); </script> Output: Floor of 7 is 6. Complexity Analysis: Time Complexity : O(n). To traverse an array only one loop is needed so the time complexity is O(n). Space Complexity: O(1). No extra space is required, So the space complexity is constant Efficient MethodApproach:There is a catch in the problem, the given array is sorted. The idea is to use Binary Search to find the floor of a number x in a sorted array by comparing it to the middle element and dividing the search space into half. Algorithm: The algorithm can be implemented recursively or through iteration, but the basic idea remains the same.There is some base cases to handle. If there is no number greater than x then print the last elementIf the first number is greater than x then print -1create three variables low = 0, mid and high = n-1 and another variable to store the answerRun a loop or recurse until and unless low is less than or equal to high.check if the middle ( (low + high) /2) element is less than x, if yes then update the low, i.elow = mid + 1, and update answer with the middle element. In this step we are reducing the search space to half.Else update the high , i.e high = mid – 1Print the answer. The algorithm can be implemented recursively or through iteration, but the basic idea remains the same. There is some base cases to handle. If there is no number greater than x then print the last elementIf the first number is greater than x then print -1 If there is no number greater than x then print the last elementIf the first number is greater than x then print -1 If there is no number greater than x then print the last element If the first number is greater than x then print -1 create three variables low = 0, mid and high = n-1 and another variable to store the answer Run a loop or recurse until and unless low is less than or equal to high. check if the middle ( (low + high) /2) element is less than x, if yes then update the low, i.elow = mid + 1, and update answer with the middle element. In this step we are reducing the search space to half. Else update the high , i.e high = mid – 1 Print the answer. C++ C Java Python3 C# Javascript // A C/C++ program to find floor// of a given number in a sorted array#include <iostream>using namespace std; /* Function to get index of floor of x in arr[low..high] */int floorSearch(int arr[], int low, int high, int x){ // If low and high cross each other if (low > high) return -1; // If last element is smaller than x if (x >= arr[high]) return high; // Find the middle point int mid = (low + high) / 2; // If middle point is floor. if (arr[mid] == x) return mid; // If x lies between mid-1 and mid if (mid > 0 && arr[mid - 1] <= x && x < arr[mid]) return mid - 1; // If x is smaller than mid, floor // must be in left half. if (x < arr[mid]) return floorSearch( arr, low, mid - 1, x); // If mid-1 is not floor and x is // greater than arr[mid], return floorSearch(arr, mid + 1, high, x);} /* Driver program to check above functions */int main(){ int arr[] = { 1, 2, 4, 6, 10, 12, 14 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 7; int index = floorSearch(arr, 0, n - 1, x); if (index == -1) cout<< "Floor of " <<x <<" doesn't exist in array "; else cout<<"Floor of "<< x <<" is " << arr[index]; return 0;} // this code is contributed by shivanisinghss2110 // A C/C++ program to find floor// of a given number in a sorted array#include <stdio.h> /* Function to get index of floor of x in arr[low..high] */int floorSearch(int arr[], int low, int high, int x){ // If low and high cross each other if (low > high) return -1; // If last element is smaller than x if (x >= arr[high]) return high; // Find the middle point int mid = (low + high) / 2; // If middle point is floor. if (arr[mid] == x) return mid; // If x lies between mid-1 and mid if (mid > 0 && arr[mid - 1] <= x && x < arr[mid]) return mid - 1; // If x is smaller than mid, floor // must be in left half. if (x < arr[mid]) return floorSearch( arr, low, mid - 1, x); // If mid-1 is not floor and x is // greater than arr[mid], return floorSearch(arr, mid + 1, high, x);} /* Driver program to check above functions */int main(){ int arr[] = { 1, 2, 4, 6, 10, 12, 14 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 7; int index = floorSearch(arr, 0, n - 1, x); if (index == -1) printf( "Floor of %d doesn't exist in array ", x); else printf( "Floor of %d is %d", x, arr[index]); return 0;} // Java program to find floor of// a given number in a sorted arrayimport java.io.*; class GFG { /* Function to get index of floor of x in arr[low..high] */ static int floorSearch( int arr[], int low, int high, int x) { // If low and high cross each other if (low > high) return -1; // If last element is smaller than x if (x >= arr[high]) return high; // Find the middle point int mid = (low + high) / 2; // If middle point is floor. if (arr[mid] == x) return mid; // If x lies between mid-1 and mid if ( mid > 0 && arr[mid - 1] <= x && x < arr[mid]) return mid - 1; // If x is smaller than mid, floor // must be in left half. if (x < arr[mid]) return floorSearch( arr, low, mid - 1, x); // If mid-1 is not floor and x is // greater than arr[mid], return floorSearch( arr, mid + 1, high, x); } /* Driver program to check above functions */ public static void main(String[] args) { int arr[] = { 1, 2, 4, 6, 10, 12, 14 }; int n = arr.length; int x = 7; int index = floorSearch( arr, 0, n - 1, x); if (index == -1) System.out.println( "Floor of " + x + " dosen't exist in array "); else System.out.println( "Floor of " + x + " is " + arr[index]); }}// This code is contributed by Prerna Saini # Python3 program to find floor of a # given number in a sorted array # Function to get index of floor# of x in arr[low..high]def floorSearch(arr, low, high, x): # If low and high cross each other if (low > high): return -1 # If last element is smaller than x if (x >= arr[high]): return high # Find the middle point mid = int((low + high) / 2) # If middle point is floor. if (arr[mid] == x): return mid # If x lies between mid-1 and mid if (mid > 0 and arr[mid-1] <= x and x < arr[mid]): return mid - 1 # If x is smaller than mid, # floor must be in left half. if (x < arr[mid]): return floorSearch(arr, low, mid-1, x) # If mid-1 is not floor and x is greater than # arr[mid], return floorSearch(arr, mid + 1, high, x) # Driver Codearr = [1, 2, 4, 6, 10, 12, 14]n = len(arr)x = 7index = floorSearch(arr, 0, n-1, x) if (index == -1): print("Floor of", x, "doesn't exist\ in array ", end = "")else: print("Floor of", x, "is", arr[index]) # This code is contributed by Smitha Dinesh Semwal. // C# program to find floor of// a given number in a sorted arrayusing System; class GFG { /* Function to get index of floor of x in arr[low..high] */ static int floorSearch( int[] arr, int low, int high, int x) { // If low and high cross each other if (low > high) return -1; // If last element is smaller than x if (x >= arr[high]) return high; // Find the middle point int mid = (low + high) / 2; // If middle point is floor. if (arr[mid] == x) return mid; // If x lies between mid-1 and mid if (mid > 0 && arr[mid - 1] <= x && x < arr[mid]) return mid - 1; // If x is smaller than mid, floor // must be in left half. if (x < arr[mid]) return floorSearch(arr, low, mid - 1, x); // If mid-1 is not floor and x is // greater than arr[mid], return floorSearch(arr, mid + 1, high, x); } /* Driver program to check above functions */ public static void Main() { int[] arr = { 1, 2, 4, 6, 10, 12, 14 }; int n = arr.Length; int x = 7; int index = floorSearch(arr, 0, n - 1, x); if (index == -1) Console.Write("Floor of " + x + " dosen't exist in array "); else Console.Write("Floor of " + x + " is " + arr[index]); }} // This code is contributed by nitin mittal. <script> // javascript program to find floor of// a given number in a sorted array /* Function to get index of floor of x inarr[low..high] */function floorSearch( arr , low, high , x){ // If low and high cross each other if (low > high) return -1; // If last element is smaller than x if (x >= arr[high]) return high; // Find the middle point var mid = (low + high) / 2; // If middle point is floor. if (arr[mid] == x) return mid; // If x lies between mid-1 and mid if ( mid > 0 && arr[mid - 1] <= x && x < arr[mid]) return mid - 1; // If x is smaller than mid, floor // must be in left half. if (x < arr[mid]) return floorSearch( arr, low, mid - 1, x); // If mid-1 is not floor and x is // greater than arr[mid], return floorSearch( arr, mid + 1, high, x);} /* Driver program to check above functions */var arr = [ 1, 2, 4, 6, 10, 12, 14 ];var n = arr.length;var x = 7;var index = floorSearch( arr, 0, n - 1, x);if (index == -1) document.write( "Floor of " + x + " dosen't exist in array ");else document.write( "Floor of " + x + " is " + arr[index]); // This code is contributed by Amit Katiyar</script> Output: Floor of 7 is 6. Complexity Analysis: Time Complexity : O(log n). To run a binary search, the time complexity required is O(log n). Space Complexity: O(1). As no extra space is required, so the space complexity is constant. This article is contributed by Mayank Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nitin mittal jit_t Akanksha_Rai Mithun Kumar andrew1234 code_hunt amit143katiyar simranarora5sos shivanisinghss2110 adityakumar129 Amazon Binary Search Divide and Conquer Searching Amazon Searching Divide and Conquer Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge Sort QuickSort Binary Search Count Inversions in an array | Set 1 (Using Merge Sort) Median of two sorted arrays of different sizes Binary Search Linear Search K'th Smallest/Largest Element in Unsorted Array | Set 1 Search an element in a sorted and rotated array Find the Missing Number
[ { "code": null, "e": 52, "s": 24, "text": "\n16 Feb, 2022" }, { "code": null, "e": 220, "s": 52, "text": "Given a sorted array and a value x, the floor of x is the largest element in array smaller than or equal to x. Write efficient functions to find floor of x.Examples: " }, { "code": null, "e": 549, "s": 220, "text": "Input : arr[] = {1, 2, 8, 10, 10, 12, 19}, x = 5\nOutput : 2\n2 is the largest element in \narr[] smaller than 5.\n\nInput : arr[] = {1, 2, 8, 10, 10, 12, 19}, x = 20\nOutput : 19\n19 is the largest element in\narr[] smaller than 20.\n\nInput : arr[] = {1, 2, 8, 10, 10, 12, 19}, x = 0\nOutput : -1\nSince floor doesn't exist,\noutput is -1." }, { "code": null, "e": 737, "s": 551, "text": "Simple MethodApproach: The idea is simple, traverse through the array and find the first element greater than x. The element just before the found element is the floor of x.Algorithm: " }, { "code": null, "e": 984, "s": 737, "text": "Traverse through the array from start to end.If the current element is greater than x print the previous number and break the loop.If there is no number greater than x then print the last elementIf the first number is greater than x then print -1" }, { "code": null, "e": 1030, "s": 984, "text": "Traverse through the array from start to end." }, { "code": null, "e": 1117, "s": 1030, "text": "If the current element is greater than x print the previous number and break the loop." }, { "code": null, "e": 1182, "s": 1117, "text": "If there is no number greater than x then print the last element" }, { "code": null, "e": 1234, "s": 1182, "text": "If the first number is greater than x then print -1" }, { "code": null, "e": 1240, "s": 1236, "text": "C++" }, { "code": null, "e": 1242, "s": 1240, "text": "C" }, { "code": null, "e": 1247, "s": 1242, "text": "Java" }, { "code": null, "e": 1255, "s": 1247, "text": "Python3" }, { "code": null, "e": 1258, "s": 1255, "text": "C#" }, { "code": null, "e": 1262, "s": 1258, "text": "PHP" }, { "code": null, "e": 1273, "s": 1262, "text": "Javascript" }, { "code": "// C++ program to find floor of a given number// in a sorted array#include <iostream>using namespace std; /* An inefficient function to getindex of floor of x in arr[0..n-1] */int floorSearch(int arr[], int n, int x){ // If last element is smaller than x if (x >= arr[n - 1]) return n - 1; // If first element is greater than x if (x < arr[0]) return -1; // Linearly search for the first element // greater than x for (int i = 1; i < n; i++) if (arr[i] > x) return (i - 1); return -1;} /* Driver program to check above functions */int main(){ int arr[] = { 1, 2, 4, 6, 10, 12, 14 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 7; int index = floorSearch(arr, n - 1, x); if (index == -1) cout<<\"Floor of \"<<x <<\" doesn't exist in array \"; else cout<<\"Floor of \"<< x <<\" is \" << arr[index]; return 0;} // This code is contributed by shivanisinghss2110", "e": 2219, "s": 1273, "text": null }, { "code": "// C/C++ program to find floor of a given number// in a sorted array#include <stdio.h> /* An inefficient function to getindex of floor of x in arr[0..n-1] */int floorSearch(int arr[], int n, int x){ // If last element is smaller than x if (x >= arr[n - 1]) return n - 1; // If first element is greater than x if (x < arr[0]) return -1; // Linearly search for the first element // greater than x for (int i = 1; i < n; i++) if (arr[i] > x) return (i - 1); return -1;} /* Driver program to check above functions */int main(){ int arr[] = { 1, 2, 4, 6, 10, 12, 14 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 7; int index = floorSearch(arr, n - 1, x); if (index == -1) printf(\"Floor of %d doesn't exist in array \", x); else printf(\"Floor of %d is %d\", x, arr[index]); return 0;}", "e": 3093, "s": 2219, "text": null }, { "code": "// Java program to find floor of// a given number in a sorted arrayimport java.io.*;import java.util.*;import java.lang.*; class GFG { /* An inefficient function to get index of floorof x in arr[0..n-1] */ static int floorSearch( int arr[], int n, int x) { // If last element is smaller than x if (x >= arr[n - 1]) return n - 1; // If first element is greater than x if (x < arr[0]) return -1; // Linearly search for the first element // greater than x for (int i = 1; i < n; i++) if (arr[i] > x) return (i - 1); return -1; } // Driver Code public static void main(String[] args) { int arr[] = { 1, 2, 4, 6, 10, 12, 14 }; int n = arr.length; int x = 7; int index = floorSearch(arr, n - 1, x); if (index == -1) System.out.print( \"Floor of \" + x + \" doesn't exist in array \"); else System.out.print( \"Floor of \" + x + \" is \" + arr[index]); }} // This code is contributed// by Akanksha Rai(Abby_akku)", "e": 4255, "s": 3093, "text": null }, { "code": "# Python3 program to find floor of a# given number in a sorted array # Function to get index of floor# of x in arr[low..high]def floorSearch(arr, low, high, x): # If low and high cross each other if (low > high): return -1 # If last element is smaller than x if (x >= arr[high]): return high # Find the middle point mid = int((low + high) / 2) # If middle point is floor. if (arr[mid] == x): return mid # If x lies between mid-1 and mid if (mid > 0 and arr[mid-1] <= x and x < arr[mid]): return mid - 1 # If x is smaller than mid, # floor must be in left half. if (x < arr[mid]): return floorSearch(arr, low, mid-1, x) # If mid-1 is not floor and x is greater than # arr[mid], return floorSearch(arr, mid + 1, high, x) # Driver Codearr = [1, 2, 4, 6, 10, 12, 14]n = len(arr)x = 7index = floorSearch(arr, 0, n-1, x) if (index == -1): print(\"Floor of\", x, \"doesn't exist \\ in array \", end = \"\")else: print(\"Floor of\", x, \"is\", arr[index]) # This code is contributed by Smitha Dinesh Semwal.", "e": 5375, "s": 4255, "text": null }, { "code": "// C# program to find floor of a given number// in a sorted arrayusing System; class GFG { /* An inefficient function to get index of floorof x in arr[0..n-1] */ static int floorSearch(int[] arr, int n, int x) { // If last element is smaller than x if (x >= arr[n - 1]) return n - 1; // If first element is greater than x if (x < arr[0]) return -1; // Linearly search for the first element // greater than x for (int i = 1; i < n; i++) if (arr[i] > x) return (i - 1); return -1; } // Driver Code static void Main() { int[] arr = { 1, 2, 4, 6, 10, 12, 14 }; int n = arr.Length; int x = 7; int index = floorSearch(arr, n - 1, x); if (index == -1) Console.WriteLine(\"Floor of \" + x + \" doesn't exist in array \"); else Console.WriteLine(\"Floor of \" + x + \" is \" + arr[index]); }} // This code is contributed// by mits", "e": 6386, "s": 5375, "text": null }, { "code": "<?php// PHP program to find floor of// a given number in a sorted array /* An inefficient function to get index of floor of x in arr[0..n-1] */ function floorSearch($arr, $n, $x){ // If last element is smaller // than x if ($x >= $arr[$n - 1]) return $n - 1; // If first element is greater // than x if ($x < $arr[0]) return -1; // Linearly search for the // first element greater than x for ($i = 1; $i < $n; $i++) if ($arr[$i] > $x) return ($i - 1); return -1;} // Driver Code$arr = array (1, 2, 4, 6, 10, 12, 14);$n = sizeof($arr);$x = 7;$index = floorSearch($arr, $n - 1, $x);if ($index == -1) echo \"Floor of \", $x, \"doesn't exist in array \";else echo \"Floor of \", $x, \" is \", $arr[$index]; // This code is contributed by ajit?>", "e": 7206, "s": 6386, "text": null }, { "code": "<script> // JavaScript program to find floor of// a given number in a sorted array /* An inefficient function to get index of floorof x in arr[0..n-1] */ function floorSearch(arr, n, x) { // If last element is smaller than x if (x >= arr[n - 1]) return n - 1; // If first element is greater than x if (x < arr[0]) return -1; // Linearly search for the first element // greater than x for (let i = 1; i < n; i++) if (arr[i] > x) return (i - 1); return -1; } // Driver Code let arr = [ 1, 2, 4, 6, 10, 12, 14 ]; let n = arr.length; let x = 7; let index = floorSearch(arr, n - 1, x); if (index == -1) document.write( \"Floor of \" + x + \" doesn't exist in array \"); else document.write( \"Floor of \" + x + \" is \" + arr[index]); </script>", "e": 8215, "s": 7206, "text": null }, { "code": null, "e": 8224, "s": 8215, "text": "Output: " }, { "code": null, "e": 8241, "s": 8224, "text": "Floor of 7 is 6." }, { "code": null, "e": 8264, "s": 8241, "text": "Complexity Analysis: " }, { "code": null, "e": 8365, "s": 8264, "text": "Time Complexity : O(n). To traverse an array only one loop is needed so the time complexity is O(n)." }, { "code": null, "e": 8453, "s": 8365, "text": "Space Complexity: O(1). No extra space is required, So the space complexity is constant" }, { "code": null, "e": 8715, "s": 8453, "text": " Efficient MethodApproach:There is a catch in the problem, the given array is sorted. The idea is to use Binary Search to find the floor of a number x in a sorted array by comparing it to the middle element and dividing the search space into half. Algorithm: " }, { "code": null, "e": 9398, "s": 8715, "text": "The algorithm can be implemented recursively or through iteration, but the basic idea remains the same.There is some base cases to handle. If there is no number greater than x then print the last elementIf the first number is greater than x then print -1create three variables low = 0, mid and high = n-1 and another variable to store the answerRun a loop or recurse until and unless low is less than or equal to high.check if the middle ( (low + high) /2) element is less than x, if yes then update the low, i.elow = mid + 1, and update answer with the middle element. In this step we are reducing the search space to half.Else update the high , i.e high = mid – 1Print the answer." }, { "code": null, "e": 9502, "s": 9398, "text": "The algorithm can be implemented recursively or through iteration, but the basic idea remains the same." }, { "code": null, "e": 9654, "s": 9502, "text": "There is some base cases to handle. If there is no number greater than x then print the last elementIf the first number is greater than x then print -1" }, { "code": null, "e": 9770, "s": 9654, "text": "If there is no number greater than x then print the last elementIf the first number is greater than x then print -1" }, { "code": null, "e": 9835, "s": 9770, "text": "If there is no number greater than x then print the last element" }, { "code": null, "e": 9887, "s": 9835, "text": "If the first number is greater than x then print -1" }, { "code": null, "e": 9979, "s": 9887, "text": "create three variables low = 0, mid and high = n-1 and another variable to store the answer" }, { "code": null, "e": 10053, "s": 9979, "text": "Run a loop or recurse until and unless low is less than or equal to high." }, { "code": null, "e": 10260, "s": 10053, "text": "check if the middle ( (low + high) /2) element is less than x, if yes then update the low, i.elow = mid + 1, and update answer with the middle element. In this step we are reducing the search space to half." }, { "code": null, "e": 10302, "s": 10260, "text": "Else update the high , i.e high = mid – 1" }, { "code": null, "e": 10320, "s": 10302, "text": "Print the answer." }, { "code": null, "e": 10326, "s": 10322, "text": "C++" }, { "code": null, "e": 10328, "s": 10326, "text": "C" }, { "code": null, "e": 10333, "s": 10328, "text": "Java" }, { "code": null, "e": 10341, "s": 10333, "text": "Python3" }, { "code": null, "e": 10344, "s": 10341, "text": "C#" }, { "code": null, "e": 10355, "s": 10344, "text": "Javascript" }, { "code": "// A C/C++ program to find floor// of a given number in a sorted array#include <iostream>using namespace std; /* Function to get index of floor of x in arr[low..high] */int floorSearch(int arr[], int low, int high, int x){ // If low and high cross each other if (low > high) return -1; // If last element is smaller than x if (x >= arr[high]) return high; // Find the middle point int mid = (low + high) / 2; // If middle point is floor. if (arr[mid] == x) return mid; // If x lies between mid-1 and mid if (mid > 0 && arr[mid - 1] <= x && x < arr[mid]) return mid - 1; // If x is smaller than mid, floor // must be in left half. if (x < arr[mid]) return floorSearch( arr, low, mid - 1, x); // If mid-1 is not floor and x is // greater than arr[mid], return floorSearch(arr, mid + 1, high, x);} /* Driver program to check above functions */int main(){ int arr[] = { 1, 2, 4, 6, 10, 12, 14 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 7; int index = floorSearch(arr, 0, n - 1, x); if (index == -1) cout<< \"Floor of \" <<x <<\" doesn't exist in array \"; else cout<<\"Floor of \"<< x <<\" is \" << arr[index]; return 0;} // this code is contributed by shivanisinghss2110", "e": 11680, "s": 10355, "text": null }, { "code": "// A C/C++ program to find floor// of a given number in a sorted array#include <stdio.h> /* Function to get index of floor of x in arr[low..high] */int floorSearch(int arr[], int low, int high, int x){ // If low and high cross each other if (low > high) return -1; // If last element is smaller than x if (x >= arr[high]) return high; // Find the middle point int mid = (low + high) / 2; // If middle point is floor. if (arr[mid] == x) return mid; // If x lies between mid-1 and mid if (mid > 0 && arr[mid - 1] <= x && x < arr[mid]) return mid - 1; // If x is smaller than mid, floor // must be in left half. if (x < arr[mid]) return floorSearch( arr, low, mid - 1, x); // If mid-1 is not floor and x is // greater than arr[mid], return floorSearch(arr, mid + 1, high, x);} /* Driver program to check above functions */int main(){ int arr[] = { 1, 2, 4, 6, 10, 12, 14 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 7; int index = floorSearch(arr, 0, n - 1, x); if (index == -1) printf( \"Floor of %d doesn't exist in array \", x); else printf( \"Floor of %d is %d\", x, arr[index]); return 0;}", "e": 12953, "s": 11680, "text": null }, { "code": "// Java program to find floor of// a given number in a sorted arrayimport java.io.*; class GFG { /* Function to get index of floor of x in arr[low..high] */ static int floorSearch( int arr[], int low, int high, int x) { // If low and high cross each other if (low > high) return -1; // If last element is smaller than x if (x >= arr[high]) return high; // Find the middle point int mid = (low + high) / 2; // If middle point is floor. if (arr[mid] == x) return mid; // If x lies between mid-1 and mid if ( mid > 0 && arr[mid - 1] <= x && x < arr[mid]) return mid - 1; // If x is smaller than mid, floor // must be in left half. if (x < arr[mid]) return floorSearch( arr, low, mid - 1, x); // If mid-1 is not floor and x is // greater than arr[mid], return floorSearch( arr, mid + 1, high, x); } /* Driver program to check above functions */ public static void main(String[] args) { int arr[] = { 1, 2, 4, 6, 10, 12, 14 }; int n = arr.length; int x = 7; int index = floorSearch( arr, 0, n - 1, x); if (index == -1) System.out.println( \"Floor of \" + x + \" dosen't exist in array \"); else System.out.println( \"Floor of \" + x + \" is \" + arr[index]); }}// This code is contributed by Prerna Saini", "e": 14540, "s": 12953, "text": null }, { "code": "# Python3 program to find floor of a # given number in a sorted array # Function to get index of floor# of x in arr[low..high]def floorSearch(arr, low, high, x): # If low and high cross each other if (low > high): return -1 # If last element is smaller than x if (x >= arr[high]): return high # Find the middle point mid = int((low + high) / 2) # If middle point is floor. if (arr[mid] == x): return mid # If x lies between mid-1 and mid if (mid > 0 and arr[mid-1] <= x and x < arr[mid]): return mid - 1 # If x is smaller than mid, # floor must be in left half. if (x < arr[mid]): return floorSearch(arr, low, mid-1, x) # If mid-1 is not floor and x is greater than # arr[mid], return floorSearch(arr, mid + 1, high, x) # Driver Codearr = [1, 2, 4, 6, 10, 12, 14]n = len(arr)x = 7index = floorSearch(arr, 0, n-1, x) if (index == -1): print(\"Floor of\", x, \"doesn't exist\\ in array \", end = \"\")else: print(\"Floor of\", x, \"is\", arr[index]) # This code is contributed by Smitha Dinesh Semwal.", "e": 15661, "s": 14540, "text": null }, { "code": "// C# program to find floor of// a given number in a sorted arrayusing System; class GFG { /* Function to get index of floor of x in arr[low..high] */ static int floorSearch( int[] arr, int low, int high, int x) { // If low and high cross each other if (low > high) return -1; // If last element is smaller than x if (x >= arr[high]) return high; // Find the middle point int mid = (low + high) / 2; // If middle point is floor. if (arr[mid] == x) return mid; // If x lies between mid-1 and mid if (mid > 0 && arr[mid - 1] <= x && x < arr[mid]) return mid - 1; // If x is smaller than mid, floor // must be in left half. if (x < arr[mid]) return floorSearch(arr, low, mid - 1, x); // If mid-1 is not floor and x is // greater than arr[mid], return floorSearch(arr, mid + 1, high, x); } /* Driver program to check above functions */ public static void Main() { int[] arr = { 1, 2, 4, 6, 10, 12, 14 }; int n = arr.Length; int x = 7; int index = floorSearch(arr, 0, n - 1, x); if (index == -1) Console.Write(\"Floor of \" + x + \" dosen't exist in array \"); else Console.Write(\"Floor of \" + x + \" is \" + arr[index]); }} // This code is contributed by nitin mittal.", "e": 17188, "s": 15661, "text": null }, { "code": "<script> // javascript program to find floor of// a given number in a sorted array /* Function to get index of floor of x inarr[low..high] */function floorSearch( arr , low, high , x){ // If low and high cross each other if (low > high) return -1; // If last element is smaller than x if (x >= arr[high]) return high; // Find the middle point var mid = (low + high) / 2; // If middle point is floor. if (arr[mid] == x) return mid; // If x lies between mid-1 and mid if ( mid > 0 && arr[mid - 1] <= x && x < arr[mid]) return mid - 1; // If x is smaller than mid, floor // must be in left half. if (x < arr[mid]) return floorSearch( arr, low, mid - 1, x); // If mid-1 is not floor and x is // greater than arr[mid], return floorSearch( arr, mid + 1, high, x);} /* Driver program to check above functions */var arr = [ 1, 2, 4, 6, 10, 12, 14 ];var n = arr.length;var x = 7;var index = floorSearch( arr, 0, n - 1, x);if (index == -1) document.write( \"Floor of \" + x + \" dosen't exist in array \");else document.write( \"Floor of \" + x + \" is \" + arr[index]); // This code is contributed by Amit Katiyar</script>", "e": 18458, "s": 17188, "text": null }, { "code": null, "e": 18468, "s": 18458, "text": "Output: " }, { "code": null, "e": 18485, "s": 18468, "text": "Floor of 7 is 6." }, { "code": null, "e": 18508, "s": 18485, "text": "Complexity Analysis: " }, { "code": null, "e": 18602, "s": 18508, "text": "Time Complexity : O(log n). To run a binary search, the time complexity required is O(log n)." }, { "code": null, "e": 18694, "s": 18602, "text": "Space Complexity: O(1). As no extra space is required, so the space complexity is constant." }, { "code": null, "e": 19117, "s": 18694, "text": "This article is contributed by Mayank Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 19130, "s": 19117, "text": "nitin mittal" }, { "code": null, "e": 19136, "s": 19130, "text": "jit_t" }, { "code": null, "e": 19149, "s": 19136, "text": "Akanksha_Rai" }, { "code": null, "e": 19162, "s": 19149, "text": "Mithun Kumar" }, { "code": null, "e": 19173, "s": 19162, "text": "andrew1234" }, { "code": null, "e": 19183, "s": 19173, "text": "code_hunt" }, { "code": null, "e": 19198, "s": 19183, "text": "amit143katiyar" }, { "code": null, "e": 19214, "s": 19198, "text": "simranarora5sos" }, { "code": null, "e": 19233, "s": 19214, "text": "shivanisinghss2110" }, { "code": null, "e": 19248, "s": 19233, "text": "adityakumar129" }, { "code": null, "e": 19255, "s": 19248, "text": "Amazon" }, { "code": null, "e": 19269, "s": 19255, "text": "Binary Search" }, { "code": null, "e": 19288, "s": 19269, "text": "Divide and Conquer" }, { "code": null, "e": 19298, "s": 19288, "text": "Searching" }, { "code": null, "e": 19305, "s": 19298, "text": "Amazon" }, { "code": null, "e": 19315, "s": 19305, "text": "Searching" }, { "code": null, "e": 19334, "s": 19315, "text": "Divide and Conquer" }, { "code": null, "e": 19348, "s": 19334, "text": "Binary Search" }, { "code": null, "e": 19446, "s": 19348, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 19457, "s": 19446, "text": "Merge Sort" }, { "code": null, "e": 19467, "s": 19457, "text": "QuickSort" }, { "code": null, "e": 19481, "s": 19467, "text": "Binary Search" }, { "code": null, "e": 19537, "s": 19481, "text": "Count Inversions in an array | Set 1 (Using Merge Sort)" }, { "code": null, "e": 19584, "s": 19537, "text": "Median of two sorted arrays of different sizes" }, { "code": null, "e": 19598, "s": 19584, "text": "Binary Search" }, { "code": null, "e": 19612, "s": 19598, "text": "Linear Search" }, { "code": null, "e": 19668, "s": 19612, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" }, { "code": null, "e": 19716, "s": 19668, "text": "Search an element in a sorted and rotated array" } ]
Count of triangles with total n points with m collinear
20 May, 2022 There are ‘n’ points in a plane, out of which ‘m’ points are co-linear. Find the number of triangles formed by the points as vertices ?Examples : Input : n = 5, m = 4 Output : 6 Out of five points, four points are collinear, we can make 6 triangles. We can choose any 2 points from 4 collinear points and use the single point as 3rd point. So total count is 4C2 = 6 Input : n = 10, m = 4 Output : 116 Number of triangles = nC3 – mC3How does this formula work? Consider the second example above. There are 10 points, out of which 4 collinear. A triangle will be formed by any three of these ten points. Thus forming a triangle amounts to selecting any three of the 10 points. Three points can be selected out of the 10 points in nC3 ways. Number of triangles formed by 10 points when no 3 of them are co-linear = 10C3......(i) Similarly, the number of triangles formed by 4 points when no 3 of them are co-linear = 4C3........(ii)Since triangle formed by these 4 points are not valid, required number of triangles formed = 10C3 – 4C3 = 120 – 4 = 116 C++ Java Python3 C# PHP Javascript // CPP program to count number of triangles// with n total points, out of which m are// collinear.#include <bits/stdc++.h>using namespace std; // Returns value of binomial coefficient// Code taken from https://goo.gl/vhy4jpint nCk(int n, int k){ int C[k+1]; memset(C, 0, sizeof(C)); C[0] = 1; // nC0 is 1 for (int i = 1; i <= n; i++) { // Compute next row of pascal triangle // using the previous row for (int j = min(i, k); j > 0; j--) C[j] = C[j] + C[j-1]; } return C[k];} /* function to calculate number of triangle can be formed */int countTriangles(int n,int m){ return (nCk(n, 3) - nCk(m, 3));} /* driver function*/int main(){ int n = 5, m = 4; cout << countTriangles(n, m); return 0;} //Java program to count number of triangles// with n total points, out of which m are// collinear.import java.io.*;import java.util.*; class GFG { // Returns value of binomial coefficient// Code taken from https://goo.gl/vhy4jpstatic int nCk(int n, int k){ int[] C=new int[k+1]; for (int i=0;i<=k;i++) C[i]=0; C[0] = 1; // nC0 is 1 for (int i = 1; i <= n; i++) { // Compute next row of pascal triangle // using the previous row for (int j = Math.min(i, k); j > 0; j--) C[j] = C[j] + C[j-1]; } return C[k];} /* function to calculate number of trianglecan be formed */static int countTriangles(int n,int m){ return (nCk(n, 3) - nCk(m, 3));} public static void main (String[] args) { int n = 5, m = 4; System.out.println(countTriangles(n, m)); }} //This code is contributed by Gitanjali. # python program to count number of triangles# with n total points, out of which m are# collinear.import math # Returns value of binomial coefficient# Code taken from https://goo.gl / vhy4jpdef nCk(n, k): C = [0 for i in range(0, k + 2)] C[0] = 1; # nC0 is 1 for i in range(0, n + 1): # Compute next row of pascal triangle # using the previous row for j in range(min(i, k), 0, -1): C[j] = C[j] + C[j-1] return C[k] # function to calculate number of triangle# can be formeddef countTriangles(n, m): return (nCk(n, 3) - nCk(m, 3)) # driver coden = 5m = 4print (countTriangles(n, m)) # This code is contributed by Gitanjali //C# program to count number of triangles// with n total points, out of which m are// collinear.using System; class GFG { // Returns value of binomial coefficient // Code taken from https://goo.gl/vhy4jp static int nCk(int n, int k) { int[] C=new int[k+1]; for (int i = 0; i <= k; i++) C[i] = 0; // nC0 is 1 C[0] = 1; for (int i = 1; i <= n; i++) { // Compute next row of pascal triangle // using the previous row for (int j = Math.Min(i, k); j > 0; j--) C[j] = C[j] + C[j - 1]; } return C[k]; } /* function to calculate number of triangle can be formed */ static int countTriangles(int n,int m) { return (nCk(n, 3) - nCk(m, 3)); } // Driver code public static void Main () { int n = 5, m = 4; Console.WriteLine(countTriangles(n, m)); }} // This code is contributed by vt_m. <?php// PHP program to count number// of triangles with n total// points, out of which m are collinear. // Returns value of binomial coefficient// Code taken from https://goo.gl/vhy4jpfunction nCk($n, $k){ for ($i = 0; $i <= $k; $i++) $C[$i] = 0; $C[0] = 1; // nC0 is 1 for ($i = 1; $i <= $n; $i++) { // Compute next row of pascal // triangle using the previous row for ($j = min($i, $k); $j > 0; $j--) $C[$j] = $C[$j] + $C[$j - 1]; } return $C[$k];} /* function to calculate numberof triangles that can be formed */function countTriangles($n, $m){ return (nCk($n, 3) - nCk($m, 3));} // Driver Code$n = 5;$m = 4;echo countTriangles($n, $m);return 0; // This code is contributed by ChitraNayal?> <script> // Javascript program to count number of triangles // with n total points, out of which m are // collinear. // Returns value of binomial coefficient // Code taken from https://goo.gl/vhy4jp function nCk(n, k) { let C = new Array(k+1); C.fill(0); C[0] = 1; // nC0 is 1 for (let i = 1; i <= n; i++) { // Compute next row of pascal triangle // using the previous row for (let j = Math.min(i, k); j > 0; j--) C[j] = C[j] + C[j-1]; } return C[k]; } /* function to calculate number of triangle can be formed */ function countTriangles(n, m) { return (nCk(n, 3) - nCk(m, 3)); } let n = 5, m = 4; document.write(countTriangles(n, m)); // This code is contributed by divyesh072019.</script> Output : 6 ukasp divyesh072019 simmytarika5 triangle Combinatorial Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n20 May, 2022" }, { "code": null, "e": 200, "s": 52, "text": "There are ‘n’ points in a plane, out of which ‘m’ points are co-linear. Find the number of triangles formed by the points as vertices ?Examples : " }, { "code": null, "e": 459, "s": 200, "text": "Input : n = 5, m = 4\nOutput : 6\nOut of five points, four points are \ncollinear, we can make 6 triangles. We\ncan choose any 2 points from 4 collinear\npoints and use the single point as 3rd\npoint. So total count is 4C2 = 6\n\nInput : n = 10, m = 4\nOutput : 116" }, { "code": null, "e": 1112, "s": 463, "text": "Number of triangles = nC3 – mC3How does this formula work? Consider the second example above. There are 10 points, out of which 4 collinear. A triangle will be formed by any three of these ten points. Thus forming a triangle amounts to selecting any three of the 10 points. Three points can be selected out of the 10 points in nC3 ways. Number of triangles formed by 10 points when no 3 of them are co-linear = 10C3......(i) Similarly, the number of triangles formed by 4 points when no 3 of them are co-linear = 4C3........(ii)Since triangle formed by these 4 points are not valid, required number of triangles formed = 10C3 – 4C3 = 120 – 4 = 116 " }, { "code": null, "e": 1118, "s": 1114, "text": "C++" }, { "code": null, "e": 1123, "s": 1118, "text": "Java" }, { "code": null, "e": 1131, "s": 1123, "text": "Python3" }, { "code": null, "e": 1134, "s": 1131, "text": "C#" }, { "code": null, "e": 1138, "s": 1134, "text": "PHP" }, { "code": null, "e": 1149, "s": 1138, "text": "Javascript" }, { "code": "// CPP program to count number of triangles// with n total points, out of which m are// collinear.#include <bits/stdc++.h>using namespace std; // Returns value of binomial coefficient// Code taken from https://goo.gl/vhy4jpint nCk(int n, int k){ int C[k+1]; memset(C, 0, sizeof(C)); C[0] = 1; // nC0 is 1 for (int i = 1; i <= n; i++) { // Compute next row of pascal triangle // using the previous row for (int j = min(i, k); j > 0; j--) C[j] = C[j] + C[j-1]; } return C[k];} /* function to calculate number of triangle can be formed */int countTriangles(int n,int m){ return (nCk(n, 3) - nCk(m, 3));} /* driver function*/int main(){ int n = 5, m = 4; cout << countTriangles(n, m); return 0;}", "e": 1911, "s": 1149, "text": null }, { "code": "//Java program to count number of triangles// with n total points, out of which m are// collinear.import java.io.*;import java.util.*; class GFG { // Returns value of binomial coefficient// Code taken from https://goo.gl/vhy4jpstatic int nCk(int n, int k){ int[] C=new int[k+1]; for (int i=0;i<=k;i++) C[i]=0; C[0] = 1; // nC0 is 1 for (int i = 1; i <= n; i++) { // Compute next row of pascal triangle // using the previous row for (int j = Math.min(i, k); j > 0; j--) C[j] = C[j] + C[j-1]; } return C[k];} /* function to calculate number of trianglecan be formed */static int countTriangles(int n,int m){ return (nCk(n, 3) - nCk(m, 3));} public static void main (String[] args) { int n = 5, m = 4; System.out.println(countTriangles(n, m)); }} //This code is contributed by Gitanjali.", "e": 2779, "s": 1911, "text": null }, { "code": "# python program to count number of triangles# with n total points, out of which m are# collinear.import math # Returns value of binomial coefficient# Code taken from https://goo.gl / vhy4jpdef nCk(n, k): C = [0 for i in range(0, k + 2)] C[0] = 1; # nC0 is 1 for i in range(0, n + 1): # Compute next row of pascal triangle # using the previous row for j in range(min(i, k), 0, -1): C[j] = C[j] + C[j-1] return C[k] # function to calculate number of triangle# can be formeddef countTriangles(n, m): return (nCk(n, 3) - nCk(m, 3)) # driver coden = 5m = 4print (countTriangles(n, m)) # This code is contributed by Gitanjali", "e": 3465, "s": 2779, "text": null }, { "code": "//C# program to count number of triangles// with n total points, out of which m are// collinear.using System; class GFG { // Returns value of binomial coefficient // Code taken from https://goo.gl/vhy4jp static int nCk(int n, int k) { int[] C=new int[k+1]; for (int i = 0; i <= k; i++) C[i] = 0; // nC0 is 1 C[0] = 1; for (int i = 1; i <= n; i++) { // Compute next row of pascal triangle // using the previous row for (int j = Math.Min(i, k); j > 0; j--) C[j] = C[j] + C[j - 1]; } return C[k]; } /* function to calculate number of triangle can be formed */ static int countTriangles(int n,int m) { return (nCk(n, 3) - nCk(m, 3)); } // Driver code public static void Main () { int n = 5, m = 4; Console.WriteLine(countTriangles(n, m)); }} // This code is contributed by vt_m.", "e": 4440, "s": 3465, "text": null }, { "code": "<?php// PHP program to count number// of triangles with n total// points, out of which m are collinear. // Returns value of binomial coefficient// Code taken from https://goo.gl/vhy4jpfunction nCk($n, $k){ for ($i = 0; $i <= $k; $i++) $C[$i] = 0; $C[0] = 1; // nC0 is 1 for ($i = 1; $i <= $n; $i++) { // Compute next row of pascal // triangle using the previous row for ($j = min($i, $k); $j > 0; $j--) $C[$j] = $C[$j] + $C[$j - 1]; } return $C[$k];} /* function to calculate numberof triangles that can be formed */function countTriangles($n, $m){ return (nCk($n, 3) - nCk($m, 3));} // Driver Code$n = 5;$m = 4;echo countTriangles($n, $m);return 0; // This code is contributed by ChitraNayal?>", "e": 5193, "s": 4440, "text": null }, { "code": "<script> // Javascript program to count number of triangles // with n total points, out of which m are // collinear. // Returns value of binomial coefficient // Code taken from https://goo.gl/vhy4jp function nCk(n, k) { let C = new Array(k+1); C.fill(0); C[0] = 1; // nC0 is 1 for (let i = 1; i <= n; i++) { // Compute next row of pascal triangle // using the previous row for (let j = Math.min(i, k); j > 0; j--) C[j] = C[j] + C[j-1]; } return C[k]; } /* function to calculate number of triangle can be formed */ function countTriangles(n, m) { return (nCk(n, 3) - nCk(m, 3)); } let n = 5, m = 4; document.write(countTriangles(n, m)); // This code is contributed by divyesh072019.</script>", "e": 6058, "s": 5193, "text": null }, { "code": null, "e": 6069, "s": 6058, "text": "Output : " }, { "code": null, "e": 6071, "s": 6069, "text": "6" }, { "code": null, "e": 6079, "s": 6073, "text": "ukasp" }, { "code": null, "e": 6093, "s": 6079, "text": "divyesh072019" }, { "code": null, "e": 6106, "s": 6093, "text": "simmytarika5" }, { "code": null, "e": 6115, "s": 6106, "text": "triangle" }, { "code": null, "e": 6129, "s": 6115, "text": "Combinatorial" }, { "code": null, "e": 6143, "s": 6129, "text": "Combinatorial" } ]
Computer System Life Cycle
21 Aug, 2019 The system life cycle is defined as collection of the phases of development through which a computer-based system passes. Life cycle phases have been defined in very many different ways and in varying degrees of detail. Most definitions, however, recognize broad phases such as initial conception, requirements definition, outline design, detailed design, programming, testing, implementation, maintenance, and modification. The most life-cycle definitions produce as a result of analysis of the tasks of system development, with the objective of making those tasks more amenable to traditional techniques of management planning and control. Phases of Computer System Life Cycle:There are some phases of Computer System Life Cycle which are given below: Initiation:The generally Initiation phase is the first phase of Computer System Life Cycle and usually informally managed by the information system owner and the ISSO. Although all information system owners should be aware of the fact that FISMA requires new information systems to be positively accredited, this may not be at the forefront of their minds. Therefore, it is generally altogether likely that the ISSO may bring the need for C&A to the attention of the information system owner.Development:System is a broad and a general term, and as per to Wikipedia; “A system is a set of interacting or interdependent components forming an integrated whole” it’s a term that can be used in different industries and hence system Development Life Cycle is a limited term that explains the phases of creating a software component that integrates with other software components to create the whole system.Implementation:In this phase, the physical design of the system takes place. The Implementation phase is generally encompassing efforts by both designers and end users.Implementation phase may also include testing or the process of ensuring that the entire system successfully works together as a single entity. The testing may be done by real users, trained personnel or automated systems; It is becoming an increasingly important process for purposes of customer satisfaction. A depending on the system in question, the Implementation phase may take a considerable amount of time.Maintenance:After an implementation phase Maintenance is required. Maintenance processes for maintaining what happens during the rest of the system’s life: changes, correction, additions, moves to a different computing platform and more. This is generally least glamorous and perhaps most important step of all and goes on seemingly forever.Disposal:It is last phase of Computer System Life Cycle.The computer system is disposed of once of transition to a new computer system is completed.This is also a pay important role in Computer System Life Cycle. Initiation:The generally Initiation phase is the first phase of Computer System Life Cycle and usually informally managed by the information system owner and the ISSO. Although all information system owners should be aware of the fact that FISMA requires new information systems to be positively accredited, this may not be at the forefront of their minds. Therefore, it is generally altogether likely that the ISSO may bring the need for C&A to the attention of the information system owner. Development:System is a broad and a general term, and as per to Wikipedia; “A system is a set of interacting or interdependent components forming an integrated whole” it’s a term that can be used in different industries and hence system Development Life Cycle is a limited term that explains the phases of creating a software component that integrates with other software components to create the whole system. Implementation:In this phase, the physical design of the system takes place. The Implementation phase is generally encompassing efforts by both designers and end users.Implementation phase may also include testing or the process of ensuring that the entire system successfully works together as a single entity. The testing may be done by real users, trained personnel or automated systems; It is becoming an increasingly important process for purposes of customer satisfaction. A depending on the system in question, the Implementation phase may take a considerable amount of time. Maintenance:After an implementation phase Maintenance is required. Maintenance processes for maintaining what happens during the rest of the system’s life: changes, correction, additions, moves to a different computing platform and more. This is generally least glamorous and perhaps most important step of all and goes on seemingly forever. Disposal:It is last phase of Computer System Life Cycle.The computer system is disposed of once of transition to a new computer system is completed.This is also a pay important role in Computer System Life Cycle. Computer Organization & Architecture Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Logical and Physical Address in Operating System Direct Access Media (DMA) Controller in Computer Architecture Computer Organization | RISC and CISC Memory Hierarchy Design and its Characteristics Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput) Interrupts Architecture of 8085 microprocessor Pin diagram of 8086 microprocessor Control Characters Computer Organization | Instruction Formats (Zero, One, Two and Three Address Instruction)
[ { "code": null, "e": 54, "s": 26, "text": "\n21 Aug, 2019" }, { "code": null, "e": 479, "s": 54, "text": "The system life cycle is defined as collection of the phases of development through which a computer-based system passes. Life cycle phases have been defined in very many different ways and in varying degrees of detail. Most definitions, however, recognize broad phases such as initial conception, requirements definition, outline design, detailed design, programming, testing, implementation, maintenance, and modification." }, { "code": null, "e": 696, "s": 479, "text": "The most life-cycle definitions produce as a result of analysis of the tasks of system development, with the objective of making those tasks more amenable to traditional techniques of management planning and control." }, { "code": null, "e": 808, "s": 696, "text": "Phases of Computer System Life Cycle:There are some phases of Computer System Life Cycle which are given below:" }, { "code": null, "e": 2846, "s": 808, "text": "Initiation:The generally Initiation phase is the first phase of Computer System Life Cycle and usually informally managed by the information system owner and the ISSO. Although all information system owners should be aware of the fact that FISMA requires new information systems to be positively accredited, this may not be at the forefront of their minds. Therefore, it is generally altogether likely that the ISSO may bring the need for C&A to the attention of the information system owner.Development:System is a broad and a general term, and as per to Wikipedia; “A system is a set of interacting or interdependent components forming an integrated whole” it’s a term that can be used in different industries and hence system Development Life Cycle is a limited term that explains the phases of creating a software component that integrates with other software components to create the whole system.Implementation:In this phase, the physical design of the system takes place. The Implementation phase is generally encompassing efforts by both designers and end users.Implementation phase may also include testing or the process of ensuring that the entire system successfully works together as a single entity. The testing may be done by real users, trained personnel or automated systems; It is becoming an increasingly important process for purposes of customer satisfaction. A depending on the system in question, the Implementation phase may take a considerable amount of time.Maintenance:After an implementation phase Maintenance is required. Maintenance processes for maintaining what happens during the rest of the system’s life: changes, correction, additions, moves to a different computing platform and more. This is generally least glamorous and perhaps most important step of all and goes on seemingly forever.Disposal:It is last phase of Computer System Life Cycle.The computer system is disposed of once of transition to a new computer system is completed.This is also a pay important role in Computer System Life Cycle." }, { "code": null, "e": 3339, "s": 2846, "text": "Initiation:The generally Initiation phase is the first phase of Computer System Life Cycle and usually informally managed by the information system owner and the ISSO. Although all information system owners should be aware of the fact that FISMA requires new information systems to be positively accredited, this may not be at the forefront of their minds. Therefore, it is generally altogether likely that the ISSO may bring the need for C&A to the attention of the information system owner." }, { "code": null, "e": 3750, "s": 3339, "text": "Development:System is a broad and a general term, and as per to Wikipedia; “A system is a set of interacting or interdependent components forming an integrated whole” it’s a term that can be used in different industries and hence system Development Life Cycle is a limited term that explains the phases of creating a software component that integrates with other software components to create the whole system." }, { "code": null, "e": 4333, "s": 3750, "text": "Implementation:In this phase, the physical design of the system takes place. The Implementation phase is generally encompassing efforts by both designers and end users.Implementation phase may also include testing or the process of ensuring that the entire system successfully works together as a single entity. The testing may be done by real users, trained personnel or automated systems; It is becoming an increasingly important process for purposes of customer satisfaction. A depending on the system in question, the Implementation phase may take a considerable amount of time." }, { "code": null, "e": 4675, "s": 4333, "text": "Maintenance:After an implementation phase Maintenance is required. Maintenance processes for maintaining what happens during the rest of the system’s life: changes, correction, additions, moves to a different computing platform and more. This is generally least glamorous and perhaps most important step of all and goes on seemingly forever." }, { "code": null, "e": 4888, "s": 4675, "text": "Disposal:It is last phase of Computer System Life Cycle.The computer system is disposed of once of transition to a new computer system is completed.This is also a pay important role in Computer System Life Cycle." }, { "code": null, "e": 4925, "s": 4888, "text": "Computer Organization & Architecture" }, { "code": null, "e": 5023, "s": 4925, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5072, "s": 5023, "text": "Logical and Physical Address in Operating System" }, { "code": null, "e": 5134, "s": 5072, "text": "Direct Access Media (DMA) Controller in Computer Architecture" }, { "code": null, "e": 5172, "s": 5134, "text": "Computer Organization | RISC and CISC" }, { "code": null, "e": 5220, "s": 5172, "text": "Memory Hierarchy Design and its Characteristics" }, { "code": null, "e": 5315, "s": 5220, "text": "Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)" }, { "code": null, "e": 5326, "s": 5315, "text": "Interrupts" }, { "code": null, "e": 5362, "s": 5326, "text": "Architecture of 8085 microprocessor" }, { "code": null, "e": 5397, "s": 5362, "text": "Pin diagram of 8086 microprocessor" }, { "code": null, "e": 5416, "s": 5397, "text": "Control Characters" } ]
HTTP headers | Referrer-Policy
12 Oct, 2021 The Referrer Policy HTTP header sets the parameter for amount of information sent along with Referrer Header while making a request. Referrer policy is used to maintain the security and privacy of source account while fetching resources or performing navigation. This is done by modifying the algorithm used to populate Referrer Header. Referrer Policy can be delivered for a request through various methods. It can be done by simply using the HTTP header or the meta element in HTML which takes referrer keyword as value that in turn allows referrer policy setting through markup or using the referrerpolicy content attribute in HTML. CSS consults the referrer policy of owner document when style attribute is used and policy can be over-written for external stylesheets which have default value of no-referrer-when-downgrade. Syntax : Referrer-Policy : no-referrer Referrer-Policy : no-referrer-when-downgrade Referrer-Policy : origin Referrer-Policy : strict-origin Referrer-Policy : origin-when-cross-origin Referrer-Policy : strict-origin-when-cross-origin Referrer-Policy : same-origin Referrer-Policy : unsafe-url Directives : This header accepts eight directive as mentioned above and described below: no-referrer : This sends no referrer information along with the request made. no-referrer-when-downgrade : This sends complete URL information to a potentially trustworthy URL from modern HTTPS State or from not modern HTTPS state to any origin . Information is sent for HTTPS -> HTTPS and HTTP -> HTTPS transition . This is the default Referrer-Policy. origin : It only sends the origin value of the request client when making either same-origin (same website) or cross-origin (different website) requests. strict-origin : This only sends origin information to potentially trustworthy URL from modern HTTPS State or from not modern HTTPS state to any origin. origin-when-cross-origin : It sends complete URL information when making requests on same origin but only origin information when making cross-origin requests. strict-origin-when-cross-origin : It sends complete URL information when working on request from same origin. It sends only origin information to potentially trustworthy URL from modern HTTPS State or from not modern HTTPS state to any origin. No referrer information is sent to a potentially non-trustworthy URL. same-origin : It sends referrer information when origin is on same website but no information is sent for cross origin. unsafe-url : It sends complete URL information irrespective of any criteria. Examples: This is the standard example given by World Wide Web Consortium. The examples here list the website to which request is sent as the Navigation Website and the referrer information sent along with it. For ease , https://example.com/page.html will be considered origin site for each example. no-referrer Navigation website : https://notexample.com/page.html (or any other website) Referrer : no referrer sent no-referrer-when-downgrade Navigation website : https://not.example.com/ Referrer : https://example.com/page.html ------------------------------------------- Navigation Website : http://not.example.com/ Referrer : no referrer sent origin Navigation Website : any trustworthy or non-trustworthy URL Referrer : https://example.com/ strict-origin Navigation Website : https://not.example.com Referrer : https://example.com/. --------------------------------------------- Navigation Website : http://not.example.com Referrer : no-referrer --------------------------------------------- Origin Website : http://example.com/page.html Navigation Website : any trustworthy or non-trustworthy URL Referrer : http://example.com/ origin-when-cross-origin Navigation Website : https://example.com/not-page.html Referrer : https://example.com/page.html ------------------------------------------------------- Navigation Website : https://not.example.com/ (or a non-trustworthy URL) Referrer : https://example.com/ strict-origin-when-cross-origin Navigation Website : https://example.com/not-page.html Referrer : https://example.com/page.html. ------------------------------------------------------- Navigation Website : https://not.example.com/ Referrer : https://example.com/ -------------------------------------------------------- Navigation Website : http://not.example.com/ Referrer : no referrer same-origin Navigation Website : https://example.com/not-page.html Referrer : https://example.com/page.html ------------------------------------------------------ Navigation Website : https://not.example.com/ Referrer : no referrer unsafe-url Navigation Website : Any trustworthy or non-trustworthy URL Referrer : https://example.com/page.html Supported Browsers: The browsers supported by HTTP headers Referrer-Policy are listed below Google ChromeSafariMicrosoft EdgeOperaMozilla Firefox Google Chrome Safari Microsoft Edge Opera Mozilla Firefox prachisoda1234 HTTP-headers Picked 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": "\n12 Oct, 2021" }, { "code": null, "e": 366, "s": 28, "text": "The Referrer Policy HTTP header sets the parameter for amount of information sent along with Referrer Header while making a request. Referrer policy is used to maintain the security and privacy of source account while fetching resources or performing navigation. This is done by modifying the algorithm used to populate Referrer Header. " }, { "code": null, "e": 858, "s": 366, "text": "Referrer Policy can be delivered for a request through various methods. It can be done by simply using the HTTP header or the meta element in HTML which takes referrer keyword as value that in turn allows referrer policy setting through markup or using the referrerpolicy content attribute in HTML. CSS consults the referrer policy of owner document when style attribute is used and policy can be over-written for external stylesheets which have default value of no-referrer-when-downgrade. " }, { "code": null, "e": 868, "s": 858, "text": "Syntax : " }, { "code": null, "e": 1152, "s": 868, "text": "Referrer-Policy : no-referrer\nReferrer-Policy : no-referrer-when-downgrade\nReferrer-Policy : origin\nReferrer-Policy : strict-origin\nReferrer-Policy : origin-when-cross-origin\nReferrer-Policy : strict-origin-when-cross-origin\nReferrer-Policy : same-origin\nReferrer-Policy : unsafe-url" }, { "code": null, "e": 1241, "s": 1152, "text": "Directives : This header accepts eight directive as mentioned above and described below:" }, { "code": null, "e": 1319, "s": 1241, "text": "no-referrer : This sends no referrer information along with the request made." }, { "code": null, "e": 1595, "s": 1319, "text": "no-referrer-when-downgrade : This sends complete URL information to a potentially trustworthy URL from modern HTTPS State or from not modern HTTPS state to any origin . Information is sent for HTTPS -> HTTPS and HTTP -> HTTPS transition . This is the default Referrer-Policy." }, { "code": null, "e": 1749, "s": 1595, "text": "origin : It only sends the origin value of the request client when making either same-origin (same website) or cross-origin (different website) requests." }, { "code": null, "e": 1901, "s": 1749, "text": "strict-origin : This only sends origin information to potentially trustworthy URL from modern HTTPS State or from not modern HTTPS state to any origin." }, { "code": null, "e": 2061, "s": 1901, "text": "origin-when-cross-origin : It sends complete URL information when making requests on same origin but only origin information when making cross-origin requests." }, { "code": null, "e": 2375, "s": 2061, "text": "strict-origin-when-cross-origin : It sends complete URL information when working on request from same origin. It sends only origin information to potentially trustworthy URL from modern HTTPS State or from not modern HTTPS state to any origin. No referrer information is sent to a potentially non-trustworthy URL." }, { "code": null, "e": 2495, "s": 2375, "text": "same-origin : It sends referrer information when origin is on same website but no information is sent for cross origin." }, { "code": null, "e": 2572, "s": 2495, "text": "unsafe-url : It sends complete URL information irrespective of any criteria." }, { "code": null, "e": 2873, "s": 2572, "text": "Examples: This is the standard example given by World Wide Web Consortium. The examples here list the website to which request is sent as the Navigation Website and the referrer information sent along with it. For ease , https://example.com/page.html will be considered origin site for each example. " }, { "code": null, "e": 2885, "s": 2873, "text": "no-referrer" }, { "code": null, "e": 2990, "s": 2885, "text": "Navigation website : https://notexample.com/page.html (or any other website)\nReferrer : no referrer sent" }, { "code": null, "e": 3017, "s": 2990, "text": "no-referrer-when-downgrade" }, { "code": null, "e": 3222, "s": 3017, "text": "Navigation website : https://not.example.com/ \nReferrer : https://example.com/page.html\n-------------------------------------------\nNavigation Website : http://not.example.com/\nReferrer : no referrer sent" }, { "code": null, "e": 3229, "s": 3222, "text": "origin" }, { "code": null, "e": 3321, "s": 3229, "text": "Navigation Website : any trustworthy or non-trustworthy URL\nReferrer : https://example.com/" }, { "code": null, "e": 3335, "s": 3321, "text": "strict-origin" }, { "code": null, "e": 3710, "s": 3335, "text": "Navigation Website : https://not.example.com\nReferrer : https://example.com/.\n---------------------------------------------\nNavigation Website : http://not.example.com\nReferrer : no-referrer \n---------------------------------------------\nOrigin Website : http://example.com/page.html\nNavigation Website : any trustworthy or non-trustworthy URL\nReferrer : http://example.com/" }, { "code": null, "e": 3735, "s": 3710, "text": "origin-when-cross-origin" }, { "code": null, "e": 3993, "s": 3735, "text": "Navigation Website : https://example.com/not-page.html \nReferrer : https://example.com/page.html\n-------------------------------------------------------\nNavigation Website : https://not.example.com/ (or a non-trustworthy URL)\nReferrer : https://example.com/" }, { "code": null, "e": 4025, "s": 3993, "text": "strict-origin-when-cross-origin" }, { "code": null, "e": 4381, "s": 4025, "text": "Navigation Website : https://example.com/not-page.html\nReferrer : https://example.com/page.html.\n-------------------------------------------------------\nNavigation Website : https://not.example.com/\nReferrer : https://example.com/\n--------------------------------------------------------\nNavigation Website : http://not.example.com/\nReferrer : no referrer" }, { "code": null, "e": 4393, "s": 4381, "text": "same-origin" }, { "code": null, "e": 4614, "s": 4393, "text": "Navigation Website : https://example.com/not-page.html \nReferrer : https://example.com/page.html\n------------------------------------------------------\nNavigation Website : https://not.example.com/\nReferrer : no referrer" }, { "code": null, "e": 4625, "s": 4614, "text": "unsafe-url" }, { "code": null, "e": 4726, "s": 4625, "text": "Navigation Website : Any trustworthy or non-trustworthy URL\nReferrer : https://example.com/page.html" }, { "code": null, "e": 4818, "s": 4726, "text": "Supported Browsers: The browsers supported by HTTP headers Referrer-Policy are listed below" }, { "code": null, "e": 4872, "s": 4818, "text": "Google ChromeSafariMicrosoft EdgeOperaMozilla Firefox" }, { "code": null, "e": 4886, "s": 4872, "text": "Google Chrome" }, { "code": null, "e": 4893, "s": 4886, "text": "Safari" }, { "code": null, "e": 4908, "s": 4893, "text": "Microsoft Edge" }, { "code": null, "e": 4914, "s": 4908, "text": "Opera" }, { "code": null, "e": 4930, "s": 4914, "text": "Mozilla Firefox" }, { "code": null, "e": 4945, "s": 4930, "text": "prachisoda1234" }, { "code": null, "e": 4958, "s": 4945, "text": "HTTP-headers" }, { "code": null, "e": 4965, "s": 4958, "text": "Picked" }, { "code": null, "e": 4982, "s": 4965, "text": "Web Technologies" } ]
Python | Triple list difference
29 Apr, 2019 The difference between 2 lists have been dealt previously, but sometimes, we can have more than two lists and we need to find the mutual differences of one list with every other list. This kind of problem has applications in many domains. Let’s discuss certain ways in which this problem can be solved. Method #1 : Using map() + set() + list comprehension The combination of above 3 functions can be used to perform this particular task. The map function can be used to convert the list to set by the set function and list comprehension can be used to get the new mutual difference list for each list. # Python3 code to demonstrate# triple list difference # using map() + set() + list comprehension # initializing lists test_list1 = [1, 5, 6, 4, 7]test_list2 = [8, 4, 3]test_list3 = [9, 10, 3, 5] # printing original listsprint("The original list 1 : " + str(test_list1))print("The original list 2 : " + str(test_list2))print("The original list 3 : " + str(test_list3)) # using map() + set() + list comprehension# triple list difference temp1, temp2, temp3 = map(set, (test_list1, test_list2, test_list3))res1 = [ele for ele in test_list1 if ele not in temp2 and ele not in temp3]res2 = [ele for ele in test_list2 if ele not in temp1 and ele not in temp3]res3 = [ele for ele in test_list3 if ele not in temp2 and ele not in temp1] # print resultprint("The mutual difference list are : " + str(res1) + " " + str(res2) + " " + str(res3)) The original list 1 : [1, 5, 6, 4, 7] The original list 2 : [8, 4, 3] The original list 3 : [9, 10, 3, 5] The mutual difference list are : [1, 6, 7] [8] [9, 10] Method #2 : Using map() + set() + "-" operator This problem can also be solved the minus operator, if one wishes not to use the list comprehension. The minus operator can perform the boolean match difference to compute the valid set difference. # Python3 code to demonstrate# triple list difference # using map() + set() + "-" operator # initializing lists test_list1 = [1, 5, 6, 4, 7]test_list2 = [8, 4, 3]test_list3 = [9, 10, 3, 5] # printing original listsprint("The original list 1 : " + str(test_list1))print("The original list 2 : " + str(test_list2))print("The original list 3 : " + str(test_list3)) # using map() + set() + "-" operator# triple list difference temp1, temp2, temp3 = map(set, (test_list1, test_list2, test_list3))res1 = temp1 - temp2 - temp3res2 = temp2 - temp3 - temp1res3 = temp3 - temp1 - temp2res1, res2, res3 = map(list, (res1, res2, res3)) # print resultprint("The mutual difference list are : " + str(res1) + " " + str(res2) + " " + str(res3)) The original list 1 : [1, 5, 6, 4, 7] The original list 2 : [8, 4, 3] The original list 3 : [9, 10, 3, 5] The mutual difference list are : [1, 6, 7] [8] [9, 10] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Apr, 2019" }, { "code": null, "e": 331, "s": 28, "text": "The difference between 2 lists have been dealt previously, but sometimes, we can have more than two lists and we need to find the mutual differences of one list with every other list. This kind of problem has applications in many domains. Let’s discuss certain ways in which this problem can be solved." }, { "code": null, "e": 384, "s": 331, "text": "Method #1 : Using map() + set() + list comprehension" }, { "code": null, "e": 630, "s": 384, "text": "The combination of above 3 functions can be used to perform this particular task. The map function can be used to convert the list to set by the set function and list comprehension can be used to get the new mutual difference list for each list." }, { "code": "# Python3 code to demonstrate# triple list difference # using map() + set() + list comprehension # initializing lists test_list1 = [1, 5, 6, 4, 7]test_list2 = [8, 4, 3]test_list3 = [9, 10, 3, 5] # printing original listsprint(\"The original list 1 : \" + str(test_list1))print(\"The original list 2 : \" + str(test_list2))print(\"The original list 3 : \" + str(test_list3)) # using map() + set() + list comprehension# triple list difference temp1, temp2, temp3 = map(set, (test_list1, test_list2, test_list3))res1 = [ele for ele in test_list1 if ele not in temp2 and ele not in temp3]res2 = [ele for ele in test_list2 if ele not in temp1 and ele not in temp3]res3 = [ele for ele in test_list3 if ele not in temp2 and ele not in temp1] # print resultprint(\"The mutual difference list are : \" + str(res1) + \" \" + str(res2) + \" \" + str(res3))", "e": 1473, "s": 630, "text": null }, { "code": null, "e": 1635, "s": 1473, "text": "The original list 1 : [1, 5, 6, 4, 7]\nThe original list 2 : [8, 4, 3]\nThe original list 3 : [9, 10, 3, 5]\nThe mutual difference list are : [1, 6, 7] [8] [9, 10]\n" }, { "code": null, "e": 1684, "s": 1637, "text": "Method #2 : Using map() + set() + \"-\" operator" }, { "code": null, "e": 1882, "s": 1684, "text": "This problem can also be solved the minus operator, if one wishes not to use the list comprehension. The minus operator can perform the boolean match difference to compute the valid set difference." }, { "code": "# Python3 code to demonstrate# triple list difference # using map() + set() + \"-\" operator # initializing lists test_list1 = [1, 5, 6, 4, 7]test_list2 = [8, 4, 3]test_list3 = [9, 10, 3, 5] # printing original listsprint(\"The original list 1 : \" + str(test_list1))print(\"The original list 2 : \" + str(test_list2))print(\"The original list 3 : \" + str(test_list3)) # using map() + set() + \"-\" operator# triple list difference temp1, temp2, temp3 = map(set, (test_list1, test_list2, test_list3))res1 = temp1 - temp2 - temp3res2 = temp2 - temp3 - temp1res3 = temp3 - temp1 - temp2res1, res2, res3 = map(list, (res1, res2, res3)) # print resultprint(\"The mutual difference list are : \" + str(res1) + \" \" + str(res2) + \" \" + str(res3))", "e": 2620, "s": 1882, "text": null }, { "code": null, "e": 2782, "s": 2620, "text": "The original list 1 : [1, 5, 6, 4, 7]\nThe original list 2 : [8, 4, 3]\nThe original list 3 : [9, 10, 3, 5]\nThe mutual difference list are : [1, 6, 7] [8] [9, 10]\n" }, { "code": null, "e": 2803, "s": 2782, "text": "Python list-programs" }, { "code": null, "e": 2810, "s": 2803, "text": "Python" }, { "code": null, "e": 2826, "s": 2810, "text": "Python Programs" } ]
How to Create Text Color Animation using HTML and CSS ?
11 Aug, 2021 The text color can be changed according to programmer’s choice using CSS @keyframes rule. HTML Code: The following code snippet creates HTML div element which contains the text for modification. <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <title>Text Color Animation</title></head><body> <div> <h2>GeeksforGeeks</h2> </div></body></html> CSS Code: The following code snippets demonstrates the design of the text using some basic CSS properties along with CSS @keyframes rule to change the color of the text to produce the animation effect. <style> body { margin: 0; padding: 0; } div { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } h2 { font-size: 5em; font-family: serif; color: transparent; text-align: center; animation: effect 2s linear infinite; } @keyframes effect { 0% { background: linear-gradient( #008000, #00FF00); -webkit-background-clip: text; } 100% { background: linear-gradient( #3CE7D7, #000FFF); -webkit-background-clip: text; } }</style> Complete Code: It is the combination of the above two code sections. <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <title>Text Color Animation</title> <style> body { margin: 0; padding: 0; } div { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } h2 { font-size: 5em; font-family: serif; color: transparent; text-align: center; animation: effect 2s linear infinite; \ } @keyframes effect { 0% { background: linear-gradient( #008000, #00FF00); -webkit-background-clip: text; } 100% { background: linear-gradient( #3CE7D7, #000FFF); -webkit-background-clip: text; } } </style></head> <body> <div> <h2>GeeksforGeeks</h2> </div></body> </html> Output: kapoorsagar226 CSS-Misc HTML-Misc CSS HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to set space between the flexbox ? Design a Tribute Page using HTML & CSS How to select all child elements recursively using CSS? Build a Survey Form using HTML and CSS CSS | :not(:last-child):after Selector REST API (Introduction) Hide or show elements in HTML using display property How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? HTTP headers | Content-Type
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Aug, 2021" }, { "code": null, "e": 118, "s": 28, "text": "The text color can be changed according to programmer’s choice using CSS @keyframes rule." }, { "code": null, "e": 223, "s": 118, "text": "HTML Code: The following code snippet creates HTML div element which contains the text for modification." }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <title>Text Color Animation</title></head><body> <div> <h2>GeeksforGeeks</h2> </div></body></html>", "e": 466, "s": 223, "text": null }, { "code": null, "e": 668, "s": 466, "text": "CSS Code: The following code snippets demonstrates the design of the text using some basic CSS properties along with CSS @keyframes rule to change the color of the text to produce the animation effect." }, { "code": "<style> body { margin: 0; padding: 0; } div { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } h2 { font-size: 5em; font-family: serif; color: transparent; text-align: center; animation: effect 2s linear infinite; } @keyframes effect { 0% { background: linear-gradient( #008000, #00FF00); -webkit-background-clip: text; } 100% { background: linear-gradient( #3CE7D7, #000FFF); -webkit-background-clip: text; } }</style>", "e": 1323, "s": 668, "text": null }, { "code": null, "e": 1392, "s": 1323, "text": "Complete Code: It is the combination of the above two code sections." }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <title>Text Color Animation</title> <style> body { margin: 0; padding: 0; } div { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } h2 { font-size: 5em; font-family: serif; color: transparent; text-align: center; animation: effect 2s linear infinite; \\ } @keyframes effect { 0% { background: linear-gradient( #008000, #00FF00); -webkit-background-clip: text; } 100% { background: linear-gradient( #3CE7D7, #000FFF); -webkit-background-clip: text; } } </style></head> <body> <div> <h2>GeeksforGeeks</h2> </div></body> </html>", "e": 2456, "s": 1392, "text": null }, { "code": null, "e": 2464, "s": 2456, "text": "Output:" }, { "code": null, "e": 2479, "s": 2464, "text": "kapoorsagar226" }, { "code": null, "e": 2488, "s": 2479, "text": "CSS-Misc" }, { "code": null, "e": 2498, "s": 2488, "text": "HTML-Misc" }, { "code": null, "e": 2502, "s": 2498, "text": "CSS" }, { "code": null, "e": 2507, "s": 2502, "text": "HTML" }, { "code": null, "e": 2524, "s": 2507, "text": "Web Technologies" }, { "code": null, "e": 2551, "s": 2524, "text": "Web technologies Questions" }, { "code": null, "e": 2556, "s": 2551, "text": "HTML" }, { "code": null, "e": 2654, "s": 2556, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2693, "s": 2654, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 2732, "s": 2693, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 2788, "s": 2732, "text": "How to select all child elements recursively using CSS?" }, { "code": null, "e": 2827, "s": 2788, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 2866, "s": 2827, "text": "CSS | :not(:last-child):after Selector" }, { "code": null, "e": 2890, "s": 2866, "text": "REST API (Introduction)" }, { "code": null, "e": 2943, "s": 2890, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 3003, "s": 2943, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 3064, "s": 3003, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Maximum bishops that can be placed on N*N chessboard
27 May, 2021 Given an integer n, the task is to print the maximum number of bishops that can be placed on a n x n chessboard so that no two bishops attack each other. For example, maximum 2 bishops can be placed safely on 2 x 2 chessboard. Examples: Input: n = 2 Output: 2 We can place two bishop in a row. Input: n = 5 Output: 8 Approach: A bishop can travel in any of the four diagonals. Therefore we can place bishops if it is not in any diagonal of another bishop. The maximum bishops that can be placed on an n * n chessboard will be 2 * (n – 1). Place n bishops in first rowPlace n-2 bishops in last row. We only leave two corners of last row Place n bishops in first row Place n-2 bishops in last row. We only leave two corners of last row Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of the approach#include <iostream>using namespace std; // Function to return the maximum number of bishops// that can be placed on an n * n chessboardint numberOfBishops(int n){ if (n < 1) return 0; else if (n == 1) return 1; else return 2 * (n - 1);} // Driver codeint main(){ int n = 5; cout << numberOfBishops(n); return 0;} // Java implementation of the approachclass gfg{ // Function to return the maximum// number of bishops that can be// placed on an n * n chessboardstatic int numberOfBishops(int n){ if (n < 1) return 0; else if (n == 1) return 1; else return 2 * (n - 1);} // Driver codepublic static void main(String[] args){ int n = 5; System.out.println(numberOfBishops(n));}} // This code is contributed by Mukul Singh. # Python3 implementation of the# approachimport math as mt # Function to return the maximum number# of bishops that can be placed on an# n * n chessboarddef numberOfBishops(n): if (n < 1): return 0 elif (n == 1): return 1 else: return 2 * (n - 1) # Driver coden = 5print(numberOfBishops(n)) # This code is contributed by# Mohit kumar 29 // C# implementation of the approachusing System; class GFG{ // Function to return the maximum number// of bishops that can be placed on an// n * n chessboardstatic int numberOfBishops(int n){ if (n < 1) return 0; else if (n == 1) return 1; else return 2 * (n - 1);} // Driver codepublic static void Main(){ int n = 5; Console.Write(numberOfBishops(n));}} // This code is contributed// by Akanksha Rai <?php// PHP implementation of the approach // Function to return the maximum number// of bishops that can be placed on an// n * n chessboardfunction numberOfBishops($n){ if ($n < 1) return 0; else if ($n == 1) return 1; else return 2 * ($n - 1);} // Driver code$n = 5;echo numberOfBishops($n); // This code is contributed by Ryuga?> <script>// Javascript implementation of the approach // Function to return the maximum// number of bishops that can be// placed on an n * n chessboard function numberOfBishops(n) { if (n < 1) return 0; else if (n == 1) return 1; else return 2 * (n - 1); } // Driver code let n = 5; document.write(numberOfBishops(n)); // This code is contributed by patel2127</script> 8 Below is the implementation for bigger values of n: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the difference of// two big numbers as stringstring subtract(string str1, string str2){ string res = ""; int n1 = str1.length(); int n2 = str2.length(); // To make subtraction easy reverse(str1.begin(), str1.end()); reverse(str2.begin(), str2.end()); int carry = 0; for (int i = 0; i < n2; i++) { // Subtract digit by bdigit int subst = ((str1[i] - '0') - (str2[i] - '0') - carry); if (subst < 0) { subst = subst + 10; carry = 1; } else carry = 0; // Change subst as character and // add it to result string res.push_back(subst + '0'); } for (int i = n2; i < n1; i++) { int subst = ((str1[i] - '0') - carry); if (subst < 0) { subst = subst + 10; carry = 1; } else carry = 0; res.push_back(subst + '0'); } // Reverse result to make it actual number reverse(res.begin(), res.end()); return res;} string NumberOfBishops(string a){ if (a == "1") return a; else { // Subtract 1 from number a = subtract(a, "1"); // Reverse the string to make calculations easier reverse(a.begin(), a.end()); int carry = 0; // Multiply by 2 for (int i = 0; i < a.size(); i++) { int tmp = a[i] - '0'; tmp *= 2; tmp += carry; a[i] = '0' + (tmp % 10); carry = tmp / 10; } if (carry > 0) a += ('0' + carry); // Reverse the string to get actual result reverse(a.begin(), a.end()); // Return result return a; }} // Driver codeint main(){ string a = "12345678901234567890"; cout << NumberOfBishops(a) << endl; return 0;} // Java implementation of the approachimport java.util.*; class GFG{ public static char[] reverse(char []str){ char[] temp = new char[str.length]; // Fill character array backwards with // characters of the string for(int i = 0; i < str.length; i++) temp[str.length - i - 1] = str[i]; // Convert character array to string // and return it return temp;} // Function to return the difference of// two big numbers as Stringstatic char[] subtract(char[] str1, char[] str2){ String res = ""; int n1 = str1.length; int n2 = str2.length; // To make subtraction easy str1 = reverse(str1); str2 = reverse(str2); int carry = 0; for(int i = 0; i < n2; i++) { // Subtract digit by bdigit int subst = ((str1[i] - '0') - (str2[i] - '0') - carry); if (subst < 0) { subst = subst + 10; carry = 1; } else carry = 0; // Change subst as character and // add it to result String res = res + (subst); } for(int i = n2; i < n1; i++) { int subst = ((str1[i] - '0') - carry); if (subst < 0) { subst = subst + 10; carry = 1; } else carry = 0; res += (subst); } // Reverse result to make it actual number char[] Res = res.toCharArray(); Res = reverse(Res); return Res;} static char[] NumberOfBishops(char[] a){ if (new String(a) == "1") return a; else { // Subtract 1 from number a = subtract(a, "1".toCharArray()); //Console.WriteLine(new String(a)); // Reverse the String to make // calculations easier a = reverse(a); int carry = 0; // Multiply by 2 for(int i = 0; i < a.length; i++) { int tmp = a[i] - '0'; tmp *= 2; tmp += carry; a[i] = (char)('0' + (tmp % 10)); carry = tmp / 10; } String A = new String(a); if (carry > 0) A += ('0' + carry); char[] a1 = A.toCharArray(); // Reverse the String to get // actual result a1 = reverse(a1); // Return result return a1; }} // Driver codepublic static void main(String []args){ char[] a = "12345678901234567890".toCharArray(); System.out.println(new String(NumberOfBishops(a)));}} // This code is contributed by pratham76 # Python3 implementation of the approach # Function to return the difference# of two big numbers as stringdef subtract(str1, str2): res = "" n1 = len(str1) n2 = len(str2) # To make subtraction easy, # reverse the strings str1 = str1[::-1] str2 = str2[::-1] carry = 0 for i in range(0, n2): # Subtract digit by bdigit subst = int(str1[i]) - int(str2[i]) - carry if subst < 0: subst = subst + 10 carry = 1 else: carry = 0 # Change subst as character and # add it to result string res += str(subst) for i in range(n2, n1): subst = int(str1[i]) - carry if subst < 0: subst = subst + 10 carry = 1 else: carry = 0 res += str(subst) # Reverse result to make it # actual number return res[::-1] def NumberOfBishops(a): if a == "1": return a else: # Subtract 1 from number a = subtract(a, "1") carry = 0 # Reverse the string to make # calculations easier. Convert the # string to list to manipulate it # as strings are immutable in python a = list(a[::-1]) # Multiply by 2 for i in range(0, len(a)): tmp = (int(a[i]) * 2) + carry a[i] = str(tmp % 10) carry = tmp // 10 # Convert the list back to string a = ''.join(a) if carry > 0: a += str(carry) # Reverse the string to get # actual result return a[::-1] # Driver codeif __name__ == "__main__": a = "12345678901234567890" print(NumberOfBishops(a)) # This code is contributed# by Rituraj Jain // C# implementation of the approachusing System;class GFG{ // Function to return the difference of // two big numbers as string static char[] subtract(char[] str1, char[] str2) { string res = ""; int n1 = str1.Length; int n2 = str2.Length; // To make subtraction easy Array.Reverse(str1); Array.Reverse(str2); int carry = 0; for (int i = 0; i < n2; i++) { // Subtract digit by bdigit int subst = ((str1[i] - '0') - (str2[i] - '0') - carry); if (subst < 0) { subst = subst + 10; carry = 1; } else carry = 0; // Change subst as character and // add it to result string res = res + (subst); } for (int i = n2; i < n1; i++) { int subst = ((str1[i] - '0') - carry); if (subst < 0) { subst = subst + 10; carry = 1; } else carry = 0; res += (subst); } // Reverse result to make it actual number char[] Res = res.ToCharArray(); Array.Reverse(Res); return Res; } static char[] NumberOfBishops(char[] a) { if (new string(a) == "1") return a; else { // Subtract 1 from number a = subtract(a, "1".ToCharArray()); //Console.WriteLine(new string(a)); // Reverse the string to make calculations easier Array.Reverse(a); int carry = 0; // Multiply by 2 for (int i = 0; i < a.Length; i++) { int tmp = a[i] - '0'; tmp *= 2; tmp += carry; a[i] = (char)('0' + (tmp % 10)); carry = tmp / 10; } string A = new string(a); if (carry > 0) A += ('0' + carry); char[] a1 = A.ToCharArray(); // Reverse the string to get actual result Array.Reverse(a1); // Return result return a1; } } // Driver code static void Main() { char[] a = "12345678901234567890".ToCharArray(); Console.WriteLine(new string(NumberOfBishops(a))); }} // This code is contributed by divyeshrabadiy07 <script> // Javascript implementation of the approach function reverse(str){ let temp = new Array(str.length); // Fill character array backwards with // characters of the string for(let i = 0; i < str.length; i++) temp[str.length - i - 1] = str[i]; // Convert character array to string // and return it return temp;} // Function to return the difference of// two big numbers as Stringfunction subtract(str1,str2){ let res = ""; let n1 = str1.length; let n2 = str2.length; // To make subtraction easy str1 = reverse(str1); str2 = reverse(str2); let carry = 0; for(let i = 0; i < n2; i++) { // Subtract digit by bdigit let subst = (parseInt(str1[i]) - parseInt(str2[i]) - carry); if (subst < 0) { subst = subst + 10; carry = 1; } else carry = 0; // Change subst as character and // add it to result String res = res + (subst).toString(); } for(let i = n2; i < n1; i++) { let subst = (parseInt(str1[i]) - carry); if (subst < 0) { subst = subst + 10; carry = 1; } else carry = 0; res += (subst).toString(); } // Reverse result to make it actual number let Res = res.split(""); Res = reverse(Res); return Res;} function NumberOfBishops(a){ if (a == "1") return a; else { // Subtract 1 from number a = subtract(a, "1"); //Console.WriteLine(new String(a)); // Reverse the String to make // calculations easier a = reverse(a); let carry = 0; // Multiply by 2 for(let i = 0; i < a.length; i++) { let tmp = parseInt(a[i]); tmp *= 2; tmp += carry; a[i] = (tmp % 10).toString(); carry = Math.floor(tmp / 10); } let A = a.join(""); if (carry > 0) A += ( carry).toString(); let a1 = A.split(""); // Reverse the String to get // actual result a1 = reverse(a1); // Return result return a1; }} // Driver codelet a = "12345678901234567890".split(""); document.write(NumberOfBishops(a).join("")); // This code is contributed by unknown2108.</script> 24691357802469135778 mohit kumar 29 ankthon Code_Mech rituraj_jain Akanksha_Rai divyeshrabadiya07 pratham76 patel2127 unknown2108 chessboard-problems Matrix Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Unique paths in a Grid with Obstacles Traverse a given Matrix using Recursion Find median in row wise sorted matrix Zigzag (or diagonal) traversal of Matrix A Boolean Matrix Question Find a specific pair in Matrix Python program to add two Matrices Common elements in all rows of a given matrix Find shortest safe route in a path with landmines Flood fill Algorithm - how to implement fill() in paint?
[ { "code": null, "e": 28, "s": 0, "text": "\n27 May, 2021" }, { "code": null, "e": 255, "s": 28, "text": "Given an integer n, the task is to print the maximum number of bishops that can be placed on a n x n chessboard so that no two bishops attack each other. For example, maximum 2 bishops can be placed safely on 2 x 2 chessboard." }, { "code": null, "e": 267, "s": 255, "text": "Examples: " }, { "code": null, "e": 324, "s": 267, "text": "Input: n = 2 Output: 2 We can place two bishop in a row." }, { "code": null, "e": 349, "s": 324, "text": "Input: n = 5 Output: 8 " }, { "code": null, "e": 576, "s": 353, "text": "Approach: A bishop can travel in any of the four diagonals. Therefore we can place bishops if it is not in any diagonal of another bishop. The maximum bishops that can be placed on an n * n chessboard will be 2 * (n – 1). " }, { "code": null, "e": 673, "s": 576, "text": "Place n bishops in first rowPlace n-2 bishops in last row. We only leave two corners of last row" }, { "code": null, "e": 702, "s": 673, "text": "Place n bishops in first row" }, { "code": null, "e": 771, "s": 702, "text": "Place n-2 bishops in last row. We only leave two corners of last row" }, { "code": null, "e": 825, "s": 773, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 829, "s": 825, "text": "C++" }, { "code": null, "e": 834, "s": 829, "text": "Java" }, { "code": null, "e": 842, "s": 834, "text": "Python3" }, { "code": null, "e": 845, "s": 842, "text": "C#" }, { "code": null, "e": 849, "s": 845, "text": "PHP" }, { "code": null, "e": 860, "s": 849, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <iostream>using namespace std; // Function to return the maximum number of bishops// that can be placed on an n * n chessboardint numberOfBishops(int n){ if (n < 1) return 0; else if (n == 1) return 1; else return 2 * (n - 1);} // Driver codeint main(){ int n = 5; cout << numberOfBishops(n); return 0;}", "e": 1249, "s": 860, "text": null }, { "code": "// Java implementation of the approachclass gfg{ // Function to return the maximum// number of bishops that can be// placed on an n * n chessboardstatic int numberOfBishops(int n){ if (n < 1) return 0; else if (n == 1) return 1; else return 2 * (n - 1);} // Driver codepublic static void main(String[] args){ int n = 5; System.out.println(numberOfBishops(n));}} // This code is contributed by Mukul Singh.", "e": 1695, "s": 1249, "text": null }, { "code": "# Python3 implementation of the# approachimport math as mt # Function to return the maximum number# of bishops that can be placed on an# n * n chessboarddef numberOfBishops(n): if (n < 1): return 0 elif (n == 1): return 1 else: return 2 * (n - 1) # Driver coden = 5print(numberOfBishops(n)) # This code is contributed by# Mohit kumar 29", "e": 2062, "s": 1695, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to return the maximum number// of bishops that can be placed on an// n * n chessboardstatic int numberOfBishops(int n){ if (n < 1) return 0; else if (n == 1) return 1; else return 2 * (n - 1);} // Driver codepublic static void Main(){ int n = 5; Console.Write(numberOfBishops(n));}} // This code is contributed// by Akanksha Rai", "e": 2504, "s": 2062, "text": null }, { "code": "<?php// PHP implementation of the approach // Function to return the maximum number// of bishops that can be placed on an// n * n chessboardfunction numberOfBishops($n){ if ($n < 1) return 0; else if ($n == 1) return 1; else return 2 * ($n - 1);} // Driver code$n = 5;echo numberOfBishops($n); // This code is contributed by Ryuga?>", "e": 2867, "s": 2504, "text": null }, { "code": "<script>// Javascript implementation of the approach // Function to return the maximum// number of bishops that can be// placed on an n * n chessboard function numberOfBishops(n) { if (n < 1) return 0; else if (n == 1) return 1; else return 2 * (n - 1); } // Driver code let n = 5; document.write(numberOfBishops(n)); // This code is contributed by patel2127</script>", "e": 3324, "s": 2867, "text": null }, { "code": null, "e": 3326, "s": 3324, "text": "8" }, { "code": null, "e": 3380, "s": 3328, "text": "Below is the implementation for bigger values of n:" }, { "code": null, "e": 3384, "s": 3380, "text": "C++" }, { "code": null, "e": 3389, "s": 3384, "text": "Java" }, { "code": null, "e": 3397, "s": 3389, "text": "Python3" }, { "code": null, "e": 3400, "s": 3397, "text": "C#" }, { "code": null, "e": 3411, "s": 3400, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the difference of// two big numbers as stringstring subtract(string str1, string str2){ string res = \"\"; int n1 = str1.length(); int n2 = str2.length(); // To make subtraction easy reverse(str1.begin(), str1.end()); reverse(str2.begin(), str2.end()); int carry = 0; for (int i = 0; i < n2; i++) { // Subtract digit by bdigit int subst = ((str1[i] - '0') - (str2[i] - '0') - carry); if (subst < 0) { subst = subst + 10; carry = 1; } else carry = 0; // Change subst as character and // add it to result string res.push_back(subst + '0'); } for (int i = n2; i < n1; i++) { int subst = ((str1[i] - '0') - carry); if (subst < 0) { subst = subst + 10; carry = 1; } else carry = 0; res.push_back(subst + '0'); } // Reverse result to make it actual number reverse(res.begin(), res.end()); return res;} string NumberOfBishops(string a){ if (a == \"1\") return a; else { // Subtract 1 from number a = subtract(a, \"1\"); // Reverse the string to make calculations easier reverse(a.begin(), a.end()); int carry = 0; // Multiply by 2 for (int i = 0; i < a.size(); i++) { int tmp = a[i] - '0'; tmp *= 2; tmp += carry; a[i] = '0' + (tmp % 10); carry = tmp / 10; } if (carry > 0) a += ('0' + carry); // Reverse the string to get actual result reverse(a.begin(), a.end()); // Return result return a; }} // Driver codeint main(){ string a = \"12345678901234567890\"; cout << NumberOfBishops(a) << endl; return 0;}", "e": 5325, "s": 3411, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GFG{ public static char[] reverse(char []str){ char[] temp = new char[str.length]; // Fill character array backwards with // characters of the string for(int i = 0; i < str.length; i++) temp[str.length - i - 1] = str[i]; // Convert character array to string // and return it return temp;} // Function to return the difference of// two big numbers as Stringstatic char[] subtract(char[] str1, char[] str2){ String res = \"\"; int n1 = str1.length; int n2 = str2.length; // To make subtraction easy str1 = reverse(str1); str2 = reverse(str2); int carry = 0; for(int i = 0; i < n2; i++) { // Subtract digit by bdigit int subst = ((str1[i] - '0') - (str2[i] - '0') - carry); if (subst < 0) { subst = subst + 10; carry = 1; } else carry = 0; // Change subst as character and // add it to result String res = res + (subst); } for(int i = n2; i < n1; i++) { int subst = ((str1[i] - '0') - carry); if (subst < 0) { subst = subst + 10; carry = 1; } else carry = 0; res += (subst); } // Reverse result to make it actual number char[] Res = res.toCharArray(); Res = reverse(Res); return Res;} static char[] NumberOfBishops(char[] a){ if (new String(a) == \"1\") return a; else { // Subtract 1 from number a = subtract(a, \"1\".toCharArray()); //Console.WriteLine(new String(a)); // Reverse the String to make // calculations easier a = reverse(a); int carry = 0; // Multiply by 2 for(int i = 0; i < a.length; i++) { int tmp = a[i] - '0'; tmp *= 2; tmp += carry; a[i] = (char)('0' + (tmp % 10)); carry = tmp / 10; } String A = new String(a); if (carry > 0) A += ('0' + carry); char[] a1 = A.toCharArray(); // Reverse the String to get // actual result a1 = reverse(a1); // Return result return a1; }} // Driver codepublic static void main(String []args){ char[] a = \"12345678901234567890\".toCharArray(); System.out.println(new String(NumberOfBishops(a)));}} // This code is contributed by pratham76", "e": 7896, "s": 5325, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the difference# of two big numbers as stringdef subtract(str1, str2): res = \"\" n1 = len(str1) n2 = len(str2) # To make subtraction easy, # reverse the strings str1 = str1[::-1] str2 = str2[::-1] carry = 0 for i in range(0, n2): # Subtract digit by bdigit subst = int(str1[i]) - int(str2[i]) - carry if subst < 0: subst = subst + 10 carry = 1 else: carry = 0 # Change subst as character and # add it to result string res += str(subst) for i in range(n2, n1): subst = int(str1[i]) - carry if subst < 0: subst = subst + 10 carry = 1 else: carry = 0 res += str(subst) # Reverse result to make it # actual number return res[::-1] def NumberOfBishops(a): if a == \"1\": return a else: # Subtract 1 from number a = subtract(a, \"1\") carry = 0 # Reverse the string to make # calculations easier. Convert the # string to list to manipulate it # as strings are immutable in python a = list(a[::-1]) # Multiply by 2 for i in range(0, len(a)): tmp = (int(a[i]) * 2) + carry a[i] = str(tmp % 10) carry = tmp // 10 # Convert the list back to string a = ''.join(a) if carry > 0: a += str(carry) # Reverse the string to get # actual result return a[::-1] # Driver codeif __name__ == \"__main__\": a = \"12345678901234567890\" print(NumberOfBishops(a)) # This code is contributed# by Rituraj Jain", "e": 9656, "s": 7896, "text": null }, { "code": "// C# implementation of the approachusing System;class GFG{ // Function to return the difference of // two big numbers as string static char[] subtract(char[] str1, char[] str2) { string res = \"\"; int n1 = str1.Length; int n2 = str2.Length; // To make subtraction easy Array.Reverse(str1); Array.Reverse(str2); int carry = 0; for (int i = 0; i < n2; i++) { // Subtract digit by bdigit int subst = ((str1[i] - '0') - (str2[i] - '0') - carry); if (subst < 0) { subst = subst + 10; carry = 1; } else carry = 0; // Change subst as character and // add it to result string res = res + (subst); } for (int i = n2; i < n1; i++) { int subst = ((str1[i] - '0') - carry); if (subst < 0) { subst = subst + 10; carry = 1; } else carry = 0; res += (subst); } // Reverse result to make it actual number char[] Res = res.ToCharArray(); Array.Reverse(Res); return Res; } static char[] NumberOfBishops(char[] a) { if (new string(a) == \"1\") return a; else { // Subtract 1 from number a = subtract(a, \"1\".ToCharArray()); //Console.WriteLine(new string(a)); // Reverse the string to make calculations easier Array.Reverse(a); int carry = 0; // Multiply by 2 for (int i = 0; i < a.Length; i++) { int tmp = a[i] - '0'; tmp *= 2; tmp += carry; a[i] = (char)('0' + (tmp % 10)); carry = tmp / 10; } string A = new string(a); if (carry > 0) A += ('0' + carry); char[] a1 = A.ToCharArray(); // Reverse the string to get actual result Array.Reverse(a1); // Return result return a1; } } // Driver code static void Main() { char[] a = \"12345678901234567890\".ToCharArray(); Console.WriteLine(new string(NumberOfBishops(a))); }} // This code is contributed by divyeshrabadiy07", "e": 11657, "s": 9656, "text": null }, { "code": "<script> // Javascript implementation of the approach function reverse(str){ let temp = new Array(str.length); // Fill character array backwards with // characters of the string for(let i = 0; i < str.length; i++) temp[str.length - i - 1] = str[i]; // Convert character array to string // and return it return temp;} // Function to return the difference of// two big numbers as Stringfunction subtract(str1,str2){ let res = \"\"; let n1 = str1.length; let n2 = str2.length; // To make subtraction easy str1 = reverse(str1); str2 = reverse(str2); let carry = 0; for(let i = 0; i < n2; i++) { // Subtract digit by bdigit let subst = (parseInt(str1[i]) - parseInt(str2[i]) - carry); if (subst < 0) { subst = subst + 10; carry = 1; } else carry = 0; // Change subst as character and // add it to result String res = res + (subst).toString(); } for(let i = n2; i < n1; i++) { let subst = (parseInt(str1[i]) - carry); if (subst < 0) { subst = subst + 10; carry = 1; } else carry = 0; res += (subst).toString(); } // Reverse result to make it actual number let Res = res.split(\"\"); Res = reverse(Res); return Res;} function NumberOfBishops(a){ if (a == \"1\") return a; else { // Subtract 1 from number a = subtract(a, \"1\"); //Console.WriteLine(new String(a)); // Reverse the String to make // calculations easier a = reverse(a); let carry = 0; // Multiply by 2 for(let i = 0; i < a.length; i++) { let tmp = parseInt(a[i]); tmp *= 2; tmp += carry; a[i] = (tmp % 10).toString(); carry = Math.floor(tmp / 10); } let A = a.join(\"\"); if (carry > 0) A += ( carry).toString(); let a1 = A.split(\"\"); // Reverse the String to get // actual result a1 = reverse(a1); // Return result return a1; }} // Driver codelet a = \"12345678901234567890\".split(\"\"); document.write(NumberOfBishops(a).join(\"\")); // This code is contributed by unknown2108.</script>", "e": 14132, "s": 11657, "text": null }, { "code": null, "e": 14153, "s": 14132, "text": "24691357802469135778" }, { "code": null, "e": 14170, "s": 14155, "text": "mohit kumar 29" }, { "code": null, "e": 14178, "s": 14170, "text": "ankthon" }, { "code": null, "e": 14188, "s": 14178, "text": "Code_Mech" }, { "code": null, "e": 14201, "s": 14188, "text": "rituraj_jain" }, { "code": null, "e": 14214, "s": 14201, "text": "Akanksha_Rai" }, { "code": null, "e": 14232, "s": 14214, "text": "divyeshrabadiya07" }, { "code": null, "e": 14242, "s": 14232, "text": "pratham76" }, { "code": null, "e": 14252, "s": 14242, "text": "patel2127" }, { "code": null, "e": 14264, "s": 14252, "text": "unknown2108" }, { "code": null, "e": 14284, "s": 14264, "text": "chessboard-problems" }, { "code": null, "e": 14291, "s": 14284, "text": "Matrix" }, { "code": null, "e": 14298, "s": 14291, "text": "Matrix" }, { "code": null, "e": 14396, "s": 14298, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 14434, "s": 14396, "text": "Unique paths in a Grid with Obstacles" }, { "code": null, "e": 14474, "s": 14434, "text": "Traverse a given Matrix using Recursion" }, { "code": null, "e": 14512, "s": 14474, "text": "Find median in row wise sorted matrix" }, { "code": null, "e": 14553, "s": 14512, "text": "Zigzag (or diagonal) traversal of Matrix" }, { "code": null, "e": 14579, "s": 14553, "text": "A Boolean Matrix Question" }, { "code": null, "e": 14610, "s": 14579, "text": "Find a specific pair in Matrix" }, { "code": null, "e": 14645, "s": 14610, "text": "Python program to add two Matrices" }, { "code": null, "e": 14691, "s": 14645, "text": "Common elements in all rows of a given matrix" }, { "code": null, "e": 14741, "s": 14691, "text": "Find shortest safe route in a path with landmines" } ]
Rearrange an array such that ‘arr[j]’ becomes ‘i’ if ‘arr[i]’ is ‘j’ | Set 1
03 Mar, 2022 Given an array of size n where all elements are distinct and in range from 0 to n-1, change contents of arr[] so that arr[i] = j is changed to arr[j] = i. Examples: Example 1: Input: arr[] = {1, 3, 0, 2}; Output: arr[] = {2, 0, 3, 1}; Explanation for the above output. Since arr[0] is 1, arr[1] is changed to 0 Since arr[1] is 3, arr[3] is changed to 1 Since arr[2] is 0, arr[0] is changed to 2 Since arr[3] is 2, arr[2] is changed to 3 Example 2: Input: arr[] = {2, 0, 1, 4, 5, 3}; Output: arr[] = {1, 2, 0, 5, 3, 4}; Example 3: Input: arr[] = {0, 1, 2, 3}; Output: arr[] = {0, 1, 2, 3}; Example 4: Input: arr[] = {3, 2, 1, 0}; Output: arr[] = {3, 2, 1, 0}; A Simple Solution is to create a temporary array and one by one copy ‘i’ to ‘temp[arr[i]]’ where i varies from 0 to n-1. Below is the implementation of the above idea. C++ C Java Python3 C# Javascript // A simple C++ program to rearrange contents of arr[]// such that arr[j] becomes j if arr[i] is j#include <bits/stdc++.h>using namespace std; // A simple method to rearrange 'arr[0..n-1]' so that 'arr[j]'// becomes 'i' if 'arr[i]' is 'j'void rearrangeNaive(int arr[], int n){ // Create an auxiliary array of same size int temp[n], i; // Store result in temp[] for (i = 0; i < n; i++) temp[arr[i]] = i; // Copy temp back to arr[] for (i = 0; i < n; i++) arr[i] = temp[i];} // A utility function to print contents of arr[0..n-1]void printArray(int arr[], int n){ int i; for (i = 0; i < n; i++) cout << ("%d ", arr[i]); cout << ("\n");} // Driver codeint main(){ int arr[] = { 1, 3, 0, 2 }; int n = sizeof(arr) / sizeof(arr[0]); cout << ("Given array is \n"); printArray(arr, n); rearrangeNaive(arr, n); cout << ("Modified array is \n"); printArray(arr, n); return 0;} // This code is contributed by Code_Mech // A simple C program to rearrange contents of arr[]// such that arr[j] becomes j if arr[i] is j#include <stdio.h> // A simple method to rearrange 'arr[0..n-1]' so that 'arr[j]'// becomes 'i' if 'arr[i]' is 'j'void rearrangeNaive(int arr[], int n){ // Create an auxiliary array of same size int temp[n], i; // Store result in temp[] for (i = 0; i < n; i++) temp[arr[i]] = i; // Copy temp back to arr[] for (i = 0; i < n; i++) arr[i] = temp[i];} // A utility function to print contents of arr[0..n-1]void printArray(int arr[], int n){ int i; for (i = 0; i < n; i++) printf("%d ", arr[i]); printf("\n");} // Driver programint main(){ int arr[] = { 1, 3, 0, 2 }; int n = sizeof(arr) / sizeof(arr[0]); printf("Given array is \n"); printArray(arr, n); rearrangeNaive(arr, n); printf("Modified array is \n"); printArray(arr, n); return 0;} // A simple Java program to rearrange contents of arr[]// such that arr[j] becomes j if arr[i] is jclass RearrangeArray { // A simple method to rearrange 'arr[0..n-1]' so that 'arr[j]' // becomes 'i' if 'arr[i]' is 'j' void rearrangeNaive(int arr[], int n) { // Create an auxiliary array of same size int temp[] = new int[n]; int i; // Store result in temp[] for (i = 0; i < n; i++) temp[arr[i]] = i; // Copy temp back to arr[] for (i = 0; i < n; i++) arr[i] = temp[i]; } // A utility function to print contents of arr[0..n-1] void printArray(int arr[], int n) { int i; for (i = 0; i < n; i++) { System.out.print(arr[i] + " "); } System.out.println(""); } // Driver program to test above functions public static void main(String[] args) { RearrangeArray arrange = new RearrangeArray(); int arr[] = { 1, 3, 0, 2 }; int n = arr.length; System.out.println("Given array is "); arrange.printArray(arr, n); arrange.rearrangeNaive(arr, n); System.out.println("Modified array is "); arrange.printArray(arr, n); }} # A simple Python3 program to rearrange# contents of arr[] such that arr[j]# becomes j if arr[i] is j # A simple method to rearrange# 'arr[0..n-1]' so that 'arr[j]'# becomes 'i' if 'arr[i]' is 'j'def rearrangeNaive(arr, n): # Create an auxiliary array # of same size temp = [0] * n # Store result in temp[] for i in range(0, n): temp[arr[i]] = i # Copy temp back to arr[] for i in range(0, n): arr[i] = temp[i] # A utility function to print # contents of arr[0..n-1]def printArray(arr, n): for i in range(0, n): print(arr[i], end = " ") # Driver programarr = [1, 3, 0, 2]n = len(arr)print("Given array is", end = " ")printArray(arr, n) rearrangeNaive(arr, n)print("\nModified array is", end = " ")printArray(arr, n) # This code is contributed by Smitha Dinesh Semwal // A simple C# program to rearrange contents of arr[]// such that arr[j] becomes j if arr[i] is j using System;class RearrangeArray { // A simple method to rearrange 'arr[0..n-1]' so that 'arr[j]' // becomes 'i' if 'arr[i]' is 'j' void rearrangeNaive(int[] arr, int n) { // Create an auxiliary array of same size int[] temp = new int[n]; int i; // Store result in temp[] for (i = 0; i < n; i++) temp[arr[i]] = i; // Copy temp back to arr[] for (i = 0; i < n; i++) arr[i] = temp[i]; } // A utility function to print contents of arr[0..n-1] void printArray(int[] arr, int n) { int i; for (i = 0; i < n; i++) { Console.Write(arr[i] + " "); } Console.WriteLine(""); } // Driver program to test above functions public static void Main() { RearrangeArray arrange = new RearrangeArray(); int[] arr = { 1, 3, 0, 2 }; int n = arr.Length; Console.WriteLine("Given array is "); arrange.printArray(arr, n); arrange.rearrangeNaive(arr, n); Console.WriteLine("Modified array is "); arrange.printArray(arr, n); }} <script> // A simple JavaScript program to rearrange contents of arr[]// such that arr[j] becomes j if arr[i] is j // A simple method to rearrange 'arr[0..n-1]' so that 'arr[j]'// becomes 'i' if 'arr[i]' is 'j'function rearrangeNaive(arr, n){ // Create an auxiliary array of same size let temp = new Array(n), i; // Store result in temp[] for (i = 0; i < n; i++) temp[arr[i]] = i; // Copy temp back to arr[] for (i = 0; i < n; i++) arr[i] = temp[i];} // A utility function to print contents of arr[0..n-1]function printArray(arr, n){ let i; for (i = 0; i < n; i++) document.write(" " + arr[i]); document.write("<br>");} // Driver code let arr = [ 1, 3, 0, 2 ]; let n = arr.length; document.write("Given array is <br>"); printArray(arr, n); rearrangeNaive(arr, n); document.write("Modified array is <br>"); printArray(arr, n); // This code is contributed by Surbhi Tyagi. </script> Output: Given array is 1 3 0 2 Modified array is 2 0 3 1 Time complexity: O(n) Auxiliary space :O(n) Can we solve this in O(n) time and O(1) auxiliary space? The idea is based on the fact that the modified array is basically a permutation of the input array. We can find the target permutation by storing the next item before updating it. Let us consider array ‘{1, 3, 0, 2}’ for example. We start with i = 0, arr[i] is 1. So we go to arr[1] and change it to 0 (because i is 0). Before we make the change, we store the old value of arr[1] as the old value is going to be our new index i. In the next iteration, we have i = 3, arr[3] is 2, so we change arr[2] to 3. Before making the change we store next i as old value of arr[2]. The below code gives idea about this approach. // This function works only when output is a permutation // with one cycle. void rearrangeUtil(int arr[], int n) { // 'val' is the value to be stored at 'arr[i]' int val = 0; // The next value is determined // using current index int i = arr[0]; // The next index is determined // using current value // While all elements in cycle are not processed while (i != 0) { // Store value at index as it is going to be // used as next index int new_i = arr[i]; // Update arr[] arr[i] = val; // Update value and index for next iteration val = i; i = new_i; } arr[0] = val; // Update the value at arr[0] } The above function doesn’t work for inputs like {2, 0, 1, 4, 5, 3}; as there are two cycles. One cycle is (2, 0, 1) and other cycle is (4, 5, 3). How to handle multiple cycles with the O(1) space constraint? The idea is to process all cycles one by one. To check whether an element is processed or not, we change the value of processed items arr[i] as -arr[i]. Since 0 can not be made negative, we first change all arr[i] to arr[i] + 1. In the end, we make all values positive and subtract 1 to get old values back. C++ C Java Python3 C# Javascript // A space efficient C++ program to rearrange contents of// arr[] such that arr[j] becomes j if arr[i] is j#include <iostream>using namespace std; // A utility function to rearrange elements in the cycle// starting at arr[i]. This function assumes values in// arr[] be from 1 to n. It changes arr[j-1] to i+1// if arr[i-1] is j+1void rearrangeUtil(int arr[], int n, int i){ // 'val' is the value to be stored at 'arr[i]' int val = -(i + 1); // The next value is determined // using current index i = arr[i] - 1; // The next index is determined // using current value // While all elements in cycle are not processed while (arr[i] > 0) { // Store value at index as it is going to be // used as next index int new_i = arr[i] - 1; // Update arr[] arr[i] = val; // Update value and index for next iteration val = -(i + 1); i = new_i; }} // A space efficient method to rearrange 'arr[0..n-1]'// so that 'arr[j]' becomes 'i' if 'arr[i]' is 'j'void rearrange(int arr[], int n){ // Increment all values by 1, so that all elements // can be made negative to mark them as visited int i; for (i = 0; i < n; i++) arr[i]++; // Process all cycles for (i = 0; i < n; i++) { // Process cycle starting at arr[i] if this cycle is // not already processed if (arr[i] > 0) rearrangeUtil(arr, n, i); } // Change sign and values of arr[] to get the original // values back, i.e., values in range from 0 to n-1 for (i = 0; i < n; i++) arr[i] = (-arr[i]) - 1;} // A utility function to print contents of arr[0..n-1]void printArray(int arr[], int n){ int i; for (i = 0; i < n; i++) cout << arr[i] << " "; cout << endl;} // Driver programint main(){ int arr[] = { 2, 0, 1, 4, 5, 3 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "Given array is " << endl; printArray(arr, n); rearrange(arr, n); cout << "Modified array is " << endl; printArray(arr, n); return 0;} // This code is contributed by shubhamsingh10 // A space efficient C program to rearrange contents of// arr[] such that arr[j] becomes j if arr[i] is j#include <stdio.h> // A utility function to rearrange elements in the cycle// starting at arr[i]. This function assumes values in// arr[] be from 1 to n. It changes arr[j-1] to i+1// if arr[i-1] is j+1void rearrangeUtil(int arr[], int n, int i){ // 'val' is the value to be stored at 'arr[i]' int val = -(i + 1); // The next value is determined // using current index i = arr[i] - 1; // The next index is determined // using current value // While all elements in cycle are not processed while (arr[i] > 0) { // Store value at index as it is going to be // used as next index int new_i = arr[i] - 1; // Update arr[] arr[i] = val; // Update value and index for next iteration val = -(i + 1); i = new_i; }} // A space efficient method to rearrange 'arr[0..n-1]'// so that 'arr[j]' becomes 'i' if 'arr[i]' is 'j'void rearrange(int arr[], int n){ // Increment all values by 1, so that all elements // can be made negative to mark them as visited int i; for (i = 0; i < n; i++) arr[i]++; // Process all cycles for (i = 0; i < n; i++) { // Process cycle starting at arr[i] if this cycle is // not already processed if (arr[i] > 0) rearrangeUtil(arr, n, i); } // Change sign and values of arr[] to get the original // values back, i.e., values in range from 0 to n-1 for (i = 0; i < n; i++) arr[i] = (-arr[i]) - 1;} // A utility function to print contents of arr[0..n-1]void printArray(int arr[], int n){ int i; for (i = 0; i < n; i++) printf("%d ", arr[i]); printf("\n");} // Driver programint main(){ int arr[] = { 2, 0, 1, 4, 5, 3 }; int n = sizeof(arr) / sizeof(arr[0]); printf("Given array is \n"); printArray(arr, n); rearrange(arr, n); printf("Modified array is \n"); printArray(arr, n); return 0;} // A space efficient Java program to rearrange contents of// arr[] such that arr[j] becomes j if arr[i] is j class RearrangeArray { // A utility function to rearrange elements in the cycle // starting at arr[i]. This function assumes values in // arr[] be from 1 to n. It changes arr[j-1] to i+1 // if arr[i-1] is j+1 void rearrangeUtil(int arr[], int n, int i) { // 'val' is the value to be stored at 'arr[i]' // The next value is determined using current index int val = -(i + 1); // The next index is determined // using current value i = arr[i] - 1; // While all elements in cycle are not processed while (arr[i] > 0) { // Store value at index as it is going to be // used as next index int new_i = arr[i] - 1; // Update arr[] arr[i] = val; // Update value and index for next iteration val = -(i + 1); i = new_i; } } // A space efficient method to rearrange 'arr[0..n-1]' // so that 'arr[j]' becomes 'i' if 'arr[i]' is 'j' void rearrange(int arr[], int n) { // Increment all values by 1, so that all elements // can be made negative to mark them as visited int i; for (i = 0; i < n; i++) arr[i]++; // Process all cycles for (i = 0; i < n; i++) { // Process cycle starting at arr[i] if this cycle is // not already processed if (arr[i] > 0) rearrangeUtil(arr, n, i); } // Change sign and values of arr[] to get the original // values back, i.e., values in range from 0 to n-1 for (i = 0; i < n; i++) arr[i] = (-arr[i]) - 1; } // A utility function to print contents of arr[0..n-1] void printArray(int arr[], int n) { int i; for (i = 0; i < n; i++) System.out.print(arr[i] + " "); System.out.println(""); } // Driver program public static void main(String[] args) { RearrangeArray arrange = new RearrangeArray(); int arr[] = { 2, 0, 1, 4, 5, 3 }; int n = arr.length; System.out.println("Given array is "); arrange.printArray(arr, n); arrange.rearrange(arr, n); System.out.println("Modified array is "); arrange.printArray(arr, n); }} # A space efficient Python3 program to# rearrange contents of arr such that# arr[j] becomes j if arr[i] is j # A utility function to rearrange elements# in the cycle starting at arr[i]. This# function assumes values in arr be from# 1 to n. It changes arr[j-1] to i+1 if# arr[i-1] is j+1def rearrangeUtil(arr, n, i): # 'val' is the value to be stored at # 'arr[i]' # The next value is determined using # current index val = -(i + 1) # The next index is determined using # current index i = arr[i] - 1 # While all elements in cycle are # not processed while (arr[i] > 0): # Store value at index as it is # going to be used as next index new_i = arr[i] - 1 # Update arr arr[i] = val # Update value and index for # next iteration val = -(i + 1) i = new_i # A space efficient method to rearrange# 'arr[0..n-1]' so that 'arr[j]' becomes# 'i' if 'arr[i]' is 'j'def rearrange(arr, n): # Increment all values by 1, so that # all elements can be made negative to # mark them as visited for i in range(n): arr[i] += 1 # Process all cycles for i in range(n): # Process cycle starting at arr[i] if # this cycle is not already processed if (arr[i] > 0): rearrangeUtil(arr, n, i) # Change sign and values of arr to # get the original values back, i.e., # values in range from 0 to n-1 for i in range(n): arr[i] = (-arr[i]) - 1 # A utility function to print contents o# f arr[0..n-1]def printArray(arr, n): for i in range(n): print(arr[i], end = " ") print() # Driver codearr = [ 2, 0, 1, 4, 5, 3 ]n = len(arr) print("Given array is ")printArray(arr, n) rearrange(arr, n) print("Modified array is ")printArray(arr, n) # This code is contributed by shubhamsingh10 // A simple C# program to// rearrange contents of arr[]// such that arr[j] becomes// j if arr[i] is jusing System; class GFG { // A simple method to rearrange // 'arr[0..n-1]' so that 'arr[j]' // becomes 'i' if 'arr[i]' is 'j' void rearrangeNaive(int[] arr, int n) { // Create an auxiliary // array of same size int[] temp = new int[n]; int i; // Store result in temp[] for (i = 0; i < n; i++) temp[arr[i]] = i; // Copy temp back to arr[] for (i = 0; i < n; i++) arr[i] = temp[i]; } // A utility function to // print contents of arr[0..n-1] void printArray(int[] arr, int n) { int i; for (i = 0; i < n; i++) { Console.Write(arr[i] + " "); } Console.WriteLine(""); } // Driver Code public static void Main() { GFG arrange = new GFG(); int[] arr = { 2, 0, 1, 4, 5, 3 }; int n = arr.Length; Console.WriteLine("Given array is "); arrange.printArray(arr, n); arrange.rearrangeNaive(arr, n); Console.WriteLine("Modified array is "); arrange.printArray(arr, n); }} // This code is contributed by anuj_67. <script> // A space efficient Javascript program to rearrange contents of// arr[] such that arr[j] becomes j if arr[i] is j // A utility function to rearrange elements in the cycle // starting at arr[i]. This function assumes values in // arr[] be from 1 to n. It changes arr[j-1] to i+1 // if arr[i-1] is j+1 function rearrangeUtil(arr,n,i) { // 'val' is the value to be stored at 'arr[i]' // The next value is determined using current index let val = -(i + 1); // The next index is determined // using current value i = arr[i] - 1; // While all elements in cycle are not processed while (arr[i] > 0) { // Store value at index as it is going to be // used as next index let new_i = arr[i] - 1; // Update arr[] arr[i] = val; // Update value and index for next iteration val = -(i + 1); i = new_i; } } // A space efficient method to rearrange 'arr[0..n-1]' // so that 'arr[j]' becomes 'i' if 'arr[i]' is 'j' function rearrange(arr,n) { // Increment all values by 1, so that all elements // can be made negative to mark them as visited let i; for (i = 0; i < n; i++) arr[i]++; // Process all cycles for (i = 0; i < n; i++) { // Process cycle starting at arr[i] if this cycle is // not already processed if (arr[i] > 0) rearrangeUtil(arr, n, i); } // Change sign and values of arr[] to get the original // values back, i.e., values in range from 0 to n-1 for (i = 0; i < n; i++) arr[i] = (-arr[i]) - 1; } // A utility function to print contents of arr[0..n-1] function printArray(arr,n) { let i; for (i = 0; i < n; i++) document.write(arr[i] + " "); document.write("<br>"); } // Driver program let arr=[2, 0, 1, 4, 5, 3]; let n = arr.length; document.write("Given array is <br>"); printArray(arr, n); rearrange(arr, n); document.write("Modified array is <br>"); printArray(arr, n); // This code is contributed by rag2127 </script> Output: Given array is 2 0 1 4 5 3 Modified array is 1 2 0 5 3 4 The time complexity of this method seems to be more than O(n) at first look. If we take a closer look, we can notice that no element is processed more than a constant number of times.Another Method: The idea is to store each element’s new and old value as quotient and remainder of n, respectively (n being the size of the array). For example, Suppose an element’s new value is 2, the old value is 1 and n is 3, then the element’s value is stored as 1 + 2*3 = 7. We can retrieve its old value by 7%3 = 1 and its new value by 7/3 = 2. Thanks Prateek Oraon for suggesting this method. C++ Java Python3 C# Javascript // A simple C++ program to rearrange// contents of arr[] such that arr[j]// becomes j if arr[i] is j#include <bits/stdc++.h>using namespace std; // A simple method to rearrange// 'arr[0..n-1]' so that 'arr[j]'// becomes 'i' if 'arr[i]' is 'j'void rearrange(int arr[], int n){ for (int i = 0; i < n; i++) { // retrieving old value and // storing with the new one arr[arr[i] % n] += i * n; } for (int i = 0; i < n; i++) { // retrieving new value arr[i] /= n; }} // A utility function to print// contents of arr[0..n-1]void printArray(int arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i] << " "; cout << endl;} // Driver programint main(){ int arr[] = { 2, 0, 1, 4, 5, 3 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "Given array is : " << endl; printArray(arr, n); rearrange(arr, n); cout << "Modified array is :" << endl; printArray(arr, n); return 0;} // A simple JAVA program to rearrange// contents of arr[] such that arr[j]// becomes j if arr[i] is j class GFG { // A simple method to rearrange // 'arr[0..n-1]' so that 'arr[j]' // becomes 'i' if 'arr[i]' is 'j' static void rearrange(int arr[], int n) { for (int i = 0; i < n; i++) { // retrieving old value and // storing with the new one arr[arr[i] % n] += i * n; } for (int i = 0; i < n; i++) { // retrieving new value arr[i] /= n; } } // A utility function to print // contents of arr[0..n-1] static void printArray(int arr[], int n) { for (int i = 0; i < n; i++) { System.out.print(arr[i] + " "); } System.out.println(); } // Driver code public static void main(String[] args) { int arr[] = { 2, 0, 1, 4, 5, 3 }; int n = arr.length; System.out.println("Given array is : "); printArray(arr, n); rearrange(arr, n); System.out.println("Modified array is :"); printArray(arr, n); }} // This code has been contributed by 29AjayKumar # A simple Python3 program to rearrange# contents of arr[] such that arr[j]# becomes j if arr[i] is j # A simple method to rearrange# 'arr[0..n-1]' so that 'arr[j]'# becomes 'i' if 'arr[i]' is 'j'def rearrange(arr, n): for i in range(n): # Retrieving old value and # storing with the new one arr[arr[i] % n] += i * n for i in range(n): # Retrieving new value arr[i] //= n # A utility function to pr# contents of arr[0..n-1]def printArray(arr, n): for i in range(n): print(arr[i], end = " ") print() # Driver codearr = [2, 0, 1, 4, 5, 3]n = len(arr) print("Given array is : ")printArray(arr, n) rearrange(arr, n) print("Modified array is :")printArray(arr, n) # This code is contributed by shubhamsingh10 // A simple C# program to rearrange// contents of arr[] such that arr[j]// becomes j if arr[i] is jusing System; class GFG{ // A simple method to rearrange // 'arr[0..n-1]' so that 'arr[j]' // becomes 'i' if 'arr[i]' is 'j' static void rearrange(int[] arr, int n) { for (int i = 0; i < n; i++) { // retrieving old value and // storing with the new one arr[arr[i] % n] += i * n; } for (int i = 0; i < n; i++) { // retrieving new value arr[i] /= n; } } // A utility function to print // contents of arr[0..n-1] static void printArray(int[] arr, int n) { for (int i = 0; i < n; i++) Console.Write(arr[i] + " "); Console.WriteLine(); } // Driver program static public void Main () { int[] arr = { 2, 0, 1, 4, 5, 3 }; int n = arr.Length; Console.WriteLine("Given array is : "); printArray(arr, n); rearrange(arr, n); Console.WriteLine("Modified array is :"); printArray(arr, n); }} // This code is contributed by shubhamsingh10 <script> // A simple javascript program to rearrange// contents of arr such that arr[j]// becomes j if arr[i] is j // A simple method to rearrange// 'arr[0..n-1]' so that 'arr[j]'// becomes 'i' if 'arr[i]' is 'j'function rearrange(arr , n){ for (i = 0; i < n; i++) { // retrieving old value and // storing with the new one arr[arr[i] % n] += i * n; } for (i = 0; i < n; i++) { // retrieving new value arr[i] = parseInt(arr[i]/n); }} // A utility function to print// contents of arr[0..n-1]function printArray(arr , n){ for (i = 0; i < n; i++) { document.write(arr[i] + " "); } document.write();} // Driver codevar arr = [ 2, 0, 1, 4, 5, 3 ];var n = arr.length; document.write("Given array is : " + "<br>");printArray(arr, n); rearrange(arr, n);document.write("<br>") document.write("Modified array is : " + "<br>");printArray(arr, n); // This code contributed by Rajput-Ji </script> Output: Given array is : 2 0 1 4 5 3 Modified array is : 1 2 0 5 3 4 Time Complexity : O(n)Auxiliary Space : O(1) This article is contributed by Arun Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above PrateekOraon vt_m ukasp 29AjayKumar Code_Mech nidhi_biet SHUBHAMSINGH10 surbhityagi15 rag2127 Rajput-Ji surinderdawra388 simmytarika5 singhh3010 Arrays Arrays 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 Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Introduction to Arrays K'th Smallest/Largest Element in Unsorted Array | Set 1 Subset Sum Problem | DP-25 Introduction to Data Structures
[ { "code": null, "e": 52, "s": 24, "text": "\n03 Mar, 2022" }, { "code": null, "e": 219, "s": 52, "text": "Given an array of size n where all elements are distinct and in range from 0 to n-1, change contents of arr[] so that arr[i] = j is changed to arr[j] = i. Examples: " }, { "code": null, "e": 720, "s": 219, "text": "Example 1:\nInput: arr[] = {1, 3, 0, 2};\nOutput: arr[] = {2, 0, 3, 1};\nExplanation for the above output.\nSince arr[0] is 1, arr[1] is changed to 0\nSince arr[1] is 3, arr[3] is changed to 1\nSince arr[2] is 0, arr[0] is changed to 2\nSince arr[3] is 2, arr[2] is changed to 3\n\nExample 2:\nInput: arr[] = {2, 0, 1, 4, 5, 3};\nOutput: arr[] = {1, 2, 0, 5, 3, 4};\n\nExample 3:\nInput: arr[] = {0, 1, 2, 3};\nOutput: arr[] = {0, 1, 2, 3};\n\nExample 4:\nInput: arr[] = {3, 2, 1, 0};\nOutput: arr[] = {3, 2, 1, 0};" }, { "code": null, "e": 892, "s": 722, "text": "A Simple Solution is to create a temporary array and one by one copy ‘i’ to ‘temp[arr[i]]’ where i varies from 0 to n-1. Below is the implementation of the above idea. " }, { "code": null, "e": 896, "s": 892, "text": "C++" }, { "code": null, "e": 898, "s": 896, "text": "C" }, { "code": null, "e": 903, "s": 898, "text": "Java" }, { "code": null, "e": 911, "s": 903, "text": "Python3" }, { "code": null, "e": 914, "s": 911, "text": "C#" }, { "code": null, "e": 925, "s": 914, "text": "Javascript" }, { "code": "// A simple C++ program to rearrange contents of arr[]// such that arr[j] becomes j if arr[i] is j#include <bits/stdc++.h>using namespace std; // A simple method to rearrange 'arr[0..n-1]' so that 'arr[j]'// becomes 'i' if 'arr[i]' is 'j'void rearrangeNaive(int arr[], int n){ // Create an auxiliary array of same size int temp[n], i; // Store result in temp[] for (i = 0; i < n; i++) temp[arr[i]] = i; // Copy temp back to arr[] for (i = 0; i < n; i++) arr[i] = temp[i];} // A utility function to print contents of arr[0..n-1]void printArray(int arr[], int n){ int i; for (i = 0; i < n; i++) cout << (\"%d \", arr[i]); cout << (\"\\n\");} // Driver codeint main(){ int arr[] = { 1, 3, 0, 2 }; int n = sizeof(arr) / sizeof(arr[0]); cout << (\"Given array is \\n\"); printArray(arr, n); rearrangeNaive(arr, n); cout << (\"Modified array is \\n\"); printArray(arr, n); return 0;} // This code is contributed by Code_Mech", "e": 1910, "s": 925, "text": null }, { "code": "// A simple C program to rearrange contents of arr[]// such that arr[j] becomes j if arr[i] is j#include <stdio.h> // A simple method to rearrange 'arr[0..n-1]' so that 'arr[j]'// becomes 'i' if 'arr[i]' is 'j'void rearrangeNaive(int arr[], int n){ // Create an auxiliary array of same size int temp[n], i; // Store result in temp[] for (i = 0; i < n; i++) temp[arr[i]] = i; // Copy temp back to arr[] for (i = 0; i < n; i++) arr[i] = temp[i];} // A utility function to print contents of arr[0..n-1]void printArray(int arr[], int n){ int i; for (i = 0; i < n; i++) printf(\"%d \", arr[i]); printf(\"\\n\");} // Driver programint main(){ int arr[] = { 1, 3, 0, 2 }; int n = sizeof(arr) / sizeof(arr[0]); printf(\"Given array is \\n\"); printArray(arr, n); rearrangeNaive(arr, n); printf(\"Modified array is \\n\"); printArray(arr, n); return 0;}", "e": 2821, "s": 1910, "text": null }, { "code": "// A simple Java program to rearrange contents of arr[]// such that arr[j] becomes j if arr[i] is jclass RearrangeArray { // A simple method to rearrange 'arr[0..n-1]' so that 'arr[j]' // becomes 'i' if 'arr[i]' is 'j' void rearrangeNaive(int arr[], int n) { // Create an auxiliary array of same size int temp[] = new int[n]; int i; // Store result in temp[] for (i = 0; i < n; i++) temp[arr[i]] = i; // Copy temp back to arr[] for (i = 0; i < n; i++) arr[i] = temp[i]; } // A utility function to print contents of arr[0..n-1] void printArray(int arr[], int n) { int i; for (i = 0; i < n; i++) { System.out.print(arr[i] + \" \"); } System.out.println(\"\"); } // Driver program to test above functions public static void main(String[] args) { RearrangeArray arrange = new RearrangeArray(); int arr[] = { 1, 3, 0, 2 }; int n = arr.length; System.out.println(\"Given array is \"); arrange.printArray(arr, n); arrange.rearrangeNaive(arr, n); System.out.println(\"Modified array is \"); arrange.printArray(arr, n); }}", "e": 4039, "s": 2821, "text": null }, { "code": "# A simple Python3 program to rearrange# contents of arr[] such that arr[j]# becomes j if arr[i] is j # A simple method to rearrange# 'arr[0..n-1]' so that 'arr[j]'# becomes 'i' if 'arr[i]' is 'j'def rearrangeNaive(arr, n): # Create an auxiliary array # of same size temp = [0] * n # Store result in temp[] for i in range(0, n): temp[arr[i]] = i # Copy temp back to arr[] for i in range(0, n): arr[i] = temp[i] # A utility function to print # contents of arr[0..n-1]def printArray(arr, n): for i in range(0, n): print(arr[i], end = \" \") # Driver programarr = [1, 3, 0, 2]n = len(arr)print(\"Given array is\", end = \" \")printArray(arr, n) rearrangeNaive(arr, n)print(\"\\nModified array is\", end = \" \")printArray(arr, n) # This code is contributed by Smitha Dinesh Semwal", "e": 4866, "s": 4039, "text": null }, { "code": "// A simple C# program to rearrange contents of arr[]// such that arr[j] becomes j if arr[i] is j using System;class RearrangeArray { // A simple method to rearrange 'arr[0..n-1]' so that 'arr[j]' // becomes 'i' if 'arr[i]' is 'j' void rearrangeNaive(int[] arr, int n) { // Create an auxiliary array of same size int[] temp = new int[n]; int i; // Store result in temp[] for (i = 0; i < n; i++) temp[arr[i]] = i; // Copy temp back to arr[] for (i = 0; i < n; i++) arr[i] = temp[i]; } // A utility function to print contents of arr[0..n-1] void printArray(int[] arr, int n) { int i; for (i = 0; i < n; i++) { Console.Write(arr[i] + \" \"); } Console.WriteLine(\"\"); } // Driver program to test above functions public static void Main() { RearrangeArray arrange = new RearrangeArray(); int[] arr = { 1, 3, 0, 2 }; int n = arr.Length; Console.WriteLine(\"Given array is \"); arrange.printArray(arr, n); arrange.rearrangeNaive(arr, n); Console.WriteLine(\"Modified array is \"); arrange.printArray(arr, n); }}", "e": 6077, "s": 4866, "text": null }, { "code": "<script> // A simple JavaScript program to rearrange contents of arr[]// such that arr[j] becomes j if arr[i] is j // A simple method to rearrange 'arr[0..n-1]' so that 'arr[j]'// becomes 'i' if 'arr[i]' is 'j'function rearrangeNaive(arr, n){ // Create an auxiliary array of same size let temp = new Array(n), i; // Store result in temp[] for (i = 0; i < n; i++) temp[arr[i]] = i; // Copy temp back to arr[] for (i = 0; i < n; i++) arr[i] = temp[i];} // A utility function to print contents of arr[0..n-1]function printArray(arr, n){ let i; for (i = 0; i < n; i++) document.write(\" \" + arr[i]); document.write(\"<br>\");} // Driver code let arr = [ 1, 3, 0, 2 ]; let n = arr.length; document.write(\"Given array is <br>\"); printArray(arr, n); rearrangeNaive(arr, n); document.write(\"Modified array is <br>\"); printArray(arr, n); // This code is contributed by Surbhi Tyagi. </script>", "e": 7032, "s": 6077, "text": null }, { "code": null, "e": 7041, "s": 7032, "text": "Output: " }, { "code": null, "e": 7090, "s": 7041, "text": "Given array is\n1 3 0 2\nModified array is\n2 0 3 1" }, { "code": null, "e": 7113, "s": 7090, "text": "Time complexity: O(n) " }, { "code": null, "e": 7135, "s": 7113, "text": "Auxiliary space :O(n)" }, { "code": null, "e": 7813, "s": 7135, "text": "Can we solve this in O(n) time and O(1) auxiliary space? The idea is based on the fact that the modified array is basically a permutation of the input array. We can find the target permutation by storing the next item before updating it. Let us consider array ‘{1, 3, 0, 2}’ for example. We start with i = 0, arr[i] is 1. So we go to arr[1] and change it to 0 (because i is 0). Before we make the change, we store the old value of arr[1] as the old value is going to be our new index i. In the next iteration, we have i = 3, arr[3] is 2, so we change arr[2] to 3. Before making the change we store next i as old value of arr[2]. The below code gives idea about this approach. " }, { "code": null, "e": 8553, "s": 7813, "text": "// This function works only when output is a permutation\n// with one cycle.\nvoid rearrangeUtil(int arr[], int n)\n{\n // 'val' is the value to be stored at 'arr[i]'\n int val = 0; // The next value is determined\n // using current index\n int i = arr[0]; // The next index is determined\n // using current value\n\n // While all elements in cycle are not processed\n while (i != 0)\n {\n // Store value at index as it is going to be\n // used as next index\n int new_i = arr[i];\n\n // Update arr[]\n arr[i] = val;\n\n // Update value and index for next iteration\n val = i;\n i = new_i;\n }\n\n arr[0] = val; // Update the value at arr[0]\n}" }, { "code": null, "e": 9071, "s": 8553, "text": "The above function doesn’t work for inputs like {2, 0, 1, 4, 5, 3}; as there are two cycles. One cycle is (2, 0, 1) and other cycle is (4, 5, 3). How to handle multiple cycles with the O(1) space constraint? The idea is to process all cycles one by one. To check whether an element is processed or not, we change the value of processed items arr[i] as -arr[i]. Since 0 can not be made negative, we first change all arr[i] to arr[i] + 1. In the end, we make all values positive and subtract 1 to get old values back. " }, { "code": null, "e": 9075, "s": 9071, "text": "C++" }, { "code": null, "e": 9077, "s": 9075, "text": "C" }, { "code": null, "e": 9082, "s": 9077, "text": "Java" }, { "code": null, "e": 9090, "s": 9082, "text": "Python3" }, { "code": null, "e": 9093, "s": 9090, "text": "C#" }, { "code": null, "e": 9104, "s": 9093, "text": "Javascript" }, { "code": "// A space efficient C++ program to rearrange contents of// arr[] such that arr[j] becomes j if arr[i] is j#include <iostream>using namespace std; // A utility function to rearrange elements in the cycle// starting at arr[i]. This function assumes values in// arr[] be from 1 to n. It changes arr[j-1] to i+1// if arr[i-1] is j+1void rearrangeUtil(int arr[], int n, int i){ // 'val' is the value to be stored at 'arr[i]' int val = -(i + 1); // The next value is determined // using current index i = arr[i] - 1; // The next index is determined // using current value // While all elements in cycle are not processed while (arr[i] > 0) { // Store value at index as it is going to be // used as next index int new_i = arr[i] - 1; // Update arr[] arr[i] = val; // Update value and index for next iteration val = -(i + 1); i = new_i; }} // A space efficient method to rearrange 'arr[0..n-1]'// so that 'arr[j]' becomes 'i' if 'arr[i]' is 'j'void rearrange(int arr[], int n){ // Increment all values by 1, so that all elements // can be made negative to mark them as visited int i; for (i = 0; i < n; i++) arr[i]++; // Process all cycles for (i = 0; i < n; i++) { // Process cycle starting at arr[i] if this cycle is // not already processed if (arr[i] > 0) rearrangeUtil(arr, n, i); } // Change sign and values of arr[] to get the original // values back, i.e., values in range from 0 to n-1 for (i = 0; i < n; i++) arr[i] = (-arr[i]) - 1;} // A utility function to print contents of arr[0..n-1]void printArray(int arr[], int n){ int i; for (i = 0; i < n; i++) cout << arr[i] << \" \"; cout << endl;} // Driver programint main(){ int arr[] = { 2, 0, 1, 4, 5, 3 }; int n = sizeof(arr) / sizeof(arr[0]); cout << \"Given array is \" << endl; printArray(arr, n); rearrange(arr, n); cout << \"Modified array is \" << endl; printArray(arr, n); return 0;} // This code is contributed by shubhamsingh10", "e": 11217, "s": 9104, "text": null }, { "code": "// A space efficient C program to rearrange contents of// arr[] such that arr[j] becomes j if arr[i] is j#include <stdio.h> // A utility function to rearrange elements in the cycle// starting at arr[i]. This function assumes values in// arr[] be from 1 to n. It changes arr[j-1] to i+1// if arr[i-1] is j+1void rearrangeUtil(int arr[], int n, int i){ // 'val' is the value to be stored at 'arr[i]' int val = -(i + 1); // The next value is determined // using current index i = arr[i] - 1; // The next index is determined // using current value // While all elements in cycle are not processed while (arr[i] > 0) { // Store value at index as it is going to be // used as next index int new_i = arr[i] - 1; // Update arr[] arr[i] = val; // Update value and index for next iteration val = -(i + 1); i = new_i; }} // A space efficient method to rearrange 'arr[0..n-1]'// so that 'arr[j]' becomes 'i' if 'arr[i]' is 'j'void rearrange(int arr[], int n){ // Increment all values by 1, so that all elements // can be made negative to mark them as visited int i; for (i = 0; i < n; i++) arr[i]++; // Process all cycles for (i = 0; i < n; i++) { // Process cycle starting at arr[i] if this cycle is // not already processed if (arr[i] > 0) rearrangeUtil(arr, n, i); } // Change sign and values of arr[] to get the original // values back, i.e., values in range from 0 to n-1 for (i = 0; i < n; i++) arr[i] = (-arr[i]) - 1;} // A utility function to print contents of arr[0..n-1]void printArray(int arr[], int n){ int i; for (i = 0; i < n; i++) printf(\"%d \", arr[i]); printf(\"\\n\");} // Driver programint main(){ int arr[] = { 2, 0, 1, 4, 5, 3 }; int n = sizeof(arr) / sizeof(arr[0]); printf(\"Given array is \\n\"); printArray(arr, n); rearrange(arr, n); printf(\"Modified array is \\n\"); printArray(arr, n); return 0;}", "e": 13226, "s": 11217, "text": null }, { "code": "// A space efficient Java program to rearrange contents of// arr[] such that arr[j] becomes j if arr[i] is j class RearrangeArray { // A utility function to rearrange elements in the cycle // starting at arr[i]. This function assumes values in // arr[] be from 1 to n. It changes arr[j-1] to i+1 // if arr[i-1] is j+1 void rearrangeUtil(int arr[], int n, int i) { // 'val' is the value to be stored at 'arr[i]' // The next value is determined using current index int val = -(i + 1); // The next index is determined // using current value i = arr[i] - 1; // While all elements in cycle are not processed while (arr[i] > 0) { // Store value at index as it is going to be // used as next index int new_i = arr[i] - 1; // Update arr[] arr[i] = val; // Update value and index for next iteration val = -(i + 1); i = new_i; } } // A space efficient method to rearrange 'arr[0..n-1]' // so that 'arr[j]' becomes 'i' if 'arr[i]' is 'j' void rearrange(int arr[], int n) { // Increment all values by 1, so that all elements // can be made negative to mark them as visited int i; for (i = 0; i < n; i++) arr[i]++; // Process all cycles for (i = 0; i < n; i++) { // Process cycle starting at arr[i] if this cycle is // not already processed if (arr[i] > 0) rearrangeUtil(arr, n, i); } // Change sign and values of arr[] to get the original // values back, i.e., values in range from 0 to n-1 for (i = 0; i < n; i++) arr[i] = (-arr[i]) - 1; } // A utility function to print contents of arr[0..n-1] void printArray(int arr[], int n) { int i; for (i = 0; i < n; i++) System.out.print(arr[i] + \" \"); System.out.println(\"\"); } // Driver program public static void main(String[] args) { RearrangeArray arrange = new RearrangeArray(); int arr[] = { 2, 0, 1, 4, 5, 3 }; int n = arr.length; System.out.println(\"Given array is \"); arrange.printArray(arr, n); arrange.rearrange(arr, n); System.out.println(\"Modified array is \"); arrange.printArray(arr, n); }}", "e": 15615, "s": 13226, "text": null }, { "code": "# A space efficient Python3 program to# rearrange contents of arr such that# arr[j] becomes j if arr[i] is j # A utility function to rearrange elements# in the cycle starting at arr[i]. This# function assumes values in arr be from# 1 to n. It changes arr[j-1] to i+1 if# arr[i-1] is j+1def rearrangeUtil(arr, n, i): # 'val' is the value to be stored at # 'arr[i]' # The next value is determined using # current index val = -(i + 1) # The next index is determined using # current index i = arr[i] - 1 # While all elements in cycle are # not processed while (arr[i] > 0): # Store value at index as it is # going to be used as next index new_i = arr[i] - 1 # Update arr arr[i] = val # Update value and index for # next iteration val = -(i + 1) i = new_i # A space efficient method to rearrange# 'arr[0..n-1]' so that 'arr[j]' becomes# 'i' if 'arr[i]' is 'j'def rearrange(arr, n): # Increment all values by 1, so that # all elements can be made negative to # mark them as visited for i in range(n): arr[i] += 1 # Process all cycles for i in range(n): # Process cycle starting at arr[i] if # this cycle is not already processed if (arr[i] > 0): rearrangeUtil(arr, n, i) # Change sign and values of arr to # get the original values back, i.e., # values in range from 0 to n-1 for i in range(n): arr[i] = (-arr[i]) - 1 # A utility function to print contents o# f arr[0..n-1]def printArray(arr, n): for i in range(n): print(arr[i], end = \" \") print() # Driver codearr = [ 2, 0, 1, 4, 5, 3 ]n = len(arr) print(\"Given array is \")printArray(arr, n) rearrange(arr, n) print(\"Modified array is \")printArray(arr, n) # This code is contributed by shubhamsingh10", "e": 17523, "s": 15615, "text": null }, { "code": "// A simple C# program to// rearrange contents of arr[]// such that arr[j] becomes// j if arr[i] is jusing System; class GFG { // A simple method to rearrange // 'arr[0..n-1]' so that 'arr[j]' // becomes 'i' if 'arr[i]' is 'j' void rearrangeNaive(int[] arr, int n) { // Create an auxiliary // array of same size int[] temp = new int[n]; int i; // Store result in temp[] for (i = 0; i < n; i++) temp[arr[i]] = i; // Copy temp back to arr[] for (i = 0; i < n; i++) arr[i] = temp[i]; } // A utility function to // print contents of arr[0..n-1] void printArray(int[] arr, int n) { int i; for (i = 0; i < n; i++) { Console.Write(arr[i] + \" \"); } Console.WriteLine(\"\"); } // Driver Code public static void Main() { GFG arrange = new GFG(); int[] arr = { 2, 0, 1, 4, 5, 3 }; int n = arr.Length; Console.WriteLine(\"Given array is \"); arrange.printArray(arr, n); arrange.rearrangeNaive(arr, n); Console.WriteLine(\"Modified array is \"); arrange.printArray(arr, n); }} // This code is contributed by anuj_67.", "e": 18769, "s": 17523, "text": null }, { "code": "<script> // A space efficient Javascript program to rearrange contents of// arr[] such that arr[j] becomes j if arr[i] is j // A utility function to rearrange elements in the cycle // starting at arr[i]. This function assumes values in // arr[] be from 1 to n. It changes arr[j-1] to i+1 // if arr[i-1] is j+1 function rearrangeUtil(arr,n,i) { // 'val' is the value to be stored at 'arr[i]' // The next value is determined using current index let val = -(i + 1); // The next index is determined // using current value i = arr[i] - 1; // While all elements in cycle are not processed while (arr[i] > 0) { // Store value at index as it is going to be // used as next index let new_i = arr[i] - 1; // Update arr[] arr[i] = val; // Update value and index for next iteration val = -(i + 1); i = new_i; } } // A space efficient method to rearrange 'arr[0..n-1]' // so that 'arr[j]' becomes 'i' if 'arr[i]' is 'j' function rearrange(arr,n) { // Increment all values by 1, so that all elements // can be made negative to mark them as visited let i; for (i = 0; i < n; i++) arr[i]++; // Process all cycles for (i = 0; i < n; i++) { // Process cycle starting at arr[i] if this cycle is // not already processed if (arr[i] > 0) rearrangeUtil(arr, n, i); } // Change sign and values of arr[] to get the original // values back, i.e., values in range from 0 to n-1 for (i = 0; i < n; i++) arr[i] = (-arr[i]) - 1; } // A utility function to print contents of arr[0..n-1] function printArray(arr,n) { let i; for (i = 0; i < n; i++) document.write(arr[i] + \" \"); document.write(\"<br>\"); } // Driver program let arr=[2, 0, 1, 4, 5, 3]; let n = arr.length; document.write(\"Given array is <br>\"); printArray(arr, n); rearrange(arr, n); document.write(\"Modified array is <br>\"); printArray(arr, n); // This code is contributed by rag2127 </script>", "e": 21055, "s": 18769, "text": null }, { "code": null, "e": 21064, "s": 21055, "text": "Output: " }, { "code": null, "e": 21122, "s": 21064, "text": "Given array is\n2 0 1 4 5 3\nModified array is\n1 2 0 5 3 4 " }, { "code": null, "e": 21707, "s": 21122, "text": "The time complexity of this method seems to be more than O(n) at first look. If we take a closer look, we can notice that no element is processed more than a constant number of times.Another Method: The idea is to store each element’s new and old value as quotient and remainder of n, respectively (n being the size of the array). For example, Suppose an element’s new value is 2, the old value is 1 and n is 3, then the element’s value is stored as 1 + 2*3 = 7. We can retrieve its old value by 7%3 = 1 and its new value by 7/3 = 2. Thanks Prateek Oraon for suggesting this method. " }, { "code": null, "e": 21711, "s": 21707, "text": "C++" }, { "code": null, "e": 21716, "s": 21711, "text": "Java" }, { "code": null, "e": 21724, "s": 21716, "text": "Python3" }, { "code": null, "e": 21727, "s": 21724, "text": "C#" }, { "code": null, "e": 21738, "s": 21727, "text": "Javascript" }, { "code": "// A simple C++ program to rearrange// contents of arr[] such that arr[j]// becomes j if arr[i] is j#include <bits/stdc++.h>using namespace std; // A simple method to rearrange// 'arr[0..n-1]' so that 'arr[j]'// becomes 'i' if 'arr[i]' is 'j'void rearrange(int arr[], int n){ for (int i = 0; i < n; i++) { // retrieving old value and // storing with the new one arr[arr[i] % n] += i * n; } for (int i = 0; i < n; i++) { // retrieving new value arr[i] /= n; }} // A utility function to print// contents of arr[0..n-1]void printArray(int arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i] << \" \"; cout << endl;} // Driver programint main(){ int arr[] = { 2, 0, 1, 4, 5, 3 }; int n = sizeof(arr) / sizeof(arr[0]); cout << \"Given array is : \" << endl; printArray(arr, n); rearrange(arr, n); cout << \"Modified array is :\" << endl; printArray(arr, n); return 0;}", "e": 22694, "s": 21738, "text": null }, { "code": "// A simple JAVA program to rearrange// contents of arr[] such that arr[j]// becomes j if arr[i] is j class GFG { // A simple method to rearrange // 'arr[0..n-1]' so that 'arr[j]' // becomes 'i' if 'arr[i]' is 'j' static void rearrange(int arr[], int n) { for (int i = 0; i < n; i++) { // retrieving old value and // storing with the new one arr[arr[i] % n] += i * n; } for (int i = 0; i < n; i++) { // retrieving new value arr[i] /= n; } } // A utility function to print // contents of arr[0..n-1] static void printArray(int arr[], int n) { for (int i = 0; i < n; i++) { System.out.print(arr[i] + \" \"); } System.out.println(); } // Driver code public static void main(String[] args) { int arr[] = { 2, 0, 1, 4, 5, 3 }; int n = arr.length; System.out.println(\"Given array is : \"); printArray(arr, n); rearrange(arr, n); System.out.println(\"Modified array is :\"); printArray(arr, n); }} // This code has been contributed by 29AjayKumar", "e": 23848, "s": 22694, "text": null }, { "code": "# A simple Python3 program to rearrange# contents of arr[] such that arr[j]# becomes j if arr[i] is j # A simple method to rearrange# 'arr[0..n-1]' so that 'arr[j]'# becomes 'i' if 'arr[i]' is 'j'def rearrange(arr, n): for i in range(n): # Retrieving old value and # storing with the new one arr[arr[i] % n] += i * n for i in range(n): # Retrieving new value arr[i] //= n # A utility function to pr# contents of arr[0..n-1]def printArray(arr, n): for i in range(n): print(arr[i], end = \" \") print() # Driver codearr = [2, 0, 1, 4, 5, 3]n = len(arr) print(\"Given array is : \")printArray(arr, n) rearrange(arr, n) print(\"Modified array is :\")printArray(arr, n) # This code is contributed by shubhamsingh10", "e": 24643, "s": 23848, "text": null }, { "code": "// A simple C# program to rearrange// contents of arr[] such that arr[j]// becomes j if arr[i] is jusing System; class GFG{ // A simple method to rearrange // 'arr[0..n-1]' so that 'arr[j]' // becomes 'i' if 'arr[i]' is 'j' static void rearrange(int[] arr, int n) { for (int i = 0; i < n; i++) { // retrieving old value and // storing with the new one arr[arr[i] % n] += i * n; } for (int i = 0; i < n; i++) { // retrieving new value arr[i] /= n; } } // A utility function to print // contents of arr[0..n-1] static void printArray(int[] arr, int n) { for (int i = 0; i < n; i++) Console.Write(arr[i] + \" \"); Console.WriteLine(); } // Driver program static public void Main () { int[] arr = { 2, 0, 1, 4, 5, 3 }; int n = arr.Length; Console.WriteLine(\"Given array is : \"); printArray(arr, n); rearrange(arr, n); Console.WriteLine(\"Modified array is :\"); printArray(arr, n); }} // This code is contributed by shubhamsingh10", "e": 25814, "s": 24643, "text": null }, { "code": "<script> // A simple javascript program to rearrange// contents of arr such that arr[j]// becomes j if arr[i] is j // A simple method to rearrange// 'arr[0..n-1]' so that 'arr[j]'// becomes 'i' if 'arr[i]' is 'j'function rearrange(arr , n){ for (i = 0; i < n; i++) { // retrieving old value and // storing with the new one arr[arr[i] % n] += i * n; } for (i = 0; i < n; i++) { // retrieving new value arr[i] = parseInt(arr[i]/n); }} // A utility function to print// contents of arr[0..n-1]function printArray(arr , n){ for (i = 0; i < n; i++) { document.write(arr[i] + \" \"); } document.write();} // Driver codevar arr = [ 2, 0, 1, 4, 5, 3 ];var n = arr.length; document.write(\"Given array is : \" + \"<br>\");printArray(arr, n); rearrange(arr, n);document.write(\"<br>\") document.write(\"Modified array is : \" + \"<br>\");printArray(arr, n); // This code contributed by Rajput-Ji </script>", "e": 26765, "s": 25814, "text": null }, { "code": null, "e": 26774, "s": 26765, "text": "Output: " }, { "code": null, "e": 26838, "s": 26774, "text": "Given array is : \n2 0 1 4 5 3 \nModified array is :\n1 2 0 5 3 4 " }, { "code": null, "e": 26883, "s": 26838, "text": "Time Complexity : O(n)Auxiliary Space : O(1)" }, { "code": null, "e": 27051, "s": 26883, "text": "This article is contributed by Arun Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 27064, "s": 27051, "text": "PrateekOraon" }, { "code": null, "e": 27069, "s": 27064, "text": "vt_m" }, { "code": null, "e": 27075, "s": 27069, "text": "ukasp" }, { "code": null, "e": 27087, "s": 27075, "text": "29AjayKumar" }, { "code": null, "e": 27097, "s": 27087, "text": "Code_Mech" }, { "code": null, "e": 27108, "s": 27097, "text": "nidhi_biet" }, { "code": null, "e": 27123, "s": 27108, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 27137, "s": 27123, "text": "surbhityagi15" }, { "code": null, "e": 27145, "s": 27137, "text": "rag2127" }, { "code": null, "e": 27155, "s": 27145, "text": "Rajput-Ji" }, { "code": null, "e": 27172, "s": 27155, "text": "surinderdawra388" }, { "code": null, "e": 27185, "s": 27172, "text": "simmytarika5" }, { "code": null, "e": 27196, "s": 27185, "text": "singhh3010" }, { "code": null, "e": 27203, "s": 27196, "text": "Arrays" }, { "code": null, "e": 27210, "s": 27203, "text": "Arrays" }, { "code": null, "e": 27308, "s": 27210, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27376, "s": 27308, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 27420, "s": 27376, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 27452, "s": 27420, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 27500, "s": 27452, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 27514, "s": 27500, "text": "Linear Search" }, { "code": null, "e": 27599, "s": 27514, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 27622, "s": 27599, "text": "Introduction to Arrays" }, { "code": null, "e": 27678, "s": 27622, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" }, { "code": null, "e": 27705, "s": 27678, "text": "Subset Sum Problem | DP-25" } ]
Convert Named Vector to DataFrame in R
06 Jun, 2021 In this article, we will see how to convert the named vector to Dataframe in the R Programming Language. Method 1: Generally while converting a named vector to a dataframe we may face a problem. That is, names of vectors may get converted into row names, and data may be converted into a single column. So we need to convert the vector into a list then convert the list into a dataframe. First, we will convert the vector into a list using as.list( ) method and passed it to data.frame( ) method in order to convert the vector into dataframe. Example: R vector1 = c(1, "karthik", "IT")names(vector1) = c("id", "name", "branch") df = data.frame(as.list(vector1))print(df) Output : Method 2: Using tibble library. In tibble library there is a method called as_tibble( ) function. In order to use as_tibble( ) we need to install tibble library. To install package we can use install.packages( ) function by passing package name as parameter. syntax : variable = as_tibble (as.list(vector)) Example: R library(tibble)vec1 = c("1", "karthik", "IT")names(vec1) = c("id", "name", "branch") df=as_tibble(as.list(vec1))print(df) Output: Picked R DataFrame-Programs R Vector-Programs R-DataFrame R-Vectors R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? 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 Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? Replace Specific Characters in String in R Merge DataFrames by Column Names in R How to Sort a DataFrame in R ?
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Jun, 2021" }, { "code": null, "e": 134, "s": 28, "text": "In this article, we will see how to convert the named vector to Dataframe in the R Programming Language. " }, { "code": null, "e": 144, "s": 134, "text": "Method 1:" }, { "code": null, "e": 417, "s": 144, "text": "Generally while converting a named vector to a dataframe we may face a problem. That is, names of vectors may get converted into row names, and data may be converted into a single column. So we need to convert the vector into a list then convert the list into a dataframe." }, { "code": null, "e": 572, "s": 417, "text": "First, we will convert the vector into a list using as.list( ) method and passed it to data.frame( ) method in order to convert the vector into dataframe." }, { "code": null, "e": 581, "s": 572, "text": "Example:" }, { "code": null, "e": 583, "s": 581, "text": "R" }, { "code": "vector1 = c(1, \"karthik\", \"IT\")names(vector1) = c(\"id\", \"name\", \"branch\") df = data.frame(as.list(vector1))print(df)", "e": 701, "s": 583, "text": null }, { "code": null, "e": 710, "s": 701, "text": "Output :" }, { "code": null, "e": 742, "s": 710, "text": "Method 2: Using tibble library." }, { "code": null, "e": 969, "s": 742, "text": "In tibble library there is a method called as_tibble( ) function. In order to use as_tibble( ) we need to install tibble library. To install package we can use install.packages( ) function by passing package name as parameter." }, { "code": null, "e": 1018, "s": 969, "text": "syntax : variable = as_tibble (as.list(vector)) " }, { "code": null, "e": 1027, "s": 1018, "text": "Example:" }, { "code": null, "e": 1029, "s": 1027, "text": "R" }, { "code": "library(tibble)vec1 = c(\"1\", \"karthik\", \"IT\")names(vec1) = c(\"id\", \"name\", \"branch\") df=as_tibble(as.list(vec1))print(df)", "e": 1152, "s": 1029, "text": null }, { "code": null, "e": 1160, "s": 1152, "text": "Output:" }, { "code": null, "e": 1167, "s": 1160, "text": "Picked" }, { "code": null, "e": 1188, "s": 1167, "text": "R DataFrame-Programs" }, { "code": null, "e": 1206, "s": 1188, "text": "R Vector-Programs" }, { "code": null, "e": 1218, "s": 1206, "text": "R-DataFrame" }, { "code": null, "e": 1228, "s": 1218, "text": "R-Vectors" }, { "code": null, "e": 1239, "s": 1228, "text": "R Language" }, { "code": null, "e": 1250, "s": 1239, "text": "R Programs" }, { "code": null, "e": 1348, "s": 1250, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1400, "s": 1348, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 1458, "s": 1400, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 1493, "s": 1458, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 1531, "s": 1493, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 1580, "s": 1531, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 1638, "s": 1580, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 1687, "s": 1638, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 1730, "s": 1687, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 1768, "s": 1730, "text": "Merge DataFrames by Column Names in R" } ]
<mat-expansion-panel> in Angular Material
25 Feb, 2021 Introduction:Angular Material is a UI component library that is developed by the Angular team to build design components for desktop and mobile web applications. In order to install it, we need to have angular installed in our project, once you have it you can enter the below command and can download it. <mat-expansion-panel> tag is a kind of dropdown which has collapse and expand functionalities. Installation syntax: ng add @angular/material Approach: First, install the angular material using the above-mentioned command. After completing the installation, Import ‘MatExpansionModule’ from ‘@angular/material/expansion’ in the app.module.ts file. Then use <mat-accordion> tag as a parent tag for <mat-expansion-panel> tag. Inside the <mat-accordion> tag we need to use <mat-expansion-panel> tag for every item. For <mat-expansion-panel> tag we have many child tags which is been explained in the below table. Once done with the above steps then serve or start the project. Code Implementation: app.module.ts import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { MatExpansionModule } from '@angular/material'; import { AppComponent } from './example.component'; @NgModule({ declarations: [AppComponent], exports: [AppComponent], imports: [ CommonModule, FormsModule, MatExpansionModule ], }) export class AppModule {} app.component.html <mat-accordion> <mat-expansion-panel > <mat-expansion-panel-header> <mat-panel-title> GEEKSFORGEEKS </mat-panel-title> <mat-panel-description> Click here to expand the panel </mat-panel-description> </mat-expansion-panel-header> <p>One stop portal to all Computer Science Subjects. </p> </mat-expansion-panel> </mat-accordion> Output: Angular-material Picked AngularJS 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": "\n25 Feb, 2021" }, { "code": null, "e": 429, "s": 28, "text": "Introduction:Angular Material is a UI component library that is developed by the Angular team to build design components for desktop and mobile web applications. In order to install it, we need to have angular installed in our project, once you have it you can enter the below command and can download it. <mat-expansion-panel> tag is a kind of dropdown which has collapse and expand functionalities." }, { "code": null, "e": 450, "s": 429, "text": "Installation syntax:" }, { "code": null, "e": 475, "s": 450, "text": "ng add @angular/material" }, { "code": null, "e": 485, "s": 475, "text": "Approach:" }, { "code": null, "e": 556, "s": 485, "text": "First, install the angular material using the above-mentioned command." }, { "code": null, "e": 681, "s": 556, "text": "After completing the installation, Import ‘MatExpansionModule’ from ‘@angular/material/expansion’ in the app.module.ts file." }, { "code": null, "e": 757, "s": 681, "text": "Then use <mat-accordion> tag as a parent tag for <mat-expansion-panel> tag." }, { "code": null, "e": 845, "s": 757, "text": "Inside the <mat-accordion> tag we need to use <mat-expansion-panel> tag for every item." }, { "code": null, "e": 943, "s": 845, "text": "For <mat-expansion-panel> tag we have many child tags which is been explained in the below table." }, { "code": null, "e": 1007, "s": 943, "text": "Once done with the above steps then serve or start the project." }, { "code": null, "e": 1028, "s": 1007, "text": "Code Implementation:" }, { "code": null, "e": 1042, "s": 1028, "text": "app.module.ts" }, { "code": "import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { MatExpansionModule } from '@angular/material'; import { AppComponent } from './example.component'; @NgModule({ declarations: [AppComponent], exports: [AppComponent], imports: [ CommonModule, FormsModule, MatExpansionModule ], }) export class AppModule {}", "e": 1471, "s": 1042, "text": null }, { "code": null, "e": 1490, "s": 1471, "text": "app.component.html" }, { "code": "<mat-accordion> <mat-expansion-panel > <mat-expansion-panel-header> <mat-panel-title> GEEKSFORGEEKS </mat-panel-title> <mat-panel-description> Click here to expand the panel </mat-panel-description> </mat-expansion-panel-header> <p>One stop portal to all Computer Science Subjects. </p> </mat-expansion-panel> </mat-accordion>", "e": 1880, "s": 1490, "text": null }, { "code": null, "e": 1888, "s": 1880, "text": "Output:" }, { "code": null, "e": 1905, "s": 1888, "text": "Angular-material" }, { "code": null, "e": 1912, "s": 1905, "text": "Picked" }, { "code": null, "e": 1922, "s": 1912, "text": "AngularJS" }, { "code": null, "e": 1939, "s": 1922, "text": "Web Technologies" } ]
Explicitly define datatype in a Python function
29 Dec, 2020 Unlike other languages Java, C++, etc. Python is a strongly-typed dynamic language in which we don’t have to specify the data type of the function return value and function argument. It relates type with values instead of names. The only way to specify data of specific types is by providing explicit datatypes while calling the functions. Example 1: We have a function to add 2 elements. Python3 # function definitiondef add(num1, num2): print("Datatype of num1 is ", type(num1)) print("Datatype of num2 is ", type(num2)) return num1 + num2 # calling the function without# explicitly declaring the datatypesprint(add(2, 3)) # calling the function by explicitly# defining the datatype as floatprint(add(float(2), float(3))) Output: Datatype of num1 is <class 'int'> Datatype of num2 is <class 'int'> 5 Datatype of num1 is <class 'float'> Datatype of num2 is <class 'float'> 5.0 Example 2: We have a function for string concatenation Python3 # function definitiondef concatenate(num1, num2): print("Datatype of num1 is ", type(num1)) print("Datatype of num2 is ", type(num2)) return num1 + num2 # calling the function without# explicitly declaring the datatypesprint(concatenate(111, 100)) # calling the function by explicitly# defining the datatype as floatprint(concatenate(str(111), str(100))) Output: Datatype of num1 is <class 'int'> Datatype of num2 is <class 'int'> 211 Datatype of num1 is <class 'str'> Datatype of num2 is <class 'str'> 111100 Python function-programs Python-Functions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Dec, 2020" }, { "code": null, "e": 368, "s": 28, "text": "Unlike other languages Java, C++, etc. Python is a strongly-typed dynamic language in which we don’t have to specify the data type of the function return value and function argument. It relates type with values instead of names. The only way to specify data of specific types is by providing explicit datatypes while calling the functions." }, { "code": null, "e": 417, "s": 368, "text": "Example 1: We have a function to add 2 elements." }, { "code": null, "e": 425, "s": 417, "text": "Python3" }, { "code": "# function definitiondef add(num1, num2): print(\"Datatype of num1 is \", type(num1)) print(\"Datatype of num2 is \", type(num2)) return num1 + num2 # calling the function without# explicitly declaring the datatypesprint(add(2, 3)) # calling the function by explicitly# defining the datatype as floatprint(add(float(2), float(3)))", "e": 763, "s": 425, "text": null }, { "code": null, "e": 771, "s": 763, "text": "Output:" }, { "code": null, "e": 922, "s": 771, "text": "Datatype of num1 is <class 'int'>\nDatatype of num2 is <class 'int'>\n5\nDatatype of num1 is <class 'float'>\nDatatype of num2 is <class 'float'>\n5.0\n" }, { "code": null, "e": 977, "s": 922, "text": "Example 2: We have a function for string concatenation" }, { "code": null, "e": 985, "s": 977, "text": "Python3" }, { "code": "# function definitiondef concatenate(num1, num2): print(\"Datatype of num1 is \", type(num1)) print(\"Datatype of num2 is \", type(num2)) return num1 + num2 # calling the function without# explicitly declaring the datatypesprint(concatenate(111, 100)) # calling the function by explicitly# defining the datatype as floatprint(concatenate(str(111), str(100)))", "e": 1351, "s": 985, "text": null }, { "code": null, "e": 1359, "s": 1351, "text": "Output:" }, { "code": null, "e": 1511, "s": 1359, "text": "Datatype of num1 is <class 'int'>\nDatatype of num2 is <class 'int'>\n211\nDatatype of num1 is <class 'str'>\nDatatype of num2 is <class 'str'>\n111100\n" }, { "code": null, "e": 1536, "s": 1511, "text": "Python function-programs" }, { "code": null, "e": 1553, "s": 1536, "text": "Python-Functions" }, { "code": null, "e": 1560, "s": 1553, "text": "Python" } ]
Tryit Editor v3.7
HTML form attributes Tryit: submit method POST
[ { "code": null, "e": 31, "s": 10, "text": "HTML form attributes" } ]
How to get all the processes on remote computers using PowerShell?
To get all running processes on the remote computer, you need to use – ComputerNameparameter in Get-process cmdlet, WMI class Win32_Process or using the Get-CimInstance cmdlet. With –ComputerName parameter Get-process -ComputerName Test-PC To connect multiple computers use computer names separated by comma (,). Get-process -ComputerName Test-PC, Win2k8 With WMI object to get processes on multiple remote computers. Get-WmiObject Win32_Process -ComputerName Test-PC, Win2k8 Get-CimInstance cmdlet to get processes on remote computers. Get-CimInstance Win32_Process -ComputerName Test-PC, Win2k8
[ { "code": null, "e": 1239, "s": 1062, "text": "To get all running processes on the remote computer, you need to use – ComputerNameparameter in Get-process cmdlet, WMI class Win32_Process or using the Get-CimInstance cmdlet." }, { "code": null, "e": 1268, "s": 1239, "text": "With –ComputerName parameter" }, { "code": null, "e": 1302, "s": 1268, "text": "Get-process -ComputerName Test-PC" }, { "code": null, "e": 1375, "s": 1302, "text": "To connect multiple computers use computer names separated by comma (,)." }, { "code": null, "e": 1418, "s": 1375, "text": "Get-process -ComputerName Test-PC, Win2k8\n" }, { "code": null, "e": 1481, "s": 1418, "text": "With WMI object to get processes on multiple remote computers." }, { "code": null, "e": 1539, "s": 1481, "text": "Get-WmiObject Win32_Process -ComputerName Test-PC, Win2k8" }, { "code": null, "e": 1600, "s": 1539, "text": "Get-CimInstance cmdlet to get processes on remote computers." }, { "code": null, "e": 1661, "s": 1600, "text": "Get-CimInstance Win32_Process -ComputerName Test-PC, Win2k8\n" } ]
Deep understanding of the ARIMA model | by Xichu Zhang | Towards Data Science
Generally, a model for time-series forecasting can be written as where yt is the variables to be forecasted (dependent variable, or response variable), t is the time at which the forecast is made, h is the forecast horizon, Xt is the variables used at time t to make forecast (independent variable), θ is a vector of parameters in function g, and εt+h denotes errors. It is worth noting that the observed data is uniquely orderly according to the time of observation, but it doesn’t have to be dependent on time, i.e. time (index of the observations) doesn’t have to be one of the independent variables. Stationarity: a stationary process is a stochastic process, whose mean, variance and autocorrelation structure do not change over time. It can also be defined formally using mathematical terms, but in this article, it’s not necessary. Intuitively, if a time series is stationary, we look at some parts of them, they should be very similar — the time series is flat looking and the shape doesn’t depend on the shift of time. (A quick check of knowledge: is f(t) = sin(t) a stationary process? It surely isn’t, since it’s not stochastic, stationarity is not one of its properties) Figure 1.1 shows the simplest example of a stationary process — white noise. The above image Figure 1.2 shows a non-stationary time series. Why is it so? We can see the obvious trend, it means that the variance changes over time. But if we use linear regression to fit a line to it (to capture the trend) and remove the trend the data now has a constant location and variance, but it’s still not stationary because of periodic behavior, which is not stochastic. When using ARMA to model a time series, one of the assumptions is that the data is stationary. Seasonality: Seasonality is the property of showing certain variations in a specific time interval that is shorter than a year (it can be over a different period of course. If we are observing the hourly temperature in a day and collect data over a couple of days, then the period is a day and it can also have seasonality — peaks might appear at 2 or 3 pm. This means we don’t have to interpret season in the context of seasonality using common sense), monthly, quarterly, etc. A very typical example of seasonal time series is electricity usage, in summer the electricity usage is usually higher because of, for instance, air conditioners. Figure 1.5 shows the data with seasonality properties, we can easily see that there is a peak of electricity usage in July and August, and a smaller peak in January and December. The data plotted in figure 1.5 is the electricity usage in the US from the year 1973 to 2010. usmelec is built-in data set in R. The electricity usage throughout the whole period looks like this The presence of seasonality requires us to adjust the way of making predictions. For example, if we want to sell air conditioners, we need to predict the monthly sales in the future using the sales in the same season in the past years, instead of the closest months. What it is? It is an operator which shifts a variable xt backward, which is denoted sometimes as B (Backshift) and sometimes L (Lag), in this article, we will adopt the notation B. It’s defined as and the forward-shift operator B−1, which satisfies B−1B = 1. Why do we need this? It’s because it enables us to expressly backshifting in a succinct way — in terms of polynomials, which also helps us with defining more complicated models. When we use something to represent something in math, it’s always important to look at what operations it supports. In this case, we can easily see that the back-shift operator allows all the arithmetic operations on it: addition, subtraction, multiplication, division, exponentiation, etc. It means, e.g. using the operator (1-B) on xt gets us the difference xt-xt−1, if we want to take the difference of xt and xt−1 again, we use operator (1-B)2 on xt, which gives us (1–2B+B2)xt = xt-2xt−1+ xt−2. This is the same as (xt-xt−1)-(xt−1-xt−2). In this example, we encountered first-order and second-order differencing (Equation 2.12, 2.13), which will be explained later. An autoregressive model of order p, abbreviated AP(p), models the current value as a linear combination of the previous p values. That’s how this model gets its name, it is a linear regression with itself. We see a lot of terms in the definition, but the model is still concerned to be univariate since the current value depends on its past values. Those values are of the same variable taken at different time points, so after all only one variable is concerned. A more generalized model is VAR (Vector autoregression), which allows multivariate times series. Formally, a (univariant) autoregressive model is defined as where wt ~ wn(0, σvv2), and φ1, φ2,..., φp (φp ≠ 0) are parameters. wn denotes “white noise”, it has normal distribution with mean 0 and variance σvv2. Sometimes there is also a constant on the right side of Equation 2.2, denoted by c (Forecasting: Principles and Practice chap 8.3). The role that the constant plays will be explained in the subsection of ARIMA. In terms of the back-shift operator, the autoregressive model is defined as The moving average model of order q, abbreviated as MA(q), models the current value as a linear combination of the previous q error terms (unlike the autoregression model, in moving average, it is the error term, which is concerned). Formally, it’s defined as where wt ~ wn(0, σvv2), and θ1, θ2,..., θq (θq ≠ 0) are parameters. wn denotes “white noise”, it has normal distribution with mean 0 and variance σvv2, like in the definition of the autoregressive model. This is a univariate model as well. A constant can also be added to the definition (Forecasting: Principles and Practice chap 8.4). In terms of the back-shift operator, the moving average model can be defined as Unlike the autoregressive model, the name of this moving-average model is not so obvious. According to the footnote on page 48 in Forecasting with Univariate Box‐Jenkins Models (2009): Concepts and Cases by Pankratz: “the label ‘moving average’ is technically incorrect since the MA coefficients may be negative and may not sum to unity. This label is used by convention.” Another confusing thing is a concept that looks like the moving-average model, the moving average, a.k.a. rolling average or running average, which is used to smooth out a time series. In fact, it is completely a different tool — it is not used for prediction. We use an example of the simple moving average to make this clear After observing the formulas, we can see that we need the k-th value to compute the k-th moving average. ARMA model is the combination of AR and MA, which is quite self-explanatory. ARMA takes into consideration both the past values and past error terms and describes a (weakly) stationary stochastic process in terms of two polynomials. Formally a time series is ARMA(p, q) if it is stationary and where φp ≠ 0, θq ≠ 0, wt ~ wn(0, σvv2), and σvv2 > 0. The parameters p and q are the autoregressive and the moving average orders respectively, as mentioned before. In terms of the back-shift operator, the ARIMA model can be written as This rewriting is not trivial. It reveals a serious problem that can occur in the model — the redundancy of parameters. If the polynomials φ(B) = 0 and θ(B) = 0 have common factors, then the models will contain redundant parameters. It will make the model uselessly complicated. When can this situation occur? When we try to fit a white noise series (xt = wt) using an ARMA(1,1) model, the program will do it, but the model we get will have superfluous parameters. Therefore, we need to remove the redundancy to simplify the model, and the redundancy can be removed using covariance analysis. The definition shown in Equation 2.8 is the non-seasonal ARMA. But it often happens that the data is seasonal. What should we do, if we want to remove seasonality? The answer is to introduce a lag h (length of the seasonal period), which brings us to the seasonal ARMA (SARMA), denoted as ARMA(P, Q)h, and is of the form This method of removing the seasonal effect corresponds to what we have described before: using Augusts’ data to predict August’s sales. What should h equal to? This depends on the frequency of the seasonality, for example, if the seasonal variation appears once in a year in some specific months, then h = 12, if it appears once in each quarter of the year, then h = 4. If we combine seasonal ARMA with non-seasonal ARMA (multiply the seasonal and non-season operators together), we will get one layer of generalization — mixed season ARMA. ARIMA model is ARMA modeled on a differenced series, the differencing is sometimes denoted as ▽. What is differencing then? It is a technique of removing the non-stationary of a series (this removes the non-constant trend, which means it only makes the mean stationery, but not variance). It takes the difference between two observations. Of course, we can difference the observations multiple times. Eq 2.12 and Eq 2.13 show the example of first-order differencing and second-order differencing. It is obvious how the differencing differs from differentiation — differencing just takes the difference, meanwhile, differentiation calculates the rate of change. ARIMA model is usually denoted by ARIMA(p, d, q), the meaning of the parameters are summarized in the following table Now it’s time to introduce the formal definition of ARIMA model, where yt’ denoted the difference series, other parameters are defined in the same way as those in the ARMA model. As before, a constant can be added to the model, which denotes the drift. It can be easily understood via an example with an ARIMA(0, 1, 0) model (no autoregressive nor moving-average terms, modeled using first-degree difference) involved: Without parameter: the model is xt = xt−1 + εt, which is a random walk. With parameter: the model is xt = c+ xt−1 + εt. This is a random walk with drift. The constant adds a non-constant trend to the process. (This sentence looks very weird, but we need to be aware that the formula xt = c+ xt−1+ εt is recursive and in each unwinding a constant in the formula with stack up) How much influence does this constant have? A lot. We can see this from the simulation of two random walks, one with and one without drift However, this differencing doesn’t take care of seasonality. To remove seasonality, we need to take the seasonal difference (the difference between xt and xt−h), and this brings us to the seasonal autoregressive integrated moving average (SARIMA) model. The relation between SARIMA and SARMA is very similar to the relation between ARIMA and ARMA — SARIMA is SARMA with differencing, but now we need to take not only the non-seasonal difference but also seasonal difference. We use ▽D and ▽d to denote the seasonal and non-seasonal differences, respectively. D is the degree of seasonal differencing. As stated in the bible book Forecasting: Principles and Practices, there is a general approach of fitting an ARIMA model: preprocess, until the data become stationary; feed to a function, which computes ARIMA model; compare the models; check the results (the residuals); if not good enough, iterate, otherwise use the result model to do forecast. In R, the parameters are estimated using maximum likelihood estimation (MLE), which maximizes a likelihood function. The likelihood is equal to the probability that an observation x is produced, given the parameters (φ, θ, ...) of our model. To compare the models, the Akaike information criterion (AIC) is used, which evaluates the loss of information and also penalizes the complication of models (amount of estimated parameters). We choose the model with the least AIC value. If we want to use an automated process to build to model, the function auto.arima is at our disposal. It uses a step-wise procedure (Hyndman-Khandakar algorithm) to traverse the space of models efficiently. The function auto.arima takes care of differencing the data to make the data stationary (whether d = 0), choosing hyperparameters, and selecting the best model according to AIC. We use oil prices from the 16th of August last year to 26th August this year to show the automated ARIMA process. What we want to achieve is to use the data from 16 Aug. 2020 to 16 Aug.2021 to predict the oil price in the following 10 days, then compare the result against the real values. (In this article the purpose is mainly to introduce the reader to the principle of the ARIMA model, so this is really a rough stock prediction, and things like back-testing are not included) # read data# Datasource: https://finance.yahoo.com/quote/OIL/history?p=OILdataOil <- read.csv2(file = "data/OIL.csv", sep=",")head(dataOil)# split into training and test datalenOil <- nrow(dataOil)trainSize <- ceiling(lenOil-10)# take the first 12 month train.oil <- dataOil[1:trainSize, ]test.oil <- slice_tail(dataOil, n=lenOil-trainSize)# convert to time seriestrain.close <- train.oil$Closetrain.close <- as.numeric(train.close)# frequency is set to be one because we have only one year of datatrain.close.ts <- ts(data=train.close, frequency=1)# plot the training data plot(train.close, type='l', ylab='Close price', main="One year oil price") Obviously, we can see a trend, and the time series is not stationary, but there is no evidence of varying variance, so we are not going to do any transformation. The rest of the model building is taken care of by auto.arima. But what we need to do is to check the residuals, to make sure that they look like random noise, this part is done by checkresiduals, which applies Ljung-Box test. If the p-value of the Ljung-Box test is larger than 0.05, we can’t reject the null hypothesis that the residuals are distributed independently. Therefore, this model is admissible, otherwise, we would need to choose a new one. start <- length(train.close.ts)test.index <- seq(start, start+9)test.close <- as.numeric(test.oil$Close)aa.train <- auto.arima(train.close.ts) # --> AIC = 157.11checkresiduals(aa.train)# --> p-value = 0.07454plot(forecast(aa.train, h=10))lines(test.index, test.close) The result looks like this, compares with the real values of the oil price from 17 Aug. to 26 Aug (the last 10 days). The automated process can fail to find a suitable model for us. If it fails the Ljung-Box test, we need to choose the hyperparameters ourselves. Therefore, sometimes we might need to choose our own model (using Arima). Compared to the automated process, what do we need to do in addition to use our own model? Firstly, after observing the data, we need to investigate the partial autocorrelation of the data. (to know more about partial correlation click here). # plot the partial difference dif.train <- difference(train.close.ts)ggtsdisplay(dif.train, plot.type='partial') The difference shown in the graph looks quite stationary, therefore we will just use the first-order difference. But we can still perform a unit root test to check the stationarity. We have several alternatives for this, here we use the Augmented Dickey-Fuller test (ADF, in R it’s adf.test, if we set k=0, then it becomes simply Dickey-Fuller test). # ADF testdif.train <- na.remove(dif.train)adf.test(dif.train)# --> p-value smaller than 0.01 According to the result, we can reject the null hypothesis that the first-order difference is non-stationary. Therefore we set d=1. According to the partial autocovariance, which shows the correlation between a stationary time series and its own lagged values with the influence of shorter lags removed, variable xt is correlated with xt+4, then we can try to set p = 4. The rest is q, we can try from 0 and gradually increase it. As to seasonality, it’s not really shown in the graph, therefore we can leave the parameters of seasonality (P, D, Q) as default zeros. Should we add drift? From the increasing trend in Figure 3.2, seems to be yes, we can set include.drift to be true. # manually try the different parametersfit.m1 <- Arima(train.close.ts, order=c(4,1,0), include.drift=TRUE)fit.m1# --> AIC = 156.15fit.m2 <- Arima(train.close.ts, order=c(4,1,1), include.drift=TRUE)fit.m2# --> AIC = 157.61 # after trying some more other values of q, we will find out# that increasing q doesn't really decrease the AICcheckresiduals(fit.m1)# --> p-value = 0.4187plot(forecast(fit.m1, h=10))lines(test.index, test.close) Our custom model has a slightly lower AIC value, yet the plot looks almost the same as the one shown in Figure 3.2. Summary In this article, at first, we quickly introduced the formal definition of time series and some typical properties which can occur in a time series. After that, we get familiar with the definition of ARIMA gradually, along with the extension of ARMA and ARIMA — seasonal ARMA (SARMA) and seasonal ARIMA (SARIMA). At last, we build a model to do a short-term prediction of oil prices both automatically and manually. [1] NIST/SEMATECH e-Handbook of Statistical Methods (2012). [2] Watson, M. W. Time series: economic forecasting (2001). International Encyclopedia of the Social & Behavioral Sciences, 15721–15724. [3] Hyndman, R. J., & Athanasopoulos, G. Forecasting: principles and practice (2018). OTexts. [4] Pankratz, A. (2009). Forecasting with univariate Box-Jenkins models: Concepts and cases (Vol. 224). John Wiley & Sons. [5] Hyndman, R. J., & Khandakar, Y. (2008). Automatic time series forecasting: the forecast package for R. Journal of statistical software, 27(1), 1–22. [6] Eni, D. (2015). Seasonal ARIMA modeling and forecasting of rainfall in Warri Town, Nigeria. Journal of Geoscience and Environment Protection, 3(06), 91. [7] Autoregressive integrated moving average. (2021, April, 29). In Wikipedia. Some of my opinions on the philosophy of modeling and prediction :)
[ { "code": null, "e": 237, "s": 172, "text": "Generally, a model for time-series forecasting can be written as" }, { "code": null, "e": 776, "s": 237, "text": "where yt is the variables to be forecasted (dependent variable, or response variable), t is the time at which the forecast is made, h is the forecast horizon, Xt is the variables used at time t to make forecast (independent variable), θ is a vector of parameters in function g, and εt+h denotes errors. It is worth noting that the observed data is uniquely orderly according to the time of observation, but it doesn’t have to be dependent on time, i.e. time (index of the observations) doesn’t have to be one of the independent variables." }, { "code": null, "e": 1355, "s": 776, "text": "Stationarity: a stationary process is a stochastic process, whose mean, variance and autocorrelation structure do not change over time. It can also be defined formally using mathematical terms, but in this article, it’s not necessary. Intuitively, if a time series is stationary, we look at some parts of them, they should be very similar — the time series is flat looking and the shape doesn’t depend on the shift of time. (A quick check of knowledge: is f(t) = sin(t) a stationary process? It surely isn’t, since it’s not stochastic, stationarity is not one of its properties)" }, { "code": null, "e": 1432, "s": 1355, "text": "Figure 1.1 shows the simplest example of a stationary process — white noise." }, { "code": null, "e": 1817, "s": 1432, "text": "The above image Figure 1.2 shows a non-stationary time series. Why is it so? We can see the obvious trend, it means that the variance changes over time. But if we use linear regression to fit a line to it (to capture the trend) and remove the trend the data now has a constant location and variance, but it’s still not stationary because of periodic behavior, which is not stochastic." }, { "code": null, "e": 1912, "s": 1817, "text": "When using ARMA to model a time series, one of the assumptions is that the data is stationary." }, { "code": null, "e": 2554, "s": 1912, "text": "Seasonality: Seasonality is the property of showing certain variations in a specific time interval that is shorter than a year (it can be over a different period of course. If we are observing the hourly temperature in a day and collect data over a couple of days, then the period is a day and it can also have seasonality — peaks might appear at 2 or 3 pm. This means we don’t have to interpret season in the context of seasonality using common sense), monthly, quarterly, etc. A very typical example of seasonal time series is electricity usage, in summer the electricity usage is usually higher because of, for instance, air conditioners." }, { "code": null, "e": 2928, "s": 2554, "text": "Figure 1.5 shows the data with seasonality properties, we can easily see that there is a peak of electricity usage in July and August, and a smaller peak in January and December. The data plotted in figure 1.5 is the electricity usage in the US from the year 1973 to 2010. usmelec is built-in data set in R. The electricity usage throughout the whole period looks like this" }, { "code": null, "e": 3195, "s": 2928, "text": "The presence of seasonality requires us to adjust the way of making predictions. For example, if we want to sell air conditioners, we need to predict the monthly sales in the future using the sales in the same season in the past years, instead of the closest months." }, { "code": null, "e": 3392, "s": 3195, "text": "What it is? It is an operator which shifts a variable xt backward, which is denoted sometimes as B (Backshift) and sometimes L (Lag), in this article, we will adopt the notation B. It’s defined as" }, { "code": null, "e": 3454, "s": 3392, "text": "and the forward-shift operator B−1, which satisfies B−1B = 1." }, { "code": null, "e": 3923, "s": 3454, "text": "Why do we need this? It’s because it enables us to expressly backshifting in a succinct way — in terms of polynomials, which also helps us with defining more complicated models. When we use something to represent something in math, it’s always important to look at what operations it supports. In this case, we can easily see that the back-shift operator allows all the arithmetic operations on it: addition, subtraction, multiplication, division, exponentiation, etc." }, { "code": null, "e": 4303, "s": 3923, "text": "It means, e.g. using the operator (1-B) on xt gets us the difference xt-xt−1, if we want to take the difference of xt and xt−1 again, we use operator (1-B)2 on xt, which gives us (1–2B+B2)xt = xt-2xt−1+ xt−2. This is the same as (xt-xt−1)-(xt−1-xt−2). In this example, we encountered first-order and second-order differencing (Equation 2.12, 2.13), which will be explained later." }, { "code": null, "e": 4924, "s": 4303, "text": "An autoregressive model of order p, abbreviated AP(p), models the current value as a linear combination of the previous p values. That’s how this model gets its name, it is a linear regression with itself. We see a lot of terms in the definition, but the model is still concerned to be univariate since the current value depends on its past values. Those values are of the same variable taken at different time points, so after all only one variable is concerned. A more generalized model is VAR (Vector autoregression), which allows multivariate times series. Formally, a (univariant) autoregressive model is defined as" }, { "code": null, "e": 5288, "s": 4924, "text": "where wt ~ wn(0, σvv2), and φ1, φ2,..., φp (φp ≠ 0) are parameters. wn denotes “white noise”, it has normal distribution with mean 0 and variance σvv2. Sometimes there is also a constant on the right side of Equation 2.2, denoted by c (Forecasting: Principles and Practice chap 8.3). The role that the constant plays will be explained in the subsection of ARIMA." }, { "code": null, "e": 5364, "s": 5288, "text": "In terms of the back-shift operator, the autoregressive model is defined as" }, { "code": null, "e": 5624, "s": 5364, "text": "The moving average model of order q, abbreviated as MA(q), models the current value as a linear combination of the previous q error terms (unlike the autoregression model, in moving average, it is the error term, which is concerned). Formally, it’s defined as" }, { "code": null, "e": 5961, "s": 5624, "text": "where wt ~ wn(0, σvv2), and θ1, θ2,..., θq (θq ≠ 0) are parameters. wn denotes “white noise”, it has normal distribution with mean 0 and variance σvv2, like in the definition of the autoregressive model. This is a univariate model as well. A constant can also be added to the definition (Forecasting: Principles and Practice chap 8.4)." }, { "code": null, "e": 6041, "s": 5961, "text": "In terms of the back-shift operator, the moving average model can be defined as" }, { "code": null, "e": 6414, "s": 6041, "text": "Unlike the autoregressive model, the name of this moving-average model is not so obvious. According to the footnote on page 48 in Forecasting with Univariate Box‐Jenkins Models (2009): Concepts and Cases by Pankratz: “the label ‘moving average’ is technically incorrect since the MA coefficients may be negative and may not sum to unity. This label is used by convention.”" }, { "code": null, "e": 6741, "s": 6414, "text": "Another confusing thing is a concept that looks like the moving-average model, the moving average, a.k.a. rolling average or running average, which is used to smooth out a time series. In fact, it is completely a different tool — it is not used for prediction. We use an example of the simple moving average to make this clear" }, { "code": null, "e": 6846, "s": 6741, "text": "After observing the formulas, we can see that we need the k-th value to compute the k-th moving average." }, { "code": null, "e": 7140, "s": 6846, "text": "ARMA model is the combination of AR and MA, which is quite self-explanatory. ARMA takes into consideration both the past values and past error terms and describes a (weakly) stationary stochastic process in terms of two polynomials. Formally a time series is ARMA(p, q) if it is stationary and" }, { "code": null, "e": 7378, "s": 7140, "text": "where φp ≠ 0, θq ≠ 0, wt ~ wn(0, σvv2), and σvv2 > 0. The parameters p and q are the autoregressive and the moving average orders respectively, as mentioned before. In terms of the back-shift operator, the ARIMA model can be written as" }, { "code": null, "e": 7971, "s": 7378, "text": "This rewriting is not trivial. It reveals a serious problem that can occur in the model — the redundancy of parameters. If the polynomials φ(B) = 0 and θ(B) = 0 have common factors, then the models will contain redundant parameters. It will make the model uselessly complicated. When can this situation occur? When we try to fit a white noise series (xt = wt) using an ARMA(1,1) model, the program will do it, but the model we get will have superfluous parameters. Therefore, we need to remove the redundancy to simplify the model, and the redundancy can be removed using covariance analysis." }, { "code": null, "e": 8292, "s": 7971, "text": "The definition shown in Equation 2.8 is the non-seasonal ARMA. But it often happens that the data is seasonal. What should we do, if we want to remove seasonality? The answer is to introduce a lag h (length of the seasonal period), which brings us to the seasonal ARMA (SARMA), denoted as ARMA(P, Q)h, and is of the form" }, { "code": null, "e": 8834, "s": 8292, "text": "This method of removing the seasonal effect corresponds to what we have described before: using Augusts’ data to predict August’s sales. What should h equal to? This depends on the frequency of the seasonality, for example, if the seasonal variation appears once in a year in some specific months, then h = 12, if it appears once in each quarter of the year, then h = 4. If we combine seasonal ARMA with non-seasonal ARMA (multiply the seasonal and non-season operators together), we will get one layer of generalization — mixed season ARMA." }, { "code": null, "e": 9173, "s": 8834, "text": "ARIMA model is ARMA modeled on a differenced series, the differencing is sometimes denoted as ▽. What is differencing then? It is a technique of removing the non-stationary of a series (this removes the non-constant trend, which means it only makes the mean stationery, but not variance). It takes the difference between two observations." }, { "code": null, "e": 9613, "s": 9173, "text": "Of course, we can difference the observations multiple times. Eq 2.12 and Eq 2.13 show the example of first-order differencing and second-order differencing. It is obvious how the differencing differs from differentiation — differencing just takes the difference, meanwhile, differentiation calculates the rate of change. ARIMA model is usually denoted by ARIMA(p, d, q), the meaning of the parameters are summarized in the following table" }, { "code": null, "e": 9678, "s": 9613, "text": "Now it’s time to introduce the formal definition of ARIMA model," }, { "code": null, "e": 10032, "s": 9678, "text": "where yt’ denoted the difference series, other parameters are defined in the same way as those in the ARMA model. As before, a constant can be added to the model, which denotes the drift. It can be easily understood via an example with an ARIMA(0, 1, 0) model (no autoregressive nor moving-average terms, modeled using first-degree difference) involved:" }, { "code": null, "e": 10104, "s": 10032, "text": "Without parameter: the model is xt = xt−1 + εt, which is a random walk." }, { "code": null, "e": 10186, "s": 10104, "text": "With parameter: the model is xt = c+ xt−1 + εt. This is a random walk with drift." }, { "code": null, "e": 10547, "s": 10186, "text": "The constant adds a non-constant trend to the process. (This sentence looks very weird, but we need to be aware that the formula xt = c+ xt−1+ εt is recursive and in each unwinding a constant in the formula with stack up) How much influence does this constant have? A lot. We can see this from the simulation of two random walks, one with and one without drift" }, { "code": null, "e": 11148, "s": 10547, "text": "However, this differencing doesn’t take care of seasonality. To remove seasonality, we need to take the seasonal difference (the difference between xt and xt−h), and this brings us to the seasonal autoregressive integrated moving average (SARIMA) model. The relation between SARIMA and SARMA is very similar to the relation between ARIMA and ARMA — SARIMA is SARMA with differencing, but now we need to take not only the non-seasonal difference but also seasonal difference. We use ▽D and ▽d to denote the seasonal and non-seasonal differences, respectively. D is the degree of seasonal differencing." }, { "code": null, "e": 11495, "s": 11148, "text": "As stated in the bible book Forecasting: Principles and Practices, there is a general approach of fitting an ARIMA model: preprocess, until the data become stationary; feed to a function, which computes ARIMA model; compare the models; check the results (the residuals); if not good enough, iterate, otherwise use the result model to do forecast." }, { "code": null, "e": 11974, "s": 11495, "text": "In R, the parameters are estimated using maximum likelihood estimation (MLE), which maximizes a likelihood function. The likelihood is equal to the probability that an observation x is produced, given the parameters (φ, θ, ...) of our model. To compare the models, the Akaike information criterion (AIC) is used, which evaluates the loss of information and also penalizes the complication of models (amount of estimated parameters). We choose the model with the least AIC value." }, { "code": null, "e": 12359, "s": 11974, "text": "If we want to use an automated process to build to model, the function auto.arima is at our disposal. It uses a step-wise procedure (Hyndman-Khandakar algorithm) to traverse the space of models efficiently. The function auto.arima takes care of differencing the data to make the data stationary (whether d = 0), choosing hyperparameters, and selecting the best model according to AIC." }, { "code": null, "e": 12840, "s": 12359, "text": "We use oil prices from the 16th of August last year to 26th August this year to show the automated ARIMA process. What we want to achieve is to use the data from 16 Aug. 2020 to 16 Aug.2021 to predict the oil price in the following 10 days, then compare the result against the real values. (In this article the purpose is mainly to introduce the reader to the principle of the ARIMA model, so this is really a rough stock prediction, and things like back-testing are not included)" }, { "code": null, "e": 13489, "s": 12840, "text": "# read data# Datasource: https://finance.yahoo.com/quote/OIL/history?p=OILdataOil <- read.csv2(file = \"data/OIL.csv\", sep=\",\")head(dataOil)# split into training and test datalenOil <- nrow(dataOil)trainSize <- ceiling(lenOil-10)# take the first 12 month train.oil <- dataOil[1:trainSize, ]test.oil <- slice_tail(dataOil, n=lenOil-trainSize)# convert to time seriestrain.close <- train.oil$Closetrain.close <- as.numeric(train.close)# frequency is set to be one because we have only one year of datatrain.close.ts <- ts(data=train.close, frequency=1)# plot the training data plot(train.close, type='l', ylab='Close price', main=\"One year oil price\")" }, { "code": null, "e": 14105, "s": 13489, "text": "Obviously, we can see a trend, and the time series is not stationary, but there is no evidence of varying variance, so we are not going to do any transformation. The rest of the model building is taken care of by auto.arima. But what we need to do is to check the residuals, to make sure that they look like random noise, this part is done by checkresiduals, which applies Ljung-Box test. If the p-value of the Ljung-Box test is larger than 0.05, we can’t reject the null hypothesis that the residuals are distributed independently. Therefore, this model is admissible, otherwise, we would need to choose a new one." }, { "code": null, "e": 14373, "s": 14105, "text": "start <- length(train.close.ts)test.index <- seq(start, start+9)test.close <- as.numeric(test.oil$Close)aa.train <- auto.arima(train.close.ts) # --> AIC = 157.11checkresiduals(aa.train)# --> p-value = 0.07454plot(forecast(aa.train, h=10))lines(test.index, test.close)" }, { "code": null, "e": 14491, "s": 14373, "text": "The result looks like this, compares with the real values of the oil price from 17 Aug. to 26 Aug (the last 10 days)." }, { "code": null, "e": 14953, "s": 14491, "text": "The automated process can fail to find a suitable model for us. If it fails the Ljung-Box test, we need to choose the hyperparameters ourselves. Therefore, sometimes we might need to choose our own model (using Arima). Compared to the automated process, what do we need to do in addition to use our own model? Firstly, after observing the data, we need to investigate the partial autocorrelation of the data. (to know more about partial correlation click here)." }, { "code": null, "e": 15066, "s": 14953, "text": "# plot the partial difference dif.train <- difference(train.close.ts)ggtsdisplay(dif.train, plot.type='partial')" }, { "code": null, "e": 15417, "s": 15066, "text": "The difference shown in the graph looks quite stationary, therefore we will just use the first-order difference. But we can still perform a unit root test to check the stationarity. We have several alternatives for this, here we use the Augmented Dickey-Fuller test (ADF, in R it’s adf.test, if we set k=0, then it becomes simply Dickey-Fuller test)." }, { "code": null, "e": 15511, "s": 15417, "text": "# ADF testdif.train <- na.remove(dif.train)adf.test(dif.train)# --> p-value smaller than 0.01" }, { "code": null, "e": 16194, "s": 15511, "text": "According to the result, we can reject the null hypothesis that the first-order difference is non-stationary. Therefore we set d=1. According to the partial autocovariance, which shows the correlation between a stationary time series and its own lagged values with the influence of shorter lags removed, variable xt is correlated with xt+4, then we can try to set p = 4. The rest is q, we can try from 0 and gradually increase it. As to seasonality, it’s not really shown in the graph, therefore we can leave the parameters of seasonality (P, D, Q) as default zeros. Should we add drift? From the increasing trend in Figure 3.2, seems to be yes, we can set include.drift to be true." }, { "code": null, "e": 16629, "s": 16194, "text": "# manually try the different parametersfit.m1 <- Arima(train.close.ts, order=c(4,1,0), include.drift=TRUE)fit.m1# --> AIC = 156.15fit.m2 <- Arima(train.close.ts, order=c(4,1,1), include.drift=TRUE)fit.m2# --> AIC = 157.61 # after trying some more other values of q, we will find out# that increasing q doesn't really decrease the AICcheckresiduals(fit.m1)# --> p-value = 0.4187plot(forecast(fit.m1, h=10))lines(test.index, test.close)" }, { "code": null, "e": 16745, "s": 16629, "text": "Our custom model has a slightly lower AIC value, yet the plot looks almost the same as the one shown in Figure 3.2." }, { "code": null, "e": 16753, "s": 16745, "text": "Summary" }, { "code": null, "e": 17168, "s": 16753, "text": "In this article, at first, we quickly introduced the formal definition of time series and some typical properties which can occur in a time series. After that, we get familiar with the definition of ARIMA gradually, along with the extension of ARMA and ARIMA — seasonal ARMA (SARMA) and seasonal ARIMA (SARIMA). At last, we build a model to do a short-term prediction of oil prices both automatically and manually." }, { "code": null, "e": 17228, "s": 17168, "text": "[1] NIST/SEMATECH e-Handbook of Statistical Methods (2012)." }, { "code": null, "e": 17365, "s": 17228, "text": "[2] Watson, M. W. Time series: economic forecasting (2001). International Encyclopedia of the Social & Behavioral Sciences, 15721–15724." }, { "code": null, "e": 17459, "s": 17365, "text": "[3] Hyndman, R. J., & Athanasopoulos, G. Forecasting: principles and practice (2018). OTexts." }, { "code": null, "e": 17582, "s": 17459, "text": "[4] Pankratz, A. (2009). Forecasting with univariate Box-Jenkins models: Concepts and cases (Vol. 224). John Wiley & Sons." }, { "code": null, "e": 17735, "s": 17582, "text": "[5] Hyndman, R. J., & Khandakar, Y. (2008). Automatic time series forecasting: the forecast package for R. Journal of statistical software, 27(1), 1–22." }, { "code": null, "e": 17892, "s": 17735, "text": "[6] Eni, D. (2015). Seasonal ARIMA modeling and forecasting of rainfall in Warri Town, Nigeria. Journal of Geoscience and Environment Protection, 3(06), 91." }, { "code": null, "e": 17971, "s": 17892, "text": "[7] Autoregressive integrated moving average. (2021, April, 29). In Wikipedia." } ]
Crystal Reports - Quick Guide
SAP Crystal Reports is a Business Intelligence tool which is used to generate reports from both SAP and non-SAP data sources. It enables end users to generate reports that includes exceptional visualizations and implement new business requirements into reports to reduce dependency on IT and Report developers. SAP Crystal Reports can connect to any data source that include Relational databases like Oracle, OLAP data source systems like BW, or also with XML data. You can create a simple report or you can also use complex or specialized tool of Crystal Reports to create advance level reports for end users. It is mostly used for pixel perfect reporting for CEO’s and Managers. Flexible and customized report − You can quickly create highly formatted, pixel-perfect reports using SAP Crystal Reports with high level design interface and efficient workflows. Powerful report delivery options − You can deliver personalized reports to your business end-users in their preferred language and format. Data source connectivity − You can connect to information sources directly. Data sources include: Native, ODBC, OLE DB, and JDBC connectivity to relational, OLAP, web services, XML, enterprise data sources, and salesforce.com. Expanded support for Excel − You can take full advantage of the Excel file format by allowing more data to be exported to a single worksheet, without spanning multiple worksheets. Windows operating system compatibility − SAP Crystal Reports software 2013 is certified compatible with Microsoft Windows 7. Mobile compatibility − You can also open interactive reports through your mobile devices. SAP Crystal Reports, Adobe Flash and HTML 5 integration − It enables SAP Crystal Reports developers to produce powerful "mash-ups" pulling data from various sources. Competitors − SAP Crystal Reports competes with several products in Microsoft market like SQL Server Reporting Services SSRS, XtraReports, ActiveReports, and List & Label. Following are the basic requirements to install Crystal Reports − PC with AMD or Intel based processors, Dual Core CPU, 2 GB RAM PC with AMD or Intel based processors, Dual Core CPU, 2 GB RAM Approximately 4GB available hard drive space (for English only, 8 GB for all languages) Approximately 4GB available hard drive space (for English only, 8 GB for all languages) Microsoft Windows 7 SP1, Windows 8, Windows Server 2008 SP2, Windows Server 2008 R2 SP1, Windows Server 2012 Microsoft Windows 7 SP1, Windows 8, Windows Server 2008 SP2, Windows Server 2008 R2 SP1, Windows Server 2012 Languages available − English, Finnish, French, German, Hungarian, Italian, Japanese, Korean, Norwegian, Polish, Portuguese, Chinese simplified, Chinese traditional, Czech, Danish, Dutch, Slovakian, Slovenian, Spanish, Swedish, Thai, Turkish, Romanian, Russian Hardware Requirements − Intel Pentium III or equivalent processor, minimum 512 MB RAM recommended Hardware Requirements − Intel Pentium III or equivalent processor, minimum 512 MB RAM recommended Disk Space − 2 GB for default installation with English language, 4 GB for default installation with all languages installed Disk Space − 2 GB for default installation with English language, 4 GB for default installation with all languages installed Let us take an example to decode the SAP Crystal Reports version format. Assume 12.1.2.957.12 is the version of CR 2008. Here 1 signifies that it is Service Pack 1, .2 signifies that Fix Pack 1.2 has been applied on top of Service Pack 1. The last three of four digits are not important. Another example, if you have version 12.3.1.684, I know I am using CR 2008, Service Pack 3, Fix Pack 3.1. Editions − Developer (D), Professional (P), Standard (S) Editions − Developer (D), Professional (P), Standard (S) Editions − Developer (D), Professional (P), Standard (S) Editions − Developer (D), Professional (P), Standard (S) Crystal Reports for enterprise provides an interface that enables you to quickly and easily create, format, and publish effective reports. The menu bar provides full range of features available in Crystal Reports for Enterprise as shown in the following image. The standard toolbar as shown in the following image allows you to access common Report functions such as − Open an existing report, create a new report, save a report, print a report, cut, paste, export and undo. The Insert tab allows you to insert objects into you report, such as inserting a text, line, box, groups, sections, pictures, calculations and/or charts, as shown in the following image. The Format tab as shown in the following image, allows you to use functions for formatting the selected field such as − changing the font size or font color, background color, alignment of text to center, left, right, etc. It also allows you to apply conditional formatting, such as highlighting values above or below a specific threshold value in the report. When you click on conditional formatting option at top right corner, the formatting box open. In this box, you define the condition under which you want conditional formatting to appear. In setting area, specify the formatting to appear when condition is met, like changing font style or color of text. The Data tab as shown in the following figure, enables you to work with data-editing queries, creating groups and sorts, applying filters to limit data in the report and creating formulas to add custom calculations to reports. When you click on Query filter option or on Edit data sources, as shown in the following image, a query panel opens. In the Query panel, you can select objects that you want to see in the report. In the filter option, you can apply filters to restrict the data returned by the report. When you click on Formula button, as shown in the following image, the Formula workshop opens. This allow you to use custom calculations in the report. You can apply formulas by typing or by clicking on objects, functions and operators in the data explorer. The main working area in Crystal Reports is known as Report Design Canvas and is divided into structure tab and page tab. Crystal Report is divided into five different parts by default and additional sections are added if you apply grouping to the report. Using the Structure tab, as shown in the above image, you can create the overall structure by placing items in various sections of the report. You can also apply any required sorting, grouping, etc. Here, you work with placeholders for data and not data itself. The Page tab, as shown in the following image, displays the report data on the basis of the structure you created in the structure tab. Here, you can evaluate formatting and layout of the report design for distribution. Report Options is one of the most commonly used feature in Crystal Report Designer, when you need to access/modify the values of Report Options of a Crystal report at runtime in a Crystal Reports .NET application. Go to Edit → Report Options Report Options feature is used to set various fields in a Crystal Reports such as, smart guidelines feature that lets you select, move, and resize entire columns of report elements without needing to manually select each element. When you select a report element, the smart guidelines appear and automatically select related elements in the column. SAP Crystal Report gives two options of page layout - landscape and portrait. Landscape means the page is oriented horizontally, while portrait means the page is oriented vertically. To open Page Layout option in Crystal Report, go to File → Page Setup. This option allows you to choose page options like: Paper size, paper width, paper height, and margins (left, right, top and bottom). To change the page layout − Select the Page Setup tab in File Menu. Click the Orientation option in the Page Setup group. SAP Crystal Report for Enterprise help tab provides all the study material and interactive videos link from SAP site to learn Crystal Report features. The following options as shown in the image, are available when you click on Help tab in menu bar − SAP Crystal Reports for Enterprise Help Documentation Tutorials Show Start Page Contact Us Register About SAP Crystal Report for Enterprise This options provides you with a complete guide titled Introduction to SAP Crystal Report for Enterprise as shown in the following image. This covers an introduction to Crystal Reports Enterprise 4.x and all basic reporting functions available in the tool like logging on to a server, introduction to reporting, design concepts, data sources and queries, charting, etc. When you click on documentation option in Help tab, it takes you to SAP link for Crystal Report for Enterprise 4.x. This link has Crystal Report for Enterprise 4.x guides for − Installation, Upgrade and Deployment End Users guide Additional Information When you click on Tutorials link in Help tab, it takes you to the Official Product Tutorials – SAP BusinessObjects Crystal Reports for Enterprise 4.x This page provides eLearning material which includes interactive sessions and video tutorials on all key features of the tool. It takes you to the homepage of SAP Crystal Reports Enterprise 4.1 tool. Contact Us and Register Option are used to contact SAP for any tool related features. It takes you to the About page of the tool that has Versions and Build details. SAP Crystal Report design environment provides you the area where you can design the structure of the report. It consists of multiple components − The Report Design Canvas is used to design the structure of your report. You can place various elements like charts, test elements, and data objects in the report. Show ruler option displays a ruler above the report canvas. You can change the unit of measurement by changing the measurement unit option on design canvas tab. Structure mode and Page mode are available to define the layout of the report. Structure mode shows the structure of the report and Page mode is used for previewing the report. Edit → Preference → Design Canvas Structure mode is used to provide an environment for designing the report. It provides a structure and instructions for creating the report. When you place an object in the report, it is shown in Structure mode. You can add/delete objects or apply complex formulas or you can also move the objects. Each object in Structure mode is represented by a frame. Structure mode has multiple components that can be used to edit the report − It is used to add Report title at the top or any other information you want to place at the beginning of the report. This option is used to present information at the top of each page like document heading, chapter name, etc. Page header doesn’t come in Report Header. This is used to show the body of the report. All report data comes in this section. This is used to present information at the end of the report like totals, etc. This is used to present page numbers or any other information you want at the end of each page. It represents the actual data in the report when the report is published or printed. It also allows you to change the formatting of the report with actual data and changes are immediately visible in the report. It is used to add/delete objects in the report. When you create a new report or open an existing report, this side panel opens itself. All the objects that are added in the query panel are shown under data explorer and from here you can add objects to the report. This is further divided into the following components − It shows all the objects that has been added to the report. You can also drag the objects to add in the report. Edit Data Sources option enables you to add new objects from the Universe or to choose a new Universe/Data Source from the repository. This shows all the formula that has been created for the report. You can create new formula with a right click on Formula tab and → New → New Formula. You can also drag formulas to the report. It shows all the parameters that has been created for the report. You can create new parameter group with a right click on Parameter → New → New Parameter. It shows a list of all running totals that has been created for the report. You can create new running totals with a right click on tab → New Running Total. It shows the predefined objects that can be added to a report. You can drag predefined objects to report canvas to add them to the report. It is used to see the tree structure of the report. The first node in tree structure represents the report itself, the first level node represents the sections in the report, and each section containing objects are listed. It is used to see tree view of all groups and subgroups in the report. It is used to search a specific value in the report. Type a word in the search box to find any value. Crystal Report can connect to multiple data sources that includes − Universe SAP BEx Query Relational Connection HANA view Excel Spreadsheets To connect to a Data source, go to File → New → From Data Source To select a data source you must be connected to SAP Business Objects platform server. When you go to File → New → From Data Source → Choose a data source connection dialogue box appears → Browse Repository → Data Source Type list → Select data source you want to connect → Next. If you choose a Universe, a query panel opens and you can add objects to query filter to generate a report. SAP BEx and Universe data source connections allow you to create and design query in Crystal Reports. To create a query in Universe you can choose both OLAP and Relational data sources. First step in a query design is to define objects that you want to add in your query. You can also refine your query by applying sorts and query filters. Query panel is divided into multiple panes − It contains a tree structure of all the objects in Universe. You can see all the objects in Universe by using Expand All option. You cannot add new objects or edit existing objects in query panel. In this area, you add objects that you want in your query. This is used to filter the value of objects in the report. You can use predefined filters or can create custom filters by adding objects. SAP BEx queries can contain one or more hierarchies and predefine objects to run the report. SAP HANA queries include data from SAP HANA Modeling views: Analytic, Calculation Views. To connect to HANA database and to use Schemas → tables inside the database, you can use an existing Relational or OLAP connection. A Relational connection can be created in IDT tool. An OLAP connection can be created in CMC as well as in Information Design tool. HANA multi-dimensional views can be connected to Crystal Reports using an OLAP connection. Click on Next → It will show you list of all Modeling views inside HANA repository → Select a Modeling View → Finish It will open objects of view in a query panel, which can be used to add them to the report. Once the Crystal Report is created using a query, to make changes to objects you have to go to edit data source option. When you click on the option, it will open an Edit Query panel where you can add/delete objects, apply filters, etc. You can also edit an existing query by going to Data → Edit Data Sources as shown in the following image. Once you are done with the changes, click on Finish and all changes will be applied to data in Crystal Report. Following are the types of query filters that can be used in Crystal Reports − Predefined filters Custom Filters Custom Filters These are inbuilt filters in query panel created by the administrator. Predefined filters are created at the Universe level and are directly used in the report from the Universe. Drag an object on which you want to apply filter to query filter pane and drag predefined filters too. When you run the query data w.r.t query filter will be returned in the report. These filters are created with the queries in the query panel. Custom filters are created in the Query panel under the query filter tab. Drag the object to the query filter pane and make use of various relational operator to pass the filter condition. You can put a constant value or a list of values in the query filter. They are used to display a question or list of values and are known as dynamic filters. Constant option allows you to enter a single value in filter. List of values allow you to choose one value from all the available values for an object. Prompt is used to pass dynamic value to a query filter. Type a value into the text box Type a value into the text box In the Prompt(s) dialog box, add members to your list by double-clicking them, or by selecting them in the Members pane and clicking the arrow in the center In the Prompt(s) dialog box, add members to your list by double-clicking them, or by selecting them in the Members pane and clicking the arrow in the center Click ok Click ok In the Edit Prompt dialog box, select New Prompt to add a new prompt, or Use Universe Parameters to select a parameter from your universe In the Edit Prompt dialog box, select New Prompt to add a new prompt, or Use Universe Parameters to select a parameter from your universe If you selected a New Prompt, enter prompt options, or if you selected Use Universe Parameters, select a parameter If you selected a New Prompt, enter prompt options, or if you selected Use Universe Parameters, select a parameter Click ok Click ok Time based query filters are used to filter the value of specific objects between certain periods of time. When you add a date dimension to query filter, you can use between operators from drop down list to specifically mention to and from date. You can click on calendar option to select dates in ‘to’ and ‘from’ fields. You can also use Date dimension with the list of values (LOVs) or Constant value option. LOVs allow you to select to and from date from the list of values available for Date dimension in the Universe. This is known as applying Time based filters in the report. Field objects controls are used to edit the object in the report. To edit the object, you can right click on the object name and select ‘Format result Object Element’ or ‘Conditional Formatting’ option as shown in the following image. Format Result Object Element field is used to change the appearance of the objects in the report. It has the following 4 tabs inside − General Font Appearance Paragraph General tab is used to define generic properties of report objects: like height and width, hide and hide if duplicate, etc. Advanced tab in General is used to pass hyperlink in the report. Font tab is used to change font size, color, style, alignment and rotation of object name in the report. Appearance tab is used to change the border and to add effects to the report objects. Paragraph tab is used to define line properties in case of multiple lines in the report. Conditional formatting is used to pass conditions for appearance of report objects. You can pass the value of an object by clicking on Add condition tab → select object name and pass condition. You can define font style, font color, etc. As discussed earlier, Crystal Reports by default provides five main sections − Report Header Page Header Body Report Footer Page Footer Here, we will learn how to insert, hide, and delete sections in Crystal Report for Enterprise 4.x. To insert a section in any of the report section, select the section → Right click and Insert. You can use Hide and move option to hide a section or to move the section up and down. Format Section option allows you to format the section properties. It includes − Name Color Size Size option allows you to adjust the height of the section. To keep a section from breaking across pages − If an element is longer than one page then it prints across multiple pages. To avoid this you can use Paging option. Right click a section and click format section → Paging → Select Avoid Page Break and click Close. Now let us see how to insert, hide and delete sections in Crystal Report 2013. Section Expert as shown in the following image is used to manage sections in the report. To insert a new section you need to − Click Section Expert button as shown in the following image (Section Expert contains a list of all the sections in the report) → Select section and click insert. A new section will appear in the report. Open Section expert at the top and select the section you want to delete → enter Delete. You can only delete the section if they are lettered. You cannot delete sections originally provided by Crystal Reports. Open Section Expert →Select section you want to move and use up and down arrows to change the order of the sections. Open Section Expert → Move sections you want to merge with each other → select the top section → Click merge. Sections will be merged with the section that is next on the list. Click on the boundary of the section you want to split → Horizontal line that splits section will appear → Drag-and-drop to the place where you want to split the section. Sometimes you are required to sort data in Crystal Reports in a certain order. When you sort the data, it is easier to find specific records in the report. You can add a sort in ascending or descending order and it can also be applied to attributes and measures value. You can also remove the sorting using delete option in Sort tab. Let us see how to apply sort in Crystal Reports. To apply a sort in Crystal Report for enterprise 4.x, go to Structure tab of the report → click on Data tab at top and choose sort. When you click on sort option, it will pop-up a window with group and sort option. Go to Sort tab and expand the body tab to apply sorting on measures and attribute values in the report. To add a sort, click on Add sort option. It will show you all the attributes and measures added to the report. Choose the object on which you want to apply sorting and click on ascending and descending option. A → Z Ascending or Z → A Descending You can also add multiple sort in a single report and click on OK. To view sorted data go to Page tab. In the above example, it has applied a sorting on customer name and then Quantity sold. To delete a sort, select the sort and click on delete sort option. In this chapter, we will cover how to define, render and delete groups. When you need to separate the data into groups in order to make it easily understood, grouping option can be used. You can also customize grouping for a single value or multiple values by using the customize option inside the grouping tab. To apply grouping in the report, go to structure tab of the report → Data → Groups To add a grouping condition. Click on New (‘+’ sign) and select the attribute on which you want to apply grouping. If you apply regular grouping on one object, it will group all the similar values in a report. To apply grouping on single value, go to customize grouping option → New → Add Condition → select operator and value from the dropdown list as shown in the following image − It also gives an option to discard everything else, group everything else in single group with group name or include everything else without changing the group name. In the following example, it has created 2 groups: first with Region Name=”New Delhi” and second group with everything else with group name “Others”. When you use grouping in a report, two new sections appear in the report canvas − Group Header 1 and Group Footer 1. To delete a group, select the group you want to remove and click on the Delete option. Go to Structure of the report → Groups → select groups #1, 2 you want to delete → Delete. You can use the following 3 options while customizing a group in Crystal Reports − Discard everything else Discard everything else Group everything else in a single group with a group name Group everything else in a single group with a group name Include everything else without changing the group name Include everything else without changing the group name When you are in Page tab, the group tree icon in side panel is used to see tree view of groups in the report. It allows you to jump to a specific group in the report instead of scrolling through the report looking for a specific group. Live header changes based on the content of the group. When you define a group in the report, the program automatically inserts a group name in the element, in the group header section. This element displays the group’s name. The grouping of data in the report is done to find the total for each group in the report. Many totaling options are available − Sum, count, maximum, minimum, average, etc. You can also add subtotal to your report. Total option in the report − Go to insert tab → Select options for your total To change the format of the total box, right click on total value → format total. Instead of creating a report from scratch, you can also use inbuilt templates from the report repository. These report templates provide predefined layout for common documents like purchase orders, invoices, letter templates, etc. To select a Report template from the repository, go to File → New → From Web template There are two template options in Crystal Reports − Featured Templates Recently Used You can also perform a search using the search tool. Once you choose a report template you will be asked to select a data source. Select Preview (To preview the report template before selecting data source)→ Set Data Source location to select a data source → Target Data Source panel, Add Connection icon → Choose a Data Source Connection dialog box appears. Select your data source connection from one of the following options − Previous Connections − This option lets you use previously connected data sources. Browse Repository − This option lets you choose your data source from the Data Source Type list. Connection by Vendor − This option connects to data sources sorted by a vendor or software provider. Click Finish. Select an object from the Current Data Source panel and connect it to an object in the Target Data Source panel → click on map → click on done. Insert options in Crystal Reports for Enterprise allows you to add multiple objects at the report level: charts, crosstabs, picture, flash, sub-reports, etc. You can add multiple format pictures in the report. It can also be used if you want to add company logos, brand name, etc. in the report. When you click on Picture, it gives an option to insert a picture in the report. The following common picture formats are supported in Crystal Reports − jpeg png gif tiff It also allows you to insert flash files in the report. When you click on flash, you can choose the file path or directly embed the link of the flash file to add in the report. It supports .swf file types in the flash file so you can add dynamic dashboards in the report. In this chapter, we will learn about types of charts, creating and formatting charts. You can use below chart types in Crystal Reports for enterprise. To insert a chart, go to Insert → Chart → select Chart type and insert the chart in the structure or page tab. You can insert a chart in Report footer. When you select the chart type from Insert chart option, you can move the cursor to the report footer area and click where you want to insert the chart. When you insert a chart it gives you two options − Data and Show chart. Show chart option allows you to resize the chart, move the chart in the Report footer area (as shown above). Data tab allows you to insert the data in the chart. When you go to data tab, it asks you to add values on X, Y, Z axis. Right click on each axis and go to Insert Chart Category Object → you can choose Selected Elements from the dropdown list → Chart Data Object, Title, Subtitle, foot note, legend, etc. Chart Data object allows you to choose the attribute name, which you want to pass in the chart data. Title, subtitle and footnote allows you to add heading or note to the chart. When you right click on chart it gives you the following formatting options − Format Chart − Allows you to format structure of the chart by going into advance, appearance and depth option. You can also change the type of chart from the dropdown list by clicking on the Chart option in the Format chart tab. Chart Highlighting Expert allows you to highlight a specific value in the chart. You can choose different color to highlight a value inside chart. Add Condition → Choose attribute which you want to highlight in the chart as shown in the following image. Edit Chart Type is same as format chart with all of the options being similar. Edit Chart data is used to edit the data in the chart. If you want to change the parameter values on the chart axis, you can click on edit chart data and change the values. Hide option is used to hide the chart and move is used to move the chart backward or forward. You can add multiple charts in a single report or in one row by formatting the chart size. Example - You can add bar chart and pie chart for different values to represent. You will see Show chart and Data option for the second chart → you can add required objects and also add header and footer note to the chart as shown in the following image. To see the actual report, go to Page tab. Cross tab is used to display the data that is grouped or totaled in two directions. It shows data in a compact format, which makes it easier to understand and see the trend in the data. For example, if you want to see the quantity sold by the customer in a particular region, without cross tab, it shows the data in a spread-out form. You can add multiple number of attributes in rows and columns by clicking on ‘+’ sign. To delete an object click on X sign. When you click on Insert, cross tab adds to the Structure of the report. If you click on the page tab, it will show Cross tab data in the report. You can also edit the cells in cross tab. To edit Cross tab properties, right click on Cross tab and you can change the properties − Format Cross tab Edit Cross tab Sort Hide Grid Options Pivot Create chart from cross tab A Crosstab includes row totals, column totals and grand totals. To see values as percentage, right click on Total cell and go to Format Total → select show as percentage. Grid options allow you to do formatting of cross tab rows like hiding empty rows, repeat row labels, hide row grand totals, etc. as shown in the following image. Formulas are used to insert data in the report that does not exist with any of the objects. If there is a need to perform some calculations or to add specialized data in the report, you can use formulas. Example − (Emp_details.sal)*0.15 Common formulas are − Calculations, string functions like UPPERCASE, date functions, etc. Formula contains two parts in the report − Syntax Components The components are used to create formulas. Crystal Reports has the following types of formulas − Report formulas and conditional formatting formulas. Report formulas are used as standalone in a report. Conditional formatting formulas define the condition on which report formulas are applied. Formula workshop is used to create different kinds of formulas. You can open formula workshop by going to Data → click formulas or by clicking formula tab on Data tool bar. In the formula workshop there are 2 panels − Navigation Panel and Objects Panel. Navigation panel contains a folder for each type of formulas in Crystal Reports. Object Panels contains 4 fields − Data Explorer − It contains in-use Objects, formulas, parameters and running totals present in the Crystal Report. Result Objects − It contains all result objects available to use in the report. Functions − It contains all inbuilt functions that can be used in the report. It also includes custom functions. Example − Sum, Count, String functions, Date functions, etc. Operators − They are used to pass conditions between values. It includes: arithmetic operators, Arrays, Boolean operators, etc. Formula workshop also contains formula text window and formula workshop buttons. Text windows is used to create or modify formulas and workshop panel button allows you to use filter formulas, sort formulas, delete, etc. You can create single or multiple formulas in one go and use them in your report. You can also delete the formulas, or search and change text of formulas in the formula text window. To create a new formula, you can right click on Formula tab under Data Explorer. Once you click on the new formula → enter the formula name → it opens the formula workshop. You can also create a new formula by opening the Formula workshop from the Formula tab under Data → New → New Formula as shown in the following image. To write a formula in the formula text window, you can use in-use objects under the Operator tab and different operators to pass condition in the formula. formula can be saved using the save option at the bottom of the page. Once the formula is saved it comes under the list of formulas in Data Explorer tab. You can drag this formula to any section of the report. In the above snapshot, Test formula has been dragged to Report footer and it has calculated value as Quantity sold/2 in the Report footer. Now to modify the formula,click on formula name under Data explorer, it will open the Formula workshop. Make changes to formula and use the save button at the bottom to save the changes. These changes will be automatically applied to the Report values. To delete the formula from a report, right click on the formula name and click on Delete. Problem pane at bottom is used for debugging purpose. It shows you the syntax error in the formula. The error message in the following image says that the field in red underline is not known as field syntax and is incorrect. There are different Boolean operators that can be used in formula in Crystal Reports. They are − AND OR NOT Eqv Imp XOR All these operators are used to pass multiple conditions in formulas − AND operator is used when you want both the conditions in the formula to be true. Other Boolean operators and their meaning is as mentioned in the above snapshot. Using Boolean Operators ‘AND’ − If {CUSTOMER.CUSTOMER_NAME} [1 to 2] = "AN" and ToText({CUSTOMER.CUSTOMER ID}) [2] = "4" then "TRUE" Else "FALSE" Using Boolean Operators ‘AND’ and ‘OR’ − If ({CUSTOMER.CUSTOMER_NAME} [1 to 2] = "AN" and ToText({CUSTOMER.CUSTOMER ID}) [1] = "4") or ({CUSTOMER.CUSTOMER_NAME} [1 to 2] = "Ja" and ToText({CUSTOMER.CUSTOMER ID}) [1] = "2") then "Five star rating CUSTOMER" Else "1 star rating CUSTOMER" The if-then-Else statement is the most basic of all the control flow statements. It tells your program to execute a certain section of code only if a particular condition meets true. If you see the following If-Then-Else statement with Boolean operators, it has allowed you to pass multiple conditions in the formula and returning the value, if the condition is true. If({PROJECT.Customer\Customer Name} [1 to 2] = "An" and ToText({PROJECT.Time\Year}) [1] = "2") or ({Project.Customer\CUSTOMER NAME} [1 to 2] = "Ja" and ToText({PROJECT.Time\Year}) [1] = "2") Then "Five star rating CUSTOMER" Else "1 star rating CUSTOMER" This statement says that when any of the condition is true (before and after OR operator), then it will print Five star rating customer otherwise it will print 1 star rating customer. This formula has been saved and then added to the body of the report under the structure tab as shown in the following images − A new column in the report has been added with the rating of the customers as mentioned in the TEST formula. Calculated formulas are used to perform mathematical calculations in Crystal Reports and they can be designed in the formula workshop. Arithmetic operators are used to design calculation formulas in workshop. There are different Arithmetic operators that can be used to Add, Divide, Exponential, Multiply, etc. To apply a calculation in the formula, drag the object from the objects pane to the formula text pane and use operators to perform the required calculation. Once you have saved the formula using the save option at the bottom, this formula will be saved under the Formula tab in Data explorer. You can then drag the formula to Report structure and go to Page tab to see the calculated data in the report. List of Arithmetic operators from highest to lowest precedence are − Exponentiation Negation Multiply, Divide and percentage Integer division Mod Addition and Subtraction To write a conditional formatting formula, right-click the report and click Format Result Object element → select the property on which you want to apply conditional formula → click and it will open formula workshop. Write the formula in the formula text pane, save and close it. In this example, if you can print Total Price greater than 60000 in Green and below 60000 in Red, this can be passed in formula workshop. In this example, crGreen, crRed, crBlack is used. You can also use actual numeric value of color constants. There are three common conditional formatting functions − CurrentObjectValue DefaultAttribute GridRowColumnValue DefaultAttribute can be used for any formatting formula, CurrentObjectValue for any formatting formula where you are formatting an object value, and GridRowColumnValue can be used for any formatting formula where you are formatting an object value in a Cross-Tab. A Variable is used to assign different values to an object unlike constant which is fixed. When you assign a value to a variable, it maintains that value till you assign a new value to it. Before using variables, it is necessary to define them in a report. When you declare a variable in Crystal Report you need to assign a name to it, however this name shouldn’t be the same as any other function, operator, etc. A variable can be a number type, string type, date type, Boolean type, range type or an array type. A variable can hold a value of single type, like if you declare it as a number it can’t be used to hold string values later. Local Stringvar Customer_Lastname Local numbervar Sales_percentage The keyword for declaring the variable has ‘var’ at the end and it is true for all variable types. You can also assign an initial value to a variable with declaration or in separate syntax. Local NumberVar Z; //Declare Z to be a Number variable Z := 30; //Assign the value of 30 to Z To use Variables in formulas, its scope is defined. Variable scope can be of three types − Local Global Shared This defines that a variable in one formula can be used in other formula. Local variables are declared using the local keyword followed by the type and followed by the variable name as in the above examples. Local variables are restricted to a single formula. This means that you cannot access the value of a local variable in one formula from a different formula. //Formula 1 Local NumberVar Z; Z := 30; //Formula 2 EvaluateAfter ({@Formula A}) Local NumberVar Z; Z := z + 5; In the above example, Formula 2 will return a value 5 as Z is declared as local number variable in formula 1 so it will take default value for variable Z in formula 2. Global variables are used throughout the main report. Their value is available to all formulas that declare the variable, except for those in sub reports. Global StringVar Z; It is recommended that you use global variable only when local variables do not suffice. Since global variables share their values throughout the main report, you cannot declare a global variable in one formula with one type and then declare a global variable with the same name in a different formula with a different type. Shared variables are used throughout the main report and all of its sub reports. Shared variables are even more general than global variables. To use a shared variable, declare it in a formula in the main report − Shared NumberVar Z := 10; To use shared variables, it must be declared and assigned a value before it can be used in the main report and subreports. An Array variable in Crystal Report can be defined by using a keyword “Array”. Global NumberVar Array Z := [1, 2, 3]; You can also assign values to the elements of Array and these values can be used for computations in formulas. For example − StringVar Array Z := [“Hello”,”World”]; Z[2] :=[“Bye”]; UpperCase (Z [2] ) This formula will return the string “Bye”. You can also resize Array using Redim and Redim Preserve keywords. Redim is used to remove previous entries of an Array while resizing it, and Redim Preserve is used to contain previous Array values. For example − Local NumberVar Array Z; Redim Z [2]; //Now Z is [0, 0] Z [2] := 10; //Now Z is [0, 10] Redim Z [3]; //Now Z is [0, 0, 0], Redim has erased previous Array values. Z [3] := 20; //Now Z is [0, 0, 20] Redim Preserve Z [4]; //Now Z is [0, 0, 20, 0], Redim Preserve has contained previous Array values. "finished" Arrays are also used with Loops: like For loop. Local NumberVar Array Z; Redim Z[10]; Local NumberVar x; For x := 1 To 10 Do (Z[x] := 10 * x); Z [5] //The formula returns the Number 50 Parameters are used to take user inputs before the report is generated. User has to answer the prompt before the report is generated and the report output depends on the response of the user for the parameter value. By using parameters with formulas and in the report, you can create a single report that changes according to the requirement of different users. LOVs can be used to enter prompt values in parameters. LOVs can be either static or dynamic. They can also be used as single level dynamic prompts or multilevel prompts. Note − Parameters in Crystal Reports can be used in filters after it is retrieved from the database. Parameters with dependency are grouped together and are known as cascading parameters. Cascading parameters allow you to group two or more parameters in a single group. Parameters can also be created at universe level or in query panel and they can be later inherited into Crystal Reports. They are called inherited parameters. These parameters can be dropped at the report level but they can’t be edited in a report. These parameters can only be edited where they are created. Parameters in Crystal Report support below data types − Number String Date Time DateTime Currency Boolean Member Important points to remember while using Parameters − To use parameter in a formula, it is not necessary to be placed in the report. Parameters can be used in a formula like other objects and can be created in the Formula workshop. To use parameter in a formula, it is not necessary to be placed in the report. Parameters can be used in a formula like other objects and can be created in the Formula workshop. Parameters can be used with static or dynamic LOVs. Parameters can be used with static or dynamic LOVs. You can also create a list of values from which the user can choose the parameter value instead of entering it manually. You can also create a list of values from which the user can choose the parameter value instead of entering it manually. Using data that does not change Filtering data after it has been retrieved from the database. Filtering report data interactively without accessing the database. Creating an LOV where it doesn't already exist in the data source. such as in a Universe or a BEx Query. Creating reusable lists of values that are managed by the Universe administrator. In Data Explorer view, right-click within the Parameters area → select New → New Parameter The Create Parameter dialog box appears → Enter a name for the parameter (up to 255 alphanumeric characters). In the dialog box, you can change the name and type of the parameter along with other properties. Select the appropriate Data Type from the list → such as String, Number, or Date, among others. In the Prompt Text box, enter the desired prompting text (up to 255 alphanumeric characters). For example − "Select a Name" This text will appear in the prompting dialog box when you preview the report, or when you refresh the data on the Page area. To create a list of values, click the ellipsis button → The Edit List of Values dialog box appears → Enter the values that you want to see when you are prompted → you might add a list of countries for a String type, or a list of values for a Number type → click OK → You return to the Create Parameter dialog → click OK and drag the parameter to your Report. Once the parameter is dragged to the structure of report, you can go to page tab to see LOVs selected while refreshing the report data. Filters are used to limit the records in a Crystal Report as per the user’s requirement. Filters are applied based on the object, operator and parameter. Go to Data tab at the top → Interactive Filter Click Add Filter → Select first object from filter → Select Operator → Select Parameter In the dropdown list it will show the list of all parameters that are created for the report. To edit the parameter, you can click on ellipsis button in the end. When a parameter is selected, click on OK. If you have selected list of values in parameter, it will ask you to select a value from the dropdown list → Select value → OK Choose saved data or refresh data → Report now shows only filter data. To add multiple interactive filters, you can use ‘AND’ and ‘OR’ operators. Go to Data tab →Interactive filter → Select filter you want to delete → Click on delete button While creating parameters, two types of prompt options can be used. Prompt to user will create a prompt for the user to enter the value of parameter. Prompt to user will create a prompt for the user to enter the value of parameter. Hidden Prompt will be used to pass some initial values or values by formula and not by the user. Hidden Prompt will be used to pass some initial values or values by formula and not by the user. When you use prompt to user option in Prompt panel, you need to enter Prompt text. Prompt panel gives you three options − Do not show prompt − It doesn’t give you an option to change value at the report level. Do not show prompt − It doesn’t give you an option to change value at the report level. Show as Editable Prompt − It gives an option to enter different value each time. Show as Editable Prompt − It gives an option to enter different value each time. Show as Read Only Prompt − It gives an option to see the value in read-only mode. Show as Read Only Prompt − It gives an option to see the value in read-only mode. Hidden Prompt are used to pass initial values or values by formula. To pass initial value, click on ellipsis button just before function button. Once you click on this, it asks you to enter a value for the parameter. Once you enter the value and click on OK that value will be saved in Hidden prompt. To add a value, type the value and click on Add. When you drag the parameter to the report, that value will appear in the report as shown in the above image. Cascading parameter group allows to arrange your parameters into groups, which provides a cascade of filtered choices. For example, if you are prompting for a city value, but you also need to know which country and region that city comes from, you could create a cascading parameter group. In this case, you first prompt for a country, and when that value has been selected, the program prompts for a region by showing only the regions that apply to the selected country. Finally, when a region value has been selected, the program prompts for a city by showing only the cities that apply to the selected region. In this way, you can provide your user with a manageable list of cities and be sure that your user picks the correct city. Go to Data Explorer → Parameter → New → New Cascading Parameter group Create a Parameter Group dialog box appears → Enter a name for the Parameter group → Enter the Prompt text as shown in the following image. Now click the first blank row in value column, it will show you all the available objects in the list. From the list, select Country → Select blank row below Country and select Region → OK Now drag the country parameter to the report. It will give a prompt to enter Country name. Once you choose country name → it will give a prompt to choose the region name. Drag Region name to the report. In Data Explorer view, right-click within the Parameters area → select New → New Parameter The Create Parameter dialog box appears → Enter a name for the parameter (up to 255 alphanumeric characters). In the dialog box, you can change the name and type of the parameter along with other properties. Select the appropriate Data Type from the list → such as String, Number, or Date, among others. In the Data Explorer → right click on Parameters → select New → New Parameter In the Create Parameter dialog box, enter a name for the parameter. Select the appropriate Data Type from the list → Enter prompting text → Set Allow Multiple Values to True. Now, when prompting, you can specify multiple values to be entered for the parameter. For the type of value range, choose Discrete or Range. If you select Discrete, the parameter will accept discrete values (rather than ranges of values). If you select Range, you are prompted for parameter values. You can enter a start value and an end value. For example, if you enter the values "1" and "10", the range is 1-10, and a report that uses this parameter for filtering will display all records with values between 1 and 10. This also works for string parameters. With a start value of "A" and an end value of "H", a report that uses this parameter for filtering will display all records within an alphabetical range of A-H. If the Allow Multiple Values and the Discrete Options are selected, the parameter will accept multiple discrete values. You can enter more than one value, but these values will be evaluated individually and will not be interpreted as a range. If the Allow Multiple Values and Range Options are selected, the parameter will accept multiple ranges. Once you drag the parameter to your report → To edit parameter filed, right click on parameter name and go to edit parameter. Once you click on edit parameter, it will open Edit parameter window. You can also edit the parameter by double clicking on the parameter name. Go to Data Explorer view → expand Parameters, and then right click on the parameter you want to delete. Choose Delete. You can create parameters using dynamic LOVs to retrieve data from data source. For example − When the customer name in database changes frequently, you can create dynamic LOVs. Open your report → Data Explorer panel → right click within Parameters and select New Parameter. The Create Parameter dialog box appears. Enter a name for the parameter (up to 255 alphanumeric characters) → To create a list of values, click the “Edit List of Values” button. The Edit List of Values dialog box appears → In the Type of List area, select Dynamic. In the Value combo box, select Customer Name from the list. You can sort the LOV in Ascending or Descending order → Click OK. In the Prompt Text object, enter the desired prompting text (up to 255 alphanumeric characters) → Text that appears in the prompting dialog and interactive panel. The default is “Enter (ParameterName)” → Click OK Drag the Parameter into your report. Subreports allow you to combine unrelated reports into a single report. It is a report within a report. You can combine data that cannot be linked and present different views of the same data in a single report. Difference between Subreport and main report − It is used as an element in the main report and cannot be used as single report. It is used as an element in the main report and cannot be used as single report. A Subreport cannot contain other subreports. A Subreport cannot contain other subreports. It can be placed in any report section and the entire subreport will print in that section. It can be placed in any report section and the entire subreport will print in that section. It doesn’t have page header or page footers sections. It doesn’t have page header or page footers sections. Unlinked subreports are standalone reports and their data is not linked to data in the main report. An unlinked subreport does not have to use the same data as the main report; it can use the same data source or a different data source entirely. Regardless of the underlying data sources, the reports are treated as unrelated. Linked subreports use data that is coordinated with data in the main report. The program matches up the data in the subreport with data in the main report. If you create a main report with customer information and a subreport with order information and then link them, the program creates a subreport for each customer that includes all their orders. Subreports can be linked with data-passing links or with subreport filters. You can insert a new report or an existing report as subreport in a main report. The subreport has similar characteristics as the main report. The data source to be used in subreport must be similar to data source that is used in main report and it must also be located on the same BI repository. You can also choose a different source connection but it should have a field to link to main report. A subreport can’t be inserted into another subreport. A subreport can be placed in any report section and the entire subreport will print in that section. However, a subreport cannot stand on its own. It is always inserted as an element into a main report. Go to Insert tab, click Subreport → The program displays an element frame. Move the cursor to where you want it to appear in the report, and click to place it. The Insert Subreport dialog box appears → Select create a new report → Type a name for the report in the Report Name text box. (You can also insert an existing subreport). The Edit Query page appears The Edit Query page appears The Choose a Data Source Connection dialog box appears The Choose a Data Source Connection dialog box appears Select a data source, and then click Next Select a data source, and then click Next The Edit Query page appears The Edit Query page appears Choose an option from the Data Connection area, and click ‘Next’. If you choose Use Main Report Data Source it will open Query panel to add objects in the report. If you select connect to a new Data source, it will open New Data source connection window from which you can choose a new data source. Once you choose new data source, you need to define the relationship between the main report and the subreport. Once you click on ‘Next’ it will prompt you to choose a Sub Report type like Detailed, Chart, Total, Custom. Click on finish → it will show in the Structure of the main report. If you click on Page tab it will show the data of Subreport in the main report. On the Insert tab, click Subreport → The program displays an element frame. Move the cursor to where you want it to appear in the report, and click to place it. The Insert Subreport wizard appears → Select Use existing report, and then click Browse. The Open dialog box appears → Select the report that you would like to use, and then click Open → Click Next. If the report you selected contains parameters, the Data Passing Links page appears. Set up the appropriate links, and click ‘Next’. The Create Subreport Filters page appears → Create links between your main report and subreport by clicking Add → Click Finish. The report that you selected is added as a subreport. You can also save a subreport as a main report. Right click on the subreport frame, and click Save Subreport As → Save As Type a new name for the subreport → Click Save. The subreport is saved as a main report and you can open it and use it. You can edit the properties of a subreport after you have inserted it into your main report. To format subreports − Right click on the subreport frame and click Format Subreport. The Format dialog box appears → Edit the values. For example, you can change the name of the subreport, edit the font, size, color, etc. Click Close. Create the report you want to be printed first as the main report. Create a new subreport. Place the subreport into the Report Footer and it will print immediately after the main report. On-demand subreports can be especially useful when you want to create a report that contains multiple subreports. The difference between regular subreports and on-demand subreports is that the actual data of an on-demand subreport is not read from the data source until the user isolates it. This way only data for on-demand subreports that are actually viewed will be retrieved from the data source. This makes the subreports much more manageable. To create an on-demand subreport: Place an ordinary subreport in your main report. Right click on the subreport, and click Format Subreport. Click the Subreport option, and select On Demand. Finished Crystal Reports can be exported to a number of formats like XML, HTM, PDF, spreadsheets and word processors and other common data interchange formats. This allows Crystal Report to use and distribute in an easy way. For example, you may want to use the report data to enhance the presentation of data in a desktop publishing package. The exporting process requires you to specify a format and a destination. The format determines the file type, and the destination determines where the file is located. In Page mode, click File → Export and select an export format from the list. The Export Options dialog box appears. Select the export options. Click OK → You can also set a format as default options. In the Export Destination dialog box that appears, do one of the following − Click ‘To file’ and enter the report title to save the exported report in the Export Report dialog box. Click ‘To file’ and enter the report title to save the exported report in the Export Report dialog box. Click ‘To application’ to open the report in the selected application without saving it. Click ‘To application’ to open the report in the selected application without saving it. There are different Excel options to export the data of a Crystal Report. Microsoft Excel (97-2003) Data-Only is a record-based format that concentrates on the data. This format does export most of the formatting, however, it does not merge cells, and each element is added to only one cell. This format can also export certain summaries as Excel functions. The summaries that are supported are SUM, AVERAGE, COUNT, MIN and MAX. Microsoft Excel Workbook Data-Only is a record based format that concentrates on data as well. This exporting format is an enhancement on the existing Microsoft Excel Workbook Data-Only exporting type. The exported result of this format is an XLSX file. XSLX file format is introduced and supported by Microsoft Excel 2007 and later. Microsoft Excel Workbook Data-Only format removes limitations of previous XLS file formats, approximately 65536 rows and 256 columns. Microsoft Excel (97-2003) Page-based format converts your report contents into Excel cells on a page-by-page basis. Contents from multiple pages are exported to the same Excel worksheet. If a worksheet becomes full and there is more data to export, the export program creates multiple worksheets to accommodate the data. If a report element covers more than one cell, the export program merges cells to represent a report element. Microsoft Excel has a limit of 256 columns in a worksheet so any report element that is added to cells beyond 256 columns is not exported. This export format retains most of the formatting, but it does not export line and box elements from your report. The Crystal Reports for Enterprise Java runtime engine does not support all of the elements embedded in a report. For example, OLAP Grids and Map elements are not supported. The character rendering technology differs between Crystal Reports for Enterprise and Crystal Reports 2013. This means that the size of each individual character can have slight differences (1 pixel) that add up over time and create additional rows or columns. XML format is primarily used for exchange of data in the report. It uses Crystal XML Schema. The XML expert in Crystal Reports can be used to customize XML output. Exporting Crystal Reports in HTML format allows an easy way to access and distribute the report data. It allows you to access your report in many of common browsers like Firefox and MS Internet Explorer. The HTML 4.0 format also saves the structure and formatting of the report by using DHTML. All of the images in your report are saved externally and a hyperlink is inserted in the exported HTML output. This export format generates more than one file in the output. Go to File → Export and select HTML 4.0 from the list. The Export Options dialog box appears. Select a Base Directory from the Base Directory text box. Click OK. The Export Destination dialog box opens. In the Export Destination dialog box, do one of the following − Click ‘To File’ and enter the report title to save the exported report in the Export Report dialog box. Click ‘To File’ and enter the report title to save the exported report in the Export Report dialog box. Click ‘To Application’ to open the report in the selected application without saving it. Click ‘To Application’ to open the report in the selected application without saving it. If you select the option Separate HTML pages check box, the entire report is divided into separate pages. The initial HTML page will be saved as <report name>.html. This is the file you open if you want to view your report through your web browser. It exports the report elements as a set of values separated by separator and delimiter characters that you specify. When a comma (,) is used to separate elements, the format is known as Comma Separated Values (CSV). This export format is popular among Microsoft Excel users. It creates one line of values for each record in your report and also contains all of the sections of your report like Page Header, Group header, Body, Group footer, Report footer and Page footer. This format cannot be used to export reports with cross-tabs. It cannot be used to export reports with subreports in Page Header or Page Footer sections. RTF format is page based format but it doesn’t preserve all structure and formatting options in the output. Microsoft Word format and Rich Text Format both produces RTF file as an output. This format is intended for use in applications, such as fill-out forms where the space for entering text is reserved as empty text objects. Almost all of the formatting is retained in this export format. The exporting file contains drawing objects and text fields to show objects in the report. The Rich Text Format (RTF) and Microsoft Word (RTF) format are same. 37 Lectures 2 hours Neha Gupta 61 Lectures 4.5 hours Sasha Miller 31 Lectures 32 mins Prof Krishna N Sharma 35 Lectures 2 hours Prof Krishna N Sharma 24 Lectures 2 hours Prof Krishna N Sharma Print Add Notes Bookmark this page
[ { "code": null, "e": 3281, "s": 2970, "text": "SAP Crystal Reports is a Business Intelligence tool which is used to generate reports from both SAP and non-SAP data sources. It enables end users to generate reports that includes exceptional visualizations and implement new business requirements into reports to reduce dependency on IT and Report developers." }, { "code": null, "e": 3651, "s": 3281, "text": "SAP Crystal Reports can connect to any data source that include Relational databases like Oracle, OLAP data source systems like BW, or also with XML data. You can create a simple report or you can also use complex or specialized tool of Crystal Reports to create advance level reports for end users. It is mostly used for pixel perfect reporting for CEO’s and Managers." }, { "code": null, "e": 3831, "s": 3651, "text": "Flexible and customized report − You can quickly create highly formatted, pixel-perfect reports using SAP Crystal Reports with high level design interface and efficient workflows." }, { "code": null, "e": 3970, "s": 3831, "text": "Powerful report delivery options − You can deliver personalized reports to your business end-users in their preferred language and format." }, { "code": null, "e": 4197, "s": 3970, "text": "Data source connectivity − You can connect to information sources directly. Data sources include: Native, ODBC, OLE DB, and JDBC connectivity to relational, OLAP, web services, XML, enterprise data sources, and salesforce.com." }, { "code": null, "e": 4377, "s": 4197, "text": "Expanded support for Excel − You can take full advantage of the Excel file format by allowing more data to be exported to a single worksheet, without spanning multiple worksheets." }, { "code": null, "e": 4502, "s": 4377, "text": "Windows operating system compatibility − SAP Crystal Reports software 2013 is certified compatible with Microsoft Windows 7." }, { "code": null, "e": 4592, "s": 4502, "text": "Mobile compatibility − You can also open interactive reports through your mobile devices." }, { "code": null, "e": 4758, "s": 4592, "text": "SAP Crystal Reports, Adobe Flash and HTML 5 integration − It enables SAP Crystal Reports developers to produce powerful \"mash-ups\" pulling data from various sources." }, { "code": null, "e": 4930, "s": 4758, "text": "Competitors − SAP Crystal Reports competes with several products in Microsoft market like SQL Server Reporting Services SSRS, XtraReports, ActiveReports, and List & Label." }, { "code": null, "e": 4996, "s": 4930, "text": "Following are the basic requirements to install Crystal Reports −" }, { "code": null, "e": 5059, "s": 4996, "text": "PC with AMD or Intel based processors, Dual Core CPU, 2 GB RAM" }, { "code": null, "e": 5122, "s": 5059, "text": "PC with AMD or Intel based processors, Dual Core CPU, 2 GB RAM" }, { "code": null, "e": 5210, "s": 5122, "text": "Approximately 4GB available hard drive space (for English only, 8 GB for all languages)" }, { "code": null, "e": 5298, "s": 5210, "text": "Approximately 4GB available hard drive space (for English only, 8 GB for all languages)" }, { "code": null, "e": 5407, "s": 5298, "text": "Microsoft Windows 7 SP1, Windows 8, Windows Server 2008 SP2, Windows Server 2008 R2 SP1, Windows Server 2012" }, { "code": null, "e": 5516, "s": 5407, "text": "Microsoft Windows 7 SP1, Windows 8, Windows Server 2008 SP2, Windows Server 2008 R2 SP1, Windows Server 2012" }, { "code": null, "e": 5777, "s": 5516, "text": "Languages available − English, Finnish, French, German, Hungarian, Italian, Japanese, Korean, Norwegian, Polish, Portuguese, Chinese simplified, Chinese traditional, Czech, Danish, Dutch, Slovakian, Slovenian, Spanish, Swedish, Thai, Turkish, Romanian, Russian" }, { "code": null, "e": 5875, "s": 5777, "text": "Hardware Requirements − Intel Pentium III or equivalent processor, minimum 512 MB RAM recommended" }, { "code": null, "e": 5973, "s": 5875, "text": "Hardware Requirements − Intel Pentium III or equivalent processor, minimum 512 MB RAM recommended" }, { "code": null, "e": 6098, "s": 5973, "text": "Disk Space − 2 GB for default installation with English language, 4 GB for default installation with all languages installed" }, { "code": null, "e": 6223, "s": 6098, "text": "Disk Space − 2 GB for default installation with English language, 4 GB for default installation with all languages installed" }, { "code": null, "e": 6617, "s": 6223, "text": "Let us take an example to decode the SAP Crystal Reports version format. Assume 12.1.2.957.12 is the version of CR 2008. Here 1 signifies that it is Service Pack 1, .2 signifies that Fix Pack 1.2 has been applied on top of Service Pack 1. The last three of four digits are not important. Another example, if you have version 12.3.1.684, I know I am using CR 2008, Service Pack 3, Fix Pack 3.1." }, { "code": null, "e": 6674, "s": 6617, "text": "Editions − Developer (D), Professional (P), Standard (S)" }, { "code": null, "e": 6731, "s": 6674, "text": "Editions − Developer (D), Professional (P), Standard (S)" }, { "code": null, "e": 6788, "s": 6731, "text": "Editions − Developer (D), Professional (P), Standard (S)" }, { "code": null, "e": 6845, "s": 6788, "text": "Editions − Developer (D), Professional (P), Standard (S)" }, { "code": null, "e": 6984, "s": 6845, "text": "Crystal Reports for enterprise provides an interface that enables you to quickly and easily create, format, and publish effective reports." }, { "code": null, "e": 7106, "s": 6984, "text": "The menu bar provides full range of features available in Crystal Reports for Enterprise as shown in the following image." }, { "code": null, "e": 7320, "s": 7106, "text": "The standard toolbar as shown in the following image allows you to access common Report functions such as − Open an existing report, create a new report, save a report, print a report, cut, paste, export and undo." }, { "code": null, "e": 7507, "s": 7320, "text": "The Insert tab allows you to insert objects into you report, such as inserting a text, line, box, groups, sections, pictures, calculations and/or charts, as shown in the following image." }, { "code": null, "e": 7730, "s": 7507, "text": "The Format tab as shown in the following image, allows you to use functions for formatting the selected field such as − changing the font size or font color, background color, alignment of text to center, left, right, etc." }, { "code": null, "e": 7867, "s": 7730, "text": "It also allows you to apply conditional formatting, such as highlighting values above or below a specific threshold value in the report." }, { "code": null, "e": 8170, "s": 7867, "text": "When you click on conditional formatting option at top right corner, the formatting box open. In this box, you define the condition under which you want conditional formatting to appear. In setting area, specify the formatting to appear when condition is met, like changing font style or color of text." }, { "code": null, "e": 8397, "s": 8170, "text": "The Data tab as shown in the following figure, enables you to work with data-editing queries, creating groups and sorts, applying filters to limit data in the report and creating formulas to add custom calculations to reports." }, { "code": null, "e": 8682, "s": 8397, "text": "When you click on Query filter option or on Edit data sources, as shown in the following image, a query panel opens. In the Query panel, you can select objects that you want to see in the report. In the filter option, you can apply filters to restrict the data returned by the report." }, { "code": null, "e": 8940, "s": 8682, "text": "When you click on Formula button, as shown in the following image, the Formula workshop opens. This allow you to use custom calculations in the report. You can apply formulas by typing or by clicking on objects, functions and operators in the data explorer." }, { "code": null, "e": 9196, "s": 8940, "text": "The main working area in Crystal Reports is known as Report Design Canvas and is divided into structure tab and page tab. Crystal Report is divided into five different parts by default and additional sections are added if you apply grouping to the report." }, { "code": null, "e": 9458, "s": 9196, "text": "Using the Structure tab, as shown in the above image, you can create the overall structure by placing items in various sections of the report. You can also apply any required sorting, grouping, etc. Here, you work with placeholders for data and not data itself." }, { "code": null, "e": 9678, "s": 9458, "text": "The Page tab, as shown in the following image, displays the report data on the basis of the structure you created in the structure tab. Here, you can evaluate formatting and layout of the report design for distribution." }, { "code": null, "e": 9892, "s": 9678, "text": "Report Options is one of the most commonly used feature in Crystal Report Designer, when you need to access/modify the values of Report Options of a Crystal report at runtime in a Crystal Reports .NET application." }, { "code": null, "e": 9920, "s": 9892, "text": "Go to Edit → Report Options" }, { "code": null, "e": 10269, "s": 9920, "text": "Report Options feature is used to set various fields in a Crystal Reports such as, smart guidelines feature that lets you select, move, and resize entire columns of report elements without needing to manually select each element. When you select a report element, the smart guidelines appear and automatically select related elements in the column." }, { "code": null, "e": 10452, "s": 10269, "text": "SAP Crystal Report gives two options of page layout - landscape and portrait. Landscape means the page is oriented horizontally, while portrait means the page is oriented vertically." }, { "code": null, "e": 10523, "s": 10452, "text": "To open Page Layout option in Crystal Report, go to File → Page Setup." }, { "code": null, "e": 10657, "s": 10523, "text": "This option allows you to choose page options like: Paper size, paper width, paper height, and margins (left, right, top and bottom)." }, { "code": null, "e": 10685, "s": 10657, "text": "To change the page layout −" }, { "code": null, "e": 10779, "s": 10685, "text": "Select the Page Setup tab in File Menu. Click the Orientation option in the Page Setup group." }, { "code": null, "e": 10930, "s": 10779, "text": "SAP Crystal Report for Enterprise help tab provides all the study material and interactive videos link from SAP site to learn Crystal Report features." }, { "code": null, "e": 11030, "s": 10930, "text": "The following options as shown in the image, are available when you click on Help tab in menu bar −" }, { "code": null, "e": 11070, "s": 11030, "text": "SAP Crystal Reports for Enterprise Help" }, { "code": null, "e": 11084, "s": 11070, "text": "Documentation" }, { "code": null, "e": 11094, "s": 11084, "text": "Tutorials" }, { "code": null, "e": 11110, "s": 11094, "text": "Show Start Page" }, { "code": null, "e": 11121, "s": 11110, "text": "Contact Us" }, { "code": null, "e": 11130, "s": 11121, "text": "Register" }, { "code": null, "e": 11170, "s": 11130, "text": "About SAP Crystal Report for Enterprise" }, { "code": null, "e": 11308, "s": 11170, "text": "This options provides you with a complete guide titled Introduction to SAP Crystal Report for Enterprise as shown in the following image." }, { "code": null, "e": 11540, "s": 11308, "text": "This covers an introduction to Crystal Reports Enterprise 4.x and all basic reporting functions available in the tool like logging on to a server, introduction to reporting, design concepts, data sources and queries, charting, etc." }, { "code": null, "e": 11656, "s": 11540, "text": "When you click on documentation option in Help tab, it takes you to SAP link for Crystal Report for Enterprise 4.x." }, { "code": null, "e": 11717, "s": 11656, "text": "This link has Crystal Report for Enterprise 4.x guides for −" }, { "code": null, "e": 11754, "s": 11717, "text": "Installation, Upgrade and Deployment" }, { "code": null, "e": 11770, "s": 11754, "text": "End Users guide" }, { "code": null, "e": 11793, "s": 11770, "text": "Additional Information" }, { "code": null, "e": 11943, "s": 11793, "text": "When you click on Tutorials link in Help tab, it takes you to the Official Product Tutorials – SAP BusinessObjects Crystal Reports for Enterprise 4.x" }, { "code": null, "e": 12070, "s": 11943, "text": "This page provides eLearning material which includes interactive sessions and video tutorials on all key features of the tool." }, { "code": null, "e": 12229, "s": 12070, "text": "It takes you to the homepage of SAP Crystal Reports Enterprise 4.1 tool. Contact Us and Register Option are used to contact SAP for any tool related features." }, { "code": null, "e": 12309, "s": 12229, "text": "It takes you to the About page of the tool that has Versions and Build details." }, { "code": null, "e": 12456, "s": 12309, "text": "SAP Crystal Report design environment provides you the area where you can design the structure of the report. It consists of multiple components −" }, { "code": null, "e": 12620, "s": 12456, "text": "The Report Design Canvas is used to design the structure of your report. You can place various elements like charts, test elements, and data objects in the report." }, { "code": null, "e": 12781, "s": 12620, "text": "Show ruler option displays a ruler above the report canvas. You can change the unit of measurement by changing the measurement unit option on design canvas tab." }, { "code": null, "e": 12958, "s": 12781, "text": "Structure mode and Page mode are available to define the layout of the report. Structure mode shows the structure of the report and Page mode is used for previewing the report." }, { "code": null, "e": 12992, "s": 12958, "text": "Edit → Preference → Design Canvas" }, { "code": null, "e": 13291, "s": 12992, "text": "Structure mode is used to provide an environment for designing the report. It provides a structure and instructions for creating the report. When you place an object in the report, it is shown in Structure mode. You can add/delete objects or apply complex formulas or you can also move the objects." }, { "code": null, "e": 13425, "s": 13291, "text": "Each object in Structure mode is represented by a frame. Structure mode has multiple components that can be used to edit the report −" }, { "code": null, "e": 13542, "s": 13425, "text": "It is used to add Report title at the top or any other information you want to place at the beginning of the report." }, { "code": null, "e": 13694, "s": 13542, "text": "This option is used to present information at the top of each page like document heading, chapter name, etc. Page header doesn’t come in Report Header." }, { "code": null, "e": 13778, "s": 13694, "text": "This is used to show the body of the report. All report data comes in this section." }, { "code": null, "e": 13857, "s": 13778, "text": "This is used to present information at the end of the report like totals, etc." }, { "code": null, "e": 13953, "s": 13857, "text": "This is used to present page numbers or any other information you want at the end of each page." }, { "code": null, "e": 14164, "s": 13953, "text": "It represents the actual data in the report when the report is published or printed. It also allows you to change the formatting of the report with actual data and changes are immediately visible in the report." }, { "code": null, "e": 14299, "s": 14164, "text": "It is used to add/delete objects in the report. When you create a new report or open an existing report, this side panel opens itself." }, { "code": null, "e": 14484, "s": 14299, "text": "All the objects that are added in the query panel are shown under data explorer and from here you can add objects to the report. This is further divided into the following components −" }, { "code": null, "e": 14731, "s": 14484, "text": "It shows all the objects that has been added to the report. You can also drag the objects to add in the report. Edit Data Sources option enables you to add new objects from the Universe or to choose a new Universe/Data Source from the repository." }, { "code": null, "e": 14882, "s": 14731, "text": "This shows all the formula that has been created for the report. You can create new formula with a right click on Formula tab and → New → New Formula." }, { "code": null, "e": 14924, "s": 14882, "text": "You can also drag formulas to the report." }, { "code": null, "e": 15080, "s": 14924, "text": "It shows all the parameters that has been created for the report. You can create new parameter group with a right click on Parameter → New → New Parameter." }, { "code": null, "e": 15237, "s": 15080, "text": "It shows a list of all running totals that has been created for the report. You can create new running totals with a right click on tab → New Running Total." }, { "code": null, "e": 15376, "s": 15237, "text": "It shows the predefined objects that can be added to a report. You can drag predefined objects to report canvas to add them to the report." }, { "code": null, "e": 15599, "s": 15376, "text": "It is used to see the tree structure of the report. The first node in tree structure represents the report itself, the first level node represents the sections in the report, and each section containing objects are listed." }, { "code": null, "e": 15670, "s": 15599, "text": "It is used to see tree view of all groups and subgroups in the report." }, { "code": null, "e": 15772, "s": 15670, "text": "It is used to search a specific value in the report. Type a word in the search box to find any value." }, { "code": null, "e": 15840, "s": 15772, "text": "Crystal Report can connect to multiple data sources that includes −" }, { "code": null, "e": 15849, "s": 15840, "text": "Universe" }, { "code": null, "e": 15863, "s": 15849, "text": "SAP BEx Query" }, { "code": null, "e": 15885, "s": 15863, "text": "Relational Connection" }, { "code": null, "e": 15895, "s": 15885, "text": "HANA view" }, { "code": null, "e": 15914, "s": 15895, "text": "Excel Spreadsheets" }, { "code": null, "e": 15979, "s": 15914, "text": "To connect to a Data source, go to File → New → From Data Source" }, { "code": null, "e": 16066, "s": 15979, "text": "To select a data source you must be connected to SAP Business Objects platform server." }, { "code": null, "e": 16259, "s": 16066, "text": "When you go to File → New → From Data Source → Choose a data source connection dialogue box appears → Browse Repository → Data Source Type list → Select data source you want to connect → Next." }, { "code": null, "e": 16367, "s": 16259, "text": "If you choose a Universe, a query panel opens and you can add objects to query filter to generate a report." }, { "code": null, "e": 16469, "s": 16367, "text": "SAP BEx and Universe data source connections allow you to create and design query in Crystal Reports." }, { "code": null, "e": 16553, "s": 16469, "text": "To create a query in Universe you can choose both OLAP and Relational data sources." }, { "code": null, "e": 16752, "s": 16553, "text": "First step in a query design is to define objects that you want to add in your query. You can also refine your query by applying sorts and query filters. Query panel is divided into multiple panes −" }, { "code": null, "e": 16881, "s": 16752, "text": "It contains a tree structure of all the objects in Universe. You can see all the objects in Universe by using Expand All option." }, { "code": null, "e": 16949, "s": 16881, "text": "You cannot add new objects or edit existing objects in query panel." }, { "code": null, "e": 17008, "s": 16949, "text": "In this area, you add objects that you want in your query." }, { "code": null, "e": 17146, "s": 17008, "text": "This is used to filter the value of objects in the report. You can use predefined filters or can create custom filters by adding objects." }, { "code": null, "e": 17239, "s": 17146, "text": "SAP BEx queries can contain one or more hierarchies and predefine objects to run the report." }, { "code": null, "e": 17512, "s": 17239, "text": "SAP HANA queries include data from SAP HANA Modeling views: Analytic, Calculation Views. To connect to HANA database and to use Schemas → tables inside the database, you can use an existing Relational or OLAP connection. A Relational connection can be created in IDT tool." }, { "code": null, "e": 17683, "s": 17512, "text": "An OLAP connection can be created in CMC as well as in Information Design tool. HANA multi-dimensional views can be connected to Crystal Reports using an OLAP connection." }, { "code": null, "e": 17800, "s": 17683, "text": "Click on Next → It will show you list of all Modeling views inside HANA repository → Select a Modeling View → Finish" }, { "code": null, "e": 17892, "s": 17800, "text": "It will open objects of view in a query panel, which can be used to add them to the report." }, { "code": null, "e": 18129, "s": 17892, "text": "Once the Crystal Report is created using a query, to make changes to objects you have to go to edit data source option. When you click on the option, it will open an Edit Query panel where you can add/delete objects, apply filters, etc." }, { "code": null, "e": 18235, "s": 18129, "text": "You can also edit an existing query by going to Data → Edit Data Sources as shown in the following image." }, { "code": null, "e": 18346, "s": 18235, "text": "Once you are done with the changes, click on Finish and all changes will be applied to data in Crystal Report." }, { "code": null, "e": 18425, "s": 18346, "text": "Following are the types of query filters that can be used in Crystal Reports −" }, { "code": null, "e": 18444, "s": 18425, "text": "Predefined filters" }, { "code": null, "e": 18459, "s": 18444, "text": "Custom Filters" }, { "code": null, "e": 18474, "s": 18459, "text": "Custom Filters" }, { "code": null, "e": 18835, "s": 18474, "text": "These are inbuilt filters in query panel created by the administrator. Predefined filters are created at the Universe level and are directly used in the report from the Universe. Drag an object on which you want to apply filter to query filter pane and drag predefined filters too. When you run the query data w.r.t query filter will be returned in the report." }, { "code": null, "e": 19157, "s": 18835, "text": "These filters are created with the queries in the query panel. Custom filters are created in the Query panel under the query filter tab. Drag the object to the query filter pane and make use of various relational operator to pass the filter condition. You can put a constant value or a list of values in the query filter." }, { "code": null, "e": 19245, "s": 19157, "text": "They are used to display a question or list of values and are known as dynamic filters." }, { "code": null, "e": 19307, "s": 19245, "text": "Constant option allows you to enter a single value in filter." }, { "code": null, "e": 19397, "s": 19307, "text": "List of values allow you to choose one value from all the available values for an object." }, { "code": null, "e": 19453, "s": 19397, "text": "Prompt is used to pass dynamic value to a query filter." }, { "code": null, "e": 19484, "s": 19453, "text": "Type a value into the text box" }, { "code": null, "e": 19515, "s": 19484, "text": "Type a value into the text box" }, { "code": null, "e": 19672, "s": 19515, "text": "In the Prompt(s) dialog box, add members to your list by double-clicking them, or by selecting them in the Members pane and clicking the arrow in the center" }, { "code": null, "e": 19829, "s": 19672, "text": "In the Prompt(s) dialog box, add members to your list by double-clicking them, or by selecting them in the Members pane and clicking the arrow in the center" }, { "code": null, "e": 19838, "s": 19829, "text": "Click ok" }, { "code": null, "e": 19847, "s": 19838, "text": "Click ok" }, { "code": null, "e": 19985, "s": 19847, "text": "In the Edit Prompt dialog box, select New Prompt to add a new prompt, or Use Universe Parameters to select a parameter from your universe" }, { "code": null, "e": 20123, "s": 19985, "text": "In the Edit Prompt dialog box, select New Prompt to add a new prompt, or Use Universe Parameters to select a parameter from your universe" }, { "code": null, "e": 20238, "s": 20123, "text": "If you selected a New Prompt, enter prompt options, or if you selected Use Universe Parameters, select a parameter" }, { "code": null, "e": 20353, "s": 20238, "text": "If you selected a New Prompt, enter prompt options, or if you selected Use Universe Parameters, select a parameter" }, { "code": null, "e": 20362, "s": 20353, "text": "Click ok" }, { "code": null, "e": 20371, "s": 20362, "text": "Click ok" }, { "code": null, "e": 20617, "s": 20371, "text": "Time based query filters are used to filter the value of specific objects between certain periods of time. When you add a date dimension to query filter, you can use between operators from drop down list to specifically mention to and from date." }, { "code": null, "e": 20894, "s": 20617, "text": "You can click on calendar option to select dates in ‘to’ and ‘from’ fields. You can also use Date dimension with the list of values (LOVs) or Constant value option. LOVs allow you to select to and from date from the list of values available for Date dimension in the Universe." }, { "code": null, "e": 20954, "s": 20894, "text": "This is known as applying Time based filters in the report." }, { "code": null, "e": 21189, "s": 20954, "text": "Field objects controls are used to edit the object in the report. To edit the object, you can right click on the object name and select ‘Format result Object Element’ or ‘Conditional Formatting’ option as shown in the following image." }, { "code": null, "e": 21324, "s": 21189, "text": "Format Result Object Element field is used to change the appearance of the objects in the report. It has the following 4 tabs inside −" }, { "code": null, "e": 21332, "s": 21324, "text": "General" }, { "code": null, "e": 21337, "s": 21332, "text": "Font" }, { "code": null, "e": 21348, "s": 21337, "text": "Appearance" }, { "code": null, "e": 21358, "s": 21348, "text": "Paragraph" }, { "code": null, "e": 21547, "s": 21358, "text": "General tab is used to define generic properties of report objects: like height and width, hide and hide if duplicate, etc. Advanced tab in General is used to pass hyperlink in the report." }, { "code": null, "e": 21652, "s": 21547, "text": "Font tab is used to change font size, color, style, alignment and rotation of object name in the report." }, { "code": null, "e": 21738, "s": 21652, "text": "Appearance tab is used to change the border and to add effects to the report objects." }, { "code": null, "e": 21827, "s": 21738, "text": "Paragraph tab is used to define line properties in case of multiple lines in the report." }, { "code": null, "e": 21911, "s": 21827, "text": "Conditional formatting is used to pass conditions for appearance of report objects." }, { "code": null, "e": 22065, "s": 21911, "text": "You can pass the value of an object by clicking on Add condition tab → select object name and pass condition. You can define font style, font color, etc." }, { "code": null, "e": 22144, "s": 22065, "text": "As discussed earlier, Crystal Reports by default provides five main sections −" }, { "code": null, "e": 22158, "s": 22144, "text": "Report Header" }, { "code": null, "e": 22170, "s": 22158, "text": "Page Header" }, { "code": null, "e": 22175, "s": 22170, "text": "Body" }, { "code": null, "e": 22189, "s": 22175, "text": "Report Footer" }, { "code": null, "e": 22201, "s": 22189, "text": "Page Footer" }, { "code": null, "e": 22300, "s": 22201, "text": "Here, we will learn how to insert, hide, and delete sections in Crystal Report for Enterprise 4.x." }, { "code": null, "e": 22395, "s": 22300, "text": "To insert a section in any of the report section, select the section → Right click and Insert." }, { "code": null, "e": 22482, "s": 22395, "text": "You can use Hide and move option to hide a section or to move the section up and down." }, { "code": null, "e": 22563, "s": 22482, "text": "Format Section option allows you to format the section properties. It includes −" }, { "code": null, "e": 22568, "s": 22563, "text": "Name" }, { "code": null, "e": 22574, "s": 22568, "text": "Color" }, { "code": null, "e": 22579, "s": 22574, "text": "Size" }, { "code": null, "e": 22639, "s": 22579, "text": "Size option allows you to adjust the height of the section." }, { "code": null, "e": 22686, "s": 22639, "text": "To keep a section from breaking across pages −" }, { "code": null, "e": 22803, "s": 22686, "text": "If an element is longer than one page then it prints across multiple pages. To avoid this you can use Paging option." }, { "code": null, "e": 22902, "s": 22803, "text": "Right click a section and click format section → Paging → Select Avoid Page Break and click Close." }, { "code": null, "e": 22981, "s": 22902, "text": "Now let us see how to insert, hide and delete sections in Crystal Report 2013." }, { "code": null, "e": 23070, "s": 22981, "text": "Section Expert as shown in the following image is used to manage sections in the report." }, { "code": null, "e": 23108, "s": 23070, "text": "To insert a new section you need to −" }, { "code": null, "e": 23270, "s": 23108, "text": "Click Section Expert button as shown in the following image (Section Expert contains a list of all the sections in the report) → Select section and click insert." }, { "code": null, "e": 23311, "s": 23270, "text": "A new section will appear in the report." }, { "code": null, "e": 23400, "s": 23311, "text": "Open Section expert at the top and select the section you want to delete → enter Delete." }, { "code": null, "e": 23521, "s": 23400, "text": "You can only delete the section if they are lettered. You cannot delete sections originally provided by Crystal Reports." }, { "code": null, "e": 23638, "s": 23521, "text": "Open Section Expert →Select section you want to move and use up and down arrows to change the order of the sections." }, { "code": null, "e": 23748, "s": 23638, "text": "Open Section Expert → Move sections you want to merge with each other → select the top section → Click merge." }, { "code": null, "e": 23815, "s": 23748, "text": "Sections will be merged with the section that is next on the list." }, { "code": null, "e": 23986, "s": 23815, "text": "Click on the boundary of the section you want to split → Horizontal line that splits section will appear → Drag-and-drop to the place where you want to split the section." }, { "code": null, "e": 24255, "s": 23986, "text": "Sometimes you are required to sort data in Crystal Reports in a certain order. When you sort the data, it is easier to find specific records in the report. You can add a sort in ascending or descending order and it can also be applied to attributes and measures value." }, { "code": null, "e": 24320, "s": 24255, "text": "You can also remove the sorting using delete option in Sort tab." }, { "code": null, "e": 24369, "s": 24320, "text": "Let us see how to apply sort in Crystal Reports." }, { "code": null, "e": 24501, "s": 24369, "text": "To apply a sort in Crystal Report for enterprise 4.x, go to Structure tab of the report → click on Data tab at top and choose sort." }, { "code": null, "e": 24584, "s": 24501, "text": "When you click on sort option, it will pop-up a window with group and sort option." }, { "code": null, "e": 24688, "s": 24584, "text": "Go to Sort tab and expand the body tab to apply sorting on measures and attribute values in the report." }, { "code": null, "e": 24898, "s": 24688, "text": "To add a sort, click on Add sort option. It will show you all the attributes and measures added to the report. Choose the object on which you want to apply sorting and click on ascending and descending option." }, { "code": null, "e": 24934, "s": 24898, "text": "A → Z Ascending or Z → A Descending" }, { "code": null, "e": 25001, "s": 24934, "text": "You can also add multiple sort in a single report and click on OK." }, { "code": null, "e": 25037, "s": 25001, "text": "To view sorted data go to Page tab." }, { "code": null, "e": 25125, "s": 25037, "text": "In the above example, it has applied a sorting on customer name and then Quantity sold." }, { "code": null, "e": 25192, "s": 25125, "text": "To delete a sort, select the sort and click on delete sort option." }, { "code": null, "e": 25264, "s": 25192, "text": "In this chapter, we will cover how to define, render and delete groups." }, { "code": null, "e": 25379, "s": 25264, "text": "When you need to separate the data into groups in order to make it easily understood, grouping option can be used." }, { "code": null, "e": 25504, "s": 25379, "text": "You can also customize grouping for a single value or multiple values by using the customize option inside the grouping tab." }, { "code": null, "e": 25587, "s": 25504, "text": "To apply grouping in the report, go to structure tab of the report → Data → Groups" }, { "code": null, "e": 25797, "s": 25587, "text": "To add a grouping condition. Click on New (‘+’ sign) and select the attribute on which you want to apply grouping. If you apply regular grouping on one object, it will group all the similar values in a report." }, { "code": null, "e": 25971, "s": 25797, "text": "To apply grouping on single value, go to customize grouping option → New → Add Condition → select operator and value from the dropdown list as shown in the following image −" }, { "code": null, "e": 26137, "s": 25971, "text": "It also gives an option to discard everything else, group everything else in single group with group name or include everything else without changing the group name." }, { "code": null, "e": 26287, "s": 26137, "text": "In the following example, it has created 2 groups: first with Region Name=”New Delhi” and second group with everything else with group name “Others”." }, { "code": null, "e": 26404, "s": 26287, "text": "When you use grouping in a report, two new sections appear in the report canvas − Group Header 1 and Group Footer 1." }, { "code": null, "e": 26491, "s": 26404, "text": "To delete a group, select the group you want to remove and click on the Delete option." }, { "code": null, "e": 26581, "s": 26491, "text": "Go to Structure of the report → Groups → select groups #1, 2 you want to delete → Delete." }, { "code": null, "e": 26664, "s": 26581, "text": "You can use the following 3 options while customizing a group in Crystal Reports −" }, { "code": null, "e": 26688, "s": 26664, "text": "Discard everything else" }, { "code": null, "e": 26712, "s": 26688, "text": "Discard everything else" }, { "code": null, "e": 26770, "s": 26712, "text": "Group everything else in a single group with a group name" }, { "code": null, "e": 26828, "s": 26770, "text": "Group everything else in a single group with a group name" }, { "code": null, "e": 26884, "s": 26828, "text": "Include everything else without changing the group name" }, { "code": null, "e": 26940, "s": 26884, "text": "Include everything else without changing the group name" }, { "code": null, "e": 27176, "s": 26940, "text": "When you are in Page tab, the group tree icon in side panel is used to see tree view of groups in the report. It allows you to jump to a specific group in the report instead of scrolling through the report looking for a specific group." }, { "code": null, "e": 27402, "s": 27176, "text": "Live header changes based on the content of the group. When you define a group in the report, the program automatically inserts a group name in the element, in the group header section. This element displays the group’s name." }, { "code": null, "e": 27617, "s": 27402, "text": "The grouping of data in the report is done to find the total for each group in the report. Many totaling options are available − Sum, count, maximum, minimum, average, etc. You can also add subtotal to your report." }, { "code": null, "e": 27695, "s": 27617, "text": "Total option in the report − Go to insert tab → Select options for your total" }, { "code": null, "e": 27777, "s": 27695, "text": "To change the format of the total box, right click on total value → format total." }, { "code": null, "e": 28008, "s": 27777, "text": "Instead of creating a report from scratch, you can also use inbuilt templates from the report repository. These report templates provide predefined layout for common documents like purchase orders, invoices, letter templates, etc." }, { "code": null, "e": 28094, "s": 28008, "text": "To select a Report template from the repository, go to File → New → From Web template" }, { "code": null, "e": 28146, "s": 28094, "text": "There are two template options in Crystal Reports −" }, { "code": null, "e": 28165, "s": 28146, "text": "Featured Templates" }, { "code": null, "e": 28179, "s": 28165, "text": "Recently Used" }, { "code": null, "e": 28309, "s": 28179, "text": "You can also perform a search using the search tool. Once you choose a report template you will be asked to select a data source." }, { "code": null, "e": 28538, "s": 28309, "text": "Select Preview (To preview the report template before selecting data source)→ Set Data Source location to select a data source → Target Data Source panel, Add Connection icon → Choose a Data Source Connection dialog box appears." }, { "code": null, "e": 28609, "s": 28538, "text": "Select your data source connection from one of the following options −" }, { "code": null, "e": 28692, "s": 28609, "text": "Previous Connections − This option lets you use previously connected data sources." }, { "code": null, "e": 28790, "s": 28692, "text": "Browse Repository − This option lets you choose your data source from the Data Source Type list." }, { "code": null, "e": 28892, "s": 28790, "text": "Connection by Vendor − This option connects to data sources sorted by a vendor or software provider." }, { "code": null, "e": 28906, "s": 28892, "text": "Click Finish." }, { "code": null, "e": 29050, "s": 28906, "text": "Select an object from the Current Data Source panel and connect it to an object in the Target Data Source panel → click on map → click on done." }, { "code": null, "e": 29208, "s": 29050, "text": "Insert options in Crystal Reports for Enterprise allows you to add multiple objects at the report level: charts, crosstabs, picture, flash, sub-reports, etc." }, { "code": null, "e": 29346, "s": 29208, "text": "You can add multiple format pictures in the report. It can also be used if you want to add company logos, brand name, etc. in the report." }, { "code": null, "e": 29499, "s": 29346, "text": "When you click on Picture, it gives an option to insert a picture in the report. The following common picture formats are supported in Crystal Reports −" }, { "code": null, "e": 29504, "s": 29499, "text": "jpeg" }, { "code": null, "e": 29508, "s": 29504, "text": "png" }, { "code": null, "e": 29512, "s": 29508, "text": "gif" }, { "code": null, "e": 29517, "s": 29512, "text": "tiff" }, { "code": null, "e": 29789, "s": 29517, "text": "It also allows you to insert flash files in the report. When you click on flash, you can choose the file path or directly embed the link of the flash file to add in the report. It supports .swf file types in the flash file so you can add dynamic dashboards in the report." }, { "code": null, "e": 29875, "s": 29789, "text": "In this chapter, we will learn about types of charts, creating and formatting charts." }, { "code": null, "e": 30051, "s": 29875, "text": "You can use below chart types in Crystal Reports for enterprise. To insert a chart, go to Insert → Chart → select Chart type and insert the chart in the structure or page tab." }, { "code": null, "e": 30245, "s": 30051, "text": "You can insert a chart in Report footer. When you select the chart type from Insert chart option, you can move the cursor to the report footer area and click where you want to insert the chart." }, { "code": null, "e": 30317, "s": 30245, "text": "When you insert a chart it gives you two options − Data and Show chart." }, { "code": null, "e": 30426, "s": 30317, "text": "Show chart option allows you to resize the chart, move the chart in the Report footer area (as shown above)." }, { "code": null, "e": 30547, "s": 30426, "text": "Data tab allows you to insert the data in the chart. When you go to data tab, it asks you to add values on X, Y, Z axis." }, { "code": null, "e": 30731, "s": 30547, "text": "Right click on each axis and go to Insert Chart Category Object → you can choose Selected Elements from the dropdown list → Chart Data Object, Title, Subtitle, foot note, legend, etc." }, { "code": null, "e": 30909, "s": 30731, "text": "Chart Data object allows you to choose the attribute name, which you want to pass in the chart data. Title, subtitle and footnote allows you to add heading or note to the chart." }, { "code": null, "e": 30987, "s": 30909, "text": "When you right click on chart it gives you the following formatting options −" }, { "code": null, "e": 31216, "s": 30987, "text": "Format Chart − Allows you to format structure of the chart by going into advance, appearance and depth option. You can also change the type of chart from the dropdown list by clicking on the Chart option in the Format chart tab." }, { "code": null, "e": 31363, "s": 31216, "text": "Chart Highlighting Expert allows you to highlight a specific value in the chart. You can choose different color to highlight a value inside chart." }, { "code": null, "e": 31470, "s": 31363, "text": "Add Condition → Choose attribute which you want to highlight in the chart as shown in the following image." }, { "code": null, "e": 31549, "s": 31470, "text": "Edit Chart Type is same as format chart with all of the options being similar." }, { "code": null, "e": 31816, "s": 31549, "text": "Edit Chart data is used to edit the data in the chart. If you want to change the parameter values on the chart axis, you can click on edit chart data and change the values. Hide option is used to hide the chart and move is used to move the chart backward or forward." }, { "code": null, "e": 32162, "s": 31816, "text": "You can add multiple charts in a single report or in one row by formatting the chart size. Example - You can add bar chart and pie chart for different values to represent. You will see Show chart and Data option for the second chart → you can add required objects and also add header and footer note to the chart as shown in the following image." }, { "code": null, "e": 32204, "s": 32162, "text": "To see the actual report, go to Page tab." }, { "code": null, "e": 32539, "s": 32204, "text": "Cross tab is used to display the data that is grouped or totaled in two directions. It shows data in a compact format, which makes it easier to understand and see the trend in the data. For example, if you want to see the quantity sold by the customer in a particular region, without cross tab, it shows the data in a spread-out form." }, { "code": null, "e": 32663, "s": 32539, "text": "You can add multiple number of attributes in rows and columns by clicking on ‘+’ sign. To delete an object click on X sign." }, { "code": null, "e": 32809, "s": 32663, "text": "When you click on Insert, cross tab adds to the Structure of the report. If you click on the page tab, it will show Cross tab data in the report." }, { "code": null, "e": 32942, "s": 32809, "text": "You can also edit the cells in cross tab. To edit Cross tab properties, right click on Cross tab and you can change the properties −" }, { "code": null, "e": 32959, "s": 32942, "text": "Format Cross tab" }, { "code": null, "e": 32974, "s": 32959, "text": "Edit Cross tab" }, { "code": null, "e": 32979, "s": 32974, "text": "Sort" }, { "code": null, "e": 32984, "s": 32979, "text": "Hide" }, { "code": null, "e": 32997, "s": 32984, "text": "Grid Options" }, { "code": null, "e": 33003, "s": 32997, "text": "Pivot" }, { "code": null, "e": 33031, "s": 33003, "text": "Create chart from cross tab" }, { "code": null, "e": 33202, "s": 33031, "text": "A Crosstab includes row totals, column totals and grand totals. To see values as percentage, right click on Total cell and go to Format Total → select show as percentage." }, { "code": null, "e": 33364, "s": 33202, "text": "Grid options allow you to do formatting of cross tab rows like hiding empty rows, repeat row labels, hide row grand totals, etc. as shown in the following image." }, { "code": null, "e": 33568, "s": 33364, "text": "Formulas are used to insert data in the report that does not exist with any of the objects. If there is a need to perform some calculations or to add specialized data in the report, you can use formulas." }, { "code": null, "e": 33601, "s": 33568, "text": "Example − (Emp_details.sal)*0.15" }, { "code": null, "e": 33691, "s": 33601, "text": "Common formulas are − Calculations, string functions like UPPERCASE, date functions, etc." }, { "code": null, "e": 33734, "s": 33691, "text": "Formula contains two parts in the report −" }, { "code": null, "e": 33741, "s": 33734, "text": "Syntax" }, { "code": null, "e": 33752, "s": 33741, "text": "Components" }, { "code": null, "e": 33796, "s": 33752, "text": "The components are used to create formulas." }, { "code": null, "e": 33903, "s": 33796, "text": "Crystal Reports has the following types of formulas − Report formulas and conditional formatting\nformulas." }, { "code": null, "e": 34046, "s": 33903, "text": "Report formulas are used as standalone in a report. Conditional formatting formulas define the condition on which report formulas are applied." }, { "code": null, "e": 34219, "s": 34046, "text": "Formula workshop is used to create different kinds of formulas. You can open formula workshop by going to Data → click formulas or by clicking formula tab on Data tool bar." }, { "code": null, "e": 34300, "s": 34219, "text": "In the formula workshop there are 2 panels − Navigation Panel and Objects Panel." }, { "code": null, "e": 34381, "s": 34300, "text": "Navigation panel contains a folder for each type of formulas in Crystal Reports." }, { "code": null, "e": 34415, "s": 34381, "text": "Object Panels contains 4 fields −" }, { "code": null, "e": 34530, "s": 34415, "text": "Data Explorer − It contains in-use Objects, formulas, parameters and running totals present in the Crystal Report." }, { "code": null, "e": 34610, "s": 34530, "text": "Result Objects − It contains all result objects available to use in the report." }, { "code": null, "e": 34784, "s": 34610, "text": "Functions − It contains all inbuilt functions that can be used in the report. It also includes custom functions. Example − Sum, Count, String functions, Date functions, etc." }, { "code": null, "e": 34912, "s": 34784, "text": "Operators − They are used to pass conditions between values. It includes: arithmetic operators, Arrays, Boolean operators, etc." }, { "code": null, "e": 35132, "s": 34912, "text": "Formula workshop also contains formula text window and formula workshop buttons. Text windows is used to create or modify formulas and workshop panel button allows you to use filter formulas, sort formulas, delete, etc." }, { "code": null, "e": 35314, "s": 35132, "text": "You can create single or multiple formulas in one go and use them in your report. You can also delete the formulas, or search and change text of formulas in the formula text window." }, { "code": null, "e": 35487, "s": 35314, "text": "To create a new formula, you can right click on Formula tab under Data Explorer. Once you click on the new formula → enter the formula name → it opens the formula workshop." }, { "code": null, "e": 35638, "s": 35487, "text": "You can also create a new formula by opening the Formula workshop from the Formula tab under Data → New → New Formula as shown in the following image." }, { "code": null, "e": 35793, "s": 35638, "text": "To write a formula in the formula text window, you can use in-use objects under the Operator tab and different operators to pass condition in the formula." }, { "code": null, "e": 35947, "s": 35793, "text": "formula can be saved using the save option at the bottom of the page. Once the formula is saved it comes under the list of formulas in Data Explorer tab." }, { "code": null, "e": 36003, "s": 35947, "text": "You can drag this formula to any section of the report." }, { "code": null, "e": 36142, "s": 36003, "text": "In the above snapshot, Test formula has been dragged to Report footer and it has calculated value as Quantity sold/2 in the Report footer." }, { "code": null, "e": 36395, "s": 36142, "text": "Now to modify the formula,click on formula name under Data explorer, it will open the Formula workshop. Make changes to formula and use the save button at the bottom to save the changes. These changes will be automatically applied to the Report values." }, { "code": null, "e": 36485, "s": 36395, "text": "To delete the formula from a report, right click on the formula name and click on Delete." }, { "code": null, "e": 36710, "s": 36485, "text": "Problem pane at bottom is used for debugging purpose. It shows you the syntax error in the formula. The error message in the following image says that the field in red underline is not known as field syntax and is incorrect." }, { "code": null, "e": 36807, "s": 36710, "text": "There are different Boolean operators that can be used in formula in Crystal Reports. They are −" }, { "code": null, "e": 36811, "s": 36807, "text": "AND" }, { "code": null, "e": 36814, "s": 36811, "text": "OR" }, { "code": null, "e": 36818, "s": 36814, "text": "NOT" }, { "code": null, "e": 36822, "s": 36818, "text": "Eqv" }, { "code": null, "e": 36826, "s": 36822, "text": "Imp" }, { "code": null, "e": 36830, "s": 36826, "text": "XOR" }, { "code": null, "e": 36901, "s": 36830, "text": "All these operators are used to pass multiple conditions in formulas −" }, { "code": null, "e": 37064, "s": 36901, "text": "AND operator is used when you want both the conditions in the formula to be true. Other Boolean operators and their meaning is as mentioned in the above snapshot." }, { "code": null, "e": 37096, "s": 37064, "text": "Using Boolean Operators ‘AND’ −" }, { "code": null, "e": 37210, "s": 37096, "text": "If {CUSTOMER.CUSTOMER_NAME} [1 to 2] = \"AN\" and\nToText({CUSTOMER.CUSTOMER ID}) [2] = \"4\" then\n\"TRUE\"\nElse\n\"FALSE\"" }, { "code": null, "e": 37251, "s": 37210, "text": "Using Boolean Operators ‘AND’ and ‘OR’ −" }, { "code": null, "e": 37496, "s": 37251, "text": "If ({CUSTOMER.CUSTOMER_NAME} [1 to 2] = \"AN\" and\nToText({CUSTOMER.CUSTOMER ID}) [1] = \"4\") or\n({CUSTOMER.CUSTOMER_NAME} [1 to 2] = \"Ja\" and\nToText({CUSTOMER.CUSTOMER ID}) [1] = \"2\") then\n\"Five star rating CUSTOMER\"\nElse\n\"1 star rating CUSTOMER\"" }, { "code": null, "e": 37679, "s": 37496, "text": "The if-then-Else statement is the most basic of all the control flow statements. It tells your program to execute a certain section of code only if a particular condition meets true." }, { "code": null, "e": 37864, "s": 37679, "text": "If you see the following If-Then-Else statement with Boolean operators, it has allowed you to pass multiple conditions in the formula and returning the value, if the condition is true." }, { "code": null, "e": 38118, "s": 37864, "text": "If({PROJECT.Customer\\Customer Name} [1 to 2] = \"An\" and\nToText({PROJECT.Time\\Year}) [1] = \"2\") or\n({Project.Customer\\CUSTOMER NAME} [1 to 2] = \"Ja\" and\nToText({PROJECT.Time\\Year}) [1] = \"2\") Then\n\"Five star rating CUSTOMER\"\nElse\n\"1 star rating CUSTOMER\"" }, { "code": null, "e": 38302, "s": 38118, "text": "This statement says that when any of the condition is true (before and after OR operator), then it will print Five star rating customer otherwise it will print 1 star rating customer." }, { "code": null, "e": 38430, "s": 38302, "text": "This formula has been saved and then added to the body of the report under the structure tab as shown in the following images −" }, { "code": null, "e": 38539, "s": 38430, "text": "A new column in the report has been added with the rating of the customers as mentioned in the TEST formula." }, { "code": null, "e": 38674, "s": 38539, "text": "Calculated formulas are used to perform mathematical calculations in Crystal Reports and they can be designed in the formula workshop." }, { "code": null, "e": 38850, "s": 38674, "text": "Arithmetic operators are used to design calculation formulas in workshop. There are different Arithmetic operators that can be used to Add, Divide, Exponential, Multiply, etc." }, { "code": null, "e": 39143, "s": 38850, "text": "To apply a calculation in the formula, drag the object from the objects pane to the formula text pane and use operators to perform the required calculation. Once you have saved the formula using the save option at the bottom, this formula will be saved under the Formula tab in Data explorer." }, { "code": null, "e": 39254, "s": 39143, "text": "You can then drag the formula to Report structure and go to Page tab to see the calculated data in the report." }, { "code": null, "e": 39323, "s": 39254, "text": "List of Arithmetic operators from highest to lowest precedence are −" }, { "code": null, "e": 39338, "s": 39323, "text": "Exponentiation" }, { "code": null, "e": 39347, "s": 39338, "text": "Negation" }, { "code": null, "e": 39379, "s": 39347, "text": "Multiply, Divide and percentage" }, { "code": null, "e": 39396, "s": 39379, "text": "Integer division" }, { "code": null, "e": 39400, "s": 39396, "text": "Mod" }, { "code": null, "e": 39425, "s": 39400, "text": "Addition and Subtraction" }, { "code": null, "e": 39642, "s": 39425, "text": "To write a conditional formatting formula, right-click the report and click Format Result Object element → select the property on which you want to apply conditional formula → click and it will open formula workshop." }, { "code": null, "e": 39705, "s": 39642, "text": "Write the formula in the formula text pane, save and close it." }, { "code": null, "e": 39843, "s": 39705, "text": "In this example, if you can print Total Price greater than 60000 in Green and below 60000 in Red, this can be passed in formula workshop." }, { "code": null, "e": 39951, "s": 39843, "text": "In this example, crGreen, crRed, crBlack is used. You can also use actual numeric value of color constants." }, { "code": null, "e": 40009, "s": 39951, "text": "There are three common conditional formatting functions −" }, { "code": null, "e": 40028, "s": 40009, "text": "CurrentObjectValue" }, { "code": null, "e": 40045, "s": 40028, "text": "DefaultAttribute" }, { "code": null, "e": 40064, "s": 40045, "text": "GridRowColumnValue" }, { "code": null, "e": 40328, "s": 40064, "text": "DefaultAttribute can be used for any formatting formula, CurrentObjectValue for any formatting formula where you are formatting an object value, and GridRowColumnValue can be used for any formatting formula where you are formatting an object value in a Cross-Tab." }, { "code": null, "e": 40585, "s": 40328, "text": "A Variable is used to assign different values to an object unlike constant which is fixed. When you assign a value to a variable, it maintains that value till you assign a new value to it. Before using variables, it is necessary to define them in a report." }, { "code": null, "e": 40967, "s": 40585, "text": "When you declare a variable in Crystal Report you need to assign a name to it, however this name shouldn’t be the same as any other function, operator, etc. A variable can be a number type, string type, date type, Boolean type, range type or an array type. A variable can hold a value of single type, like if you declare it as a number it can’t be used to hold string values later." }, { "code": null, "e": 41035, "s": 40967, "text": "Local Stringvar Customer_Lastname\nLocal numbervar Sales_percentage\n" }, { "code": null, "e": 41225, "s": 41035, "text": "The keyword for declaring the variable has ‘var’ at the end and it is true for all variable types. You can also assign an initial value to a variable with declaration or in separate syntax." }, { "code": null, "e": 41330, "s": 41225, "text": "Local NumberVar Z; //Declare Z to be a Number variable\nZ := 30; //Assign the value of 30 to Z\n" }, { "code": null, "e": 41421, "s": 41330, "text": "To use Variables in formulas, its scope is defined. Variable scope can be of three types −" }, { "code": null, "e": 41427, "s": 41421, "text": "Local" }, { "code": null, "e": 41434, "s": 41427, "text": "Global" }, { "code": null, "e": 41441, "s": 41434, "text": "Shared" }, { "code": null, "e": 41515, "s": 41441, "text": "This defines that a variable in one formula can be used in other formula." }, { "code": null, "e": 41649, "s": 41515, "text": "Local variables are declared using the local keyword followed by the type and followed by the variable name as in the above examples." }, { "code": null, "e": 41806, "s": 41649, "text": "Local variables are restricted to a single formula. This means that you cannot access the value of a local variable in one formula from a different formula." }, { "code": null, "e": 41919, "s": 41806, "text": "//Formula 1\nLocal NumberVar Z;\nZ := 30;\n\n//Formula 2\nEvaluateAfter ({@Formula A})\nLocal NumberVar Z;\nZ := z + 5;" }, { "code": null, "e": 42087, "s": 41919, "text": "In the above example, Formula 2 will return a value 5 as Z is declared as local number variable in formula 1 so it will take default value for variable Z in formula 2." }, { "code": null, "e": 42242, "s": 42087, "text": "Global variables are used throughout the main report. Their value is available to all formulas that declare the variable, except for those in sub reports." }, { "code": null, "e": 42263, "s": 42242, "text": "Global StringVar Z;\n" }, { "code": null, "e": 42352, "s": 42263, "text": "It is recommended that you use global variable only when local variables do not suffice." }, { "code": null, "e": 42588, "s": 42352, "text": "Since global variables share their values throughout the main report, you cannot declare a global variable in one formula with one type and then declare a global variable with the same name in a different formula with a different type." }, { "code": null, "e": 42731, "s": 42588, "text": "Shared variables are used throughout the main report and all of its sub reports. Shared variables are even more general than global variables." }, { "code": null, "e": 42802, "s": 42731, "text": "To use a shared variable, declare it in a formula in the main report −" }, { "code": null, "e": 42829, "s": 42802, "text": "Shared NumberVar Z := 10;\n" }, { "code": null, "e": 42952, "s": 42829, "text": "To use shared variables, it must be declared and assigned a value before it can be used in the main report and subreports." }, { "code": null, "e": 43031, "s": 42952, "text": "An Array variable in Crystal Report can be defined by using a keyword “Array”." }, { "code": null, "e": 43071, "s": 43031, "text": "Global NumberVar Array Z := [1, 2, 3];\n" }, { "code": null, "e": 43196, "s": 43071, "text": "You can also assign values to the elements of Array and these values can be used for computations in formulas. For example −" }, { "code": null, "e": 43272, "s": 43196, "text": "StringVar Array Z := [“Hello”,”World”];\nZ[2] :=[“Bye”];\nUpperCase (Z [2] )\n" }, { "code": null, "e": 43315, "s": 43272, "text": "This formula will return the string “Bye”." }, { "code": null, "e": 43529, "s": 43315, "text": "You can also resize Array using Redim and Redim Preserve keywords. Redim is used to remove previous entries of an Array while resizing it, and Redim Preserve is used to contain previous Array values. For example −" }, { "code": null, "e": 43839, "s": 43529, "text": "Local NumberVar Array Z;\nRedim Z [2]; //Now Z is [0, 0]\nZ [2] := 10; //Now Z is [0, 10]\nRedim Z [3]; //Now Z is [0, 0, 0], Redim has erased previous Array values.\nZ [3] := 20; //Now Z is [0, 0, 20]\nRedim Preserve Z [4]; \n//Now Z is [0, 0, 20, 0], Redim Preserve has contained previous Array values.\n\"finished\"" }, { "code": null, "e": 43887, "s": 43839, "text": "Arrays are also used with Loops: like For loop." }, { "code": null, "e": 44024, "s": 43887, "text": "Local NumberVar Array Z;\nRedim Z[10];\nLocal NumberVar x;\nFor x := 1 To 10 Do\n(Z[x] := 10 * x);\nZ [5] //The formula returns the Number 50" }, { "code": null, "e": 44240, "s": 44024, "text": "Parameters are used to take user inputs before the report is generated. User has to answer the prompt before the report is generated and the report output depends on the response of the user for the parameter value." }, { "code": null, "e": 44386, "s": 44240, "text": "By using parameters with formulas and in the report, you can create a single report that changes according to the requirement of different users." }, { "code": null, "e": 44556, "s": 44386, "text": "LOVs can be used to enter prompt values in parameters. LOVs can be either static or dynamic. They can also be used as single level dynamic prompts or multilevel prompts." }, { "code": null, "e": 44657, "s": 44556, "text": "Note − Parameters in Crystal Reports can be used in filters after it is retrieved from the database." }, { "code": null, "e": 44826, "s": 44657, "text": "Parameters with dependency are grouped together and are known as cascading parameters. Cascading parameters allow you to group two or more parameters in a single group." }, { "code": null, "e": 45135, "s": 44826, "text": "Parameters can also be created at universe level or in query panel and they can be later inherited into Crystal Reports. They are called inherited parameters. These parameters can be dropped at the report level but they can’t be edited in a report. These parameters can only be edited where they are created." }, { "code": null, "e": 45191, "s": 45135, "text": "Parameters in Crystal Report support below data types −" }, { "code": null, "e": 45198, "s": 45191, "text": "Number" }, { "code": null, "e": 45205, "s": 45198, "text": "String" }, { "code": null, "e": 45210, "s": 45205, "text": "Date" }, { "code": null, "e": 45215, "s": 45210, "text": "Time" }, { "code": null, "e": 45224, "s": 45215, "text": "DateTime" }, { "code": null, "e": 45233, "s": 45224, "text": "Currency" }, { "code": null, "e": 45241, "s": 45233, "text": "Boolean" }, { "code": null, "e": 45248, "s": 45241, "text": "Member" }, { "code": null, "e": 45302, "s": 45248, "text": "Important points to remember while using Parameters −" }, { "code": null, "e": 45480, "s": 45302, "text": "To use parameter in a formula, it is not necessary to be placed in the report. Parameters can be used in a formula like other objects and can be created in the Formula workshop." }, { "code": null, "e": 45658, "s": 45480, "text": "To use parameter in a formula, it is not necessary to be placed in the report. Parameters can be used in a formula like other objects and can be created in the Formula workshop." }, { "code": null, "e": 45710, "s": 45658, "text": "Parameters can be used with static or dynamic LOVs." }, { "code": null, "e": 45762, "s": 45710, "text": "Parameters can be used with static or dynamic LOVs." }, { "code": null, "e": 45883, "s": 45762, "text": "You can also create a list of values from which the user can choose the parameter value instead of entering it manually." }, { "code": null, "e": 46004, "s": 45883, "text": "You can also create a list of values from which the user can choose the parameter value instead of entering it manually." }, { "code": null, "e": 46036, "s": 46004, "text": "Using data that does not change" }, { "code": null, "e": 46098, "s": 46036, "text": "Filtering data after it has been retrieved from the database." }, { "code": null, "e": 46166, "s": 46098, "text": "Filtering report data interactively without accessing the database." }, { "code": null, "e": 46271, "s": 46166, "text": "Creating an LOV where it doesn't already exist in the data source. such as in a Universe or a BEx Query." }, { "code": null, "e": 46353, "s": 46271, "text": "Creating reusable lists of values that are managed by the Universe administrator." }, { "code": null, "e": 46444, "s": 46353, "text": "In Data Explorer view, right-click within the Parameters area → select New → New Parameter" }, { "code": null, "e": 46652, "s": 46444, "text": "The Create Parameter dialog box appears → Enter a name for the parameter (up to 255 alphanumeric characters). In the dialog box, you can change the name and type of the parameter along with other properties." }, { "code": null, "e": 46748, "s": 46652, "text": "Select the appropriate Data Type from the list → such as String, Number, or Date, among others." }, { "code": null, "e": 46842, "s": 46748, "text": "In the Prompt Text box, enter the desired prompting text (up to 255 alphanumeric characters)." }, { "code": null, "e": 46872, "s": 46842, "text": "For example − \"Select a Name\"" }, { "code": null, "e": 46998, "s": 46872, "text": "This text will appear in the prompting dialog box when you preview the report, or when you refresh the data on the Page area." }, { "code": null, "e": 47357, "s": 46998, "text": "To create a list of values, click the ellipsis button → The Edit List of Values dialog box appears → Enter the values that you want to see when you are prompted → you might add a list of countries for a String type, or a list of values for a Number type → click OK → You return to the Create Parameter dialog → click OK and drag the parameter to your Report." }, { "code": null, "e": 47493, "s": 47357, "text": "Once the parameter is dragged to the structure of report, you can go to page tab to see LOVs selected while refreshing the report data." }, { "code": null, "e": 47647, "s": 47493, "text": "Filters are used to limit the records in a Crystal Report as per the user’s requirement. Filters are applied based on the object, operator and parameter." }, { "code": null, "e": 47694, "s": 47647, "text": "Go to Data tab at the top → Interactive Filter" }, { "code": null, "e": 47782, "s": 47694, "text": "Click Add Filter → Select first object from filter → Select Operator → Select Parameter" }, { "code": null, "e": 47944, "s": 47782, "text": "In the dropdown list it will show the list of all parameters that are created for the report. To edit the parameter, you can click on ellipsis button in the end." }, { "code": null, "e": 48114, "s": 47944, "text": "When a parameter is selected, click on OK. If you have selected list of values in parameter, it will ask you to select a value from the dropdown list → Select value → OK" }, { "code": null, "e": 48185, "s": 48114, "text": "Choose saved data or refresh data → Report now shows only filter data." }, { "code": null, "e": 48260, "s": 48185, "text": "To add multiple interactive filters, you can use ‘AND’ and ‘OR’ operators." }, { "code": null, "e": 48355, "s": 48260, "text": "Go to Data tab →Interactive filter → Select filter you want to delete → Click on delete button" }, { "code": null, "e": 48423, "s": 48355, "text": "While creating parameters, two types of prompt options can be used." }, { "code": null, "e": 48505, "s": 48423, "text": "Prompt to user will create a prompt for the user to enter the value of parameter." }, { "code": null, "e": 48587, "s": 48505, "text": "Prompt to user will create a prompt for the user to enter the value of parameter." }, { "code": null, "e": 48684, "s": 48587, "text": "Hidden Prompt will be used to pass some initial values or values by formula and not by the user." }, { "code": null, "e": 48781, "s": 48684, "text": "Hidden Prompt will be used to pass some initial values or values by formula and not by the user." }, { "code": null, "e": 48903, "s": 48781, "text": "When you use prompt to user option in Prompt panel, you need to enter Prompt text. Prompt panel gives you three options −" }, { "code": null, "e": 48991, "s": 48903, "text": "Do not show prompt − It doesn’t give you an option to change value at the report level." }, { "code": null, "e": 49079, "s": 48991, "text": "Do not show prompt − It doesn’t give you an option to change value at the report level." }, { "code": null, "e": 49160, "s": 49079, "text": "Show as Editable Prompt − It gives an option to enter different value each time." }, { "code": null, "e": 49241, "s": 49160, "text": "Show as Editable Prompt − It gives an option to enter different value each time." }, { "code": null, "e": 49323, "s": 49241, "text": "Show as Read Only Prompt − It gives an option to see the value in read-only mode." }, { "code": null, "e": 49405, "s": 49323, "text": "Show as Read Only Prompt − It gives an option to see the value in read-only mode." }, { "code": null, "e": 49473, "s": 49405, "text": "Hidden Prompt are used to pass initial values or values by formula." }, { "code": null, "e": 49706, "s": 49473, "text": "To pass initial value, click on ellipsis button just before function button. Once you click on this, it asks you to enter a value for the parameter. Once you enter the value and click on OK that value will be saved in Hidden prompt." }, { "code": null, "e": 49864, "s": 49706, "text": "To add a value, type the value and click on Add. When you drag the parameter to the report, that value will appear in the report as shown in the above image." }, { "code": null, "e": 49983, "s": 49864, "text": "Cascading parameter group allows to arrange your parameters into groups, which provides a cascade of filtered choices." }, { "code": null, "e": 50600, "s": 49983, "text": "For example, if you are prompting for a city value, but you also need to know which country and region that city comes from, you could create a cascading parameter group. In this case, you first prompt for a country, and when that value has been selected, the program prompts for a region by showing only the regions that apply to the selected country. Finally, when a region value has been selected, the program prompts for a city by showing only the cities that apply to the selected region. In this way, you can provide your user with a manageable list of cities and be sure that your user picks the correct city." }, { "code": null, "e": 50670, "s": 50600, "text": "Go to Data Explorer → Parameter → New → New Cascading Parameter group" }, { "code": null, "e": 50810, "s": 50670, "text": "Create a Parameter Group dialog box appears → Enter a name for the Parameter group → Enter the Prompt text as shown in the following image." }, { "code": null, "e": 50999, "s": 50810, "text": "Now click the first blank row in value column, it will show you all the available objects in the list. From the list, select Country → Select blank row below Country and select Region → OK" }, { "code": null, "e": 51170, "s": 50999, "text": "Now drag the country parameter to the report. It will give a prompt to enter Country name. Once you choose country name → it will give a prompt to choose the region name." }, { "code": null, "e": 51202, "s": 51170, "text": "Drag Region name to the report." }, { "code": null, "e": 51293, "s": 51202, "text": "In Data Explorer view, right-click within the Parameters area → select New → New Parameter" }, { "code": null, "e": 51501, "s": 51293, "text": "The Create Parameter dialog box appears → Enter a name for the parameter (up to 255 alphanumeric characters). In the dialog box, you can change the name and type of the parameter along with other properties." }, { "code": null, "e": 51597, "s": 51501, "text": "Select the appropriate Data Type from the list → such as String, Number, or Date, among others." }, { "code": null, "e": 51675, "s": 51597, "text": "In the Data Explorer → right click on Parameters → select New → New Parameter" }, { "code": null, "e": 51743, "s": 51675, "text": "In the Create Parameter dialog box, enter a name for the parameter." }, { "code": null, "e": 51850, "s": 51743, "text": "Select the appropriate Data Type from the list → Enter prompting text → Set Allow Multiple Values to True." }, { "code": null, "e": 51936, "s": 51850, "text": "Now, when prompting, you can specify multiple values to be entered for the parameter." }, { "code": null, "e": 51991, "s": 51936, "text": "For the type of value range, choose Discrete or Range." }, { "code": null, "e": 52089, "s": 51991, "text": "If you select Discrete, the parameter will accept discrete values (rather than ranges of values)." }, { "code": null, "e": 52572, "s": 52089, "text": "If you select Range, you are prompted for parameter values. You can enter a start value and an end value. For example, if you enter the values \"1\" and \"10\", the range is 1-10, and a report that uses this parameter for filtering will display all records with values between 1 and 10. This also works for string parameters. With a start value of \"A\" and an end value of \"H\", a report that uses this parameter for filtering will display all records within an alphabetical range of A-H." }, { "code": null, "e": 52919, "s": 52572, "text": "If the Allow Multiple Values and the Discrete Options are selected, the parameter will accept multiple discrete values. You can enter more than one value, but these values will be evaluated individually and will not be interpreted as a range. If the Allow Multiple Values and Range Options are selected, the parameter will accept multiple ranges." }, { "code": null, "e": 53045, "s": 52919, "text": "Once you drag the parameter to your report → To edit parameter filed, right click on parameter name and go to edit parameter." }, { "code": null, "e": 53115, "s": 53045, "text": "Once you click on edit parameter, it will open Edit parameter window." }, { "code": null, "e": 53189, "s": 53115, "text": "You can also edit the parameter by double clicking on the parameter name." }, { "code": null, "e": 53293, "s": 53189, "text": "Go to Data Explorer view → expand Parameters, and then right click on the parameter you want to delete." }, { "code": null, "e": 53308, "s": 53293, "text": "Choose Delete." }, { "code": null, "e": 53486, "s": 53308, "text": "You can create parameters using dynamic LOVs to retrieve data from data source. For example − When the customer name in database changes frequently, you can create dynamic LOVs." }, { "code": null, "e": 53583, "s": 53486, "text": "Open your report → Data Explorer panel → right click within Parameters and select New Parameter." }, { "code": null, "e": 53624, "s": 53583, "text": "The Create Parameter dialog box appears." }, { "code": null, "e": 53761, "s": 53624, "text": "Enter a name for the parameter (up to 255 alphanumeric characters) → To create a list of values, click the “Edit List of Values” button." }, { "code": null, "e": 53848, "s": 53761, "text": "The Edit List of Values dialog box appears → In the Type of List area, select Dynamic." }, { "code": null, "e": 53908, "s": 53848, "text": "In the Value combo box, select Customer Name from the list." }, { "code": null, "e": 53974, "s": 53908, "text": "You can sort the LOV in Ascending or Descending order → Click OK." }, { "code": null, "e": 54187, "s": 53974, "text": "In the Prompt Text object, enter the desired prompting text (up to 255 alphanumeric characters) → Text that appears in the prompting dialog and interactive panel. The default is “Enter (ParameterName)” → Click OK" }, { "code": null, "e": 54224, "s": 54187, "text": "Drag the Parameter into your report." }, { "code": null, "e": 54436, "s": 54224, "text": "Subreports allow you to combine unrelated reports into a single report. It is a report within a report. You can combine data that cannot be linked and present different views of the same data in a single report." }, { "code": null, "e": 54483, "s": 54436, "text": "Difference between Subreport and main report −" }, { "code": null, "e": 54564, "s": 54483, "text": "It is used as an element in the main report and cannot be used as single report." }, { "code": null, "e": 54645, "s": 54564, "text": "It is used as an element in the main report and cannot be used as single report." }, { "code": null, "e": 54690, "s": 54645, "text": "A Subreport cannot contain other subreports." }, { "code": null, "e": 54735, "s": 54690, "text": "A Subreport cannot contain other subreports." }, { "code": null, "e": 54827, "s": 54735, "text": "It can be placed in any report section and the entire subreport will print in that section." }, { "code": null, "e": 54919, "s": 54827, "text": "It can be placed in any report section and the entire subreport will print in that section." }, { "code": null, "e": 54973, "s": 54919, "text": "It doesn’t have page header or page footers sections." }, { "code": null, "e": 55027, "s": 54973, "text": "It doesn’t have page header or page footers sections." }, { "code": null, "e": 55354, "s": 55027, "text": "Unlinked subreports are standalone reports and their data is not linked to data in the main report. An unlinked subreport does not have to use the same data as the main report; it can use the same data source or a different data source entirely. Regardless of the underlying data sources, the reports are treated as unrelated." }, { "code": null, "e": 55705, "s": 55354, "text": "Linked subreports use data that is coordinated with data in the main report. The program matches up the data in the subreport with data in the main report. If you create a main report with customer information and a subreport with order information and then link them, the program creates a subreport for each customer that includes all their orders." }, { "code": null, "e": 55781, "s": 55705, "text": "Subreports can be linked with data-passing links or with subreport filters." }, { "code": null, "e": 56179, "s": 55781, "text": "You can insert a new report or an existing report as subreport in a main report. The subreport has similar characteristics as the main report. The data source to be used in subreport must be similar to data source that is used in main report and it must also be located on the same BI repository. You can also choose a different source connection but it should have a field to link to main report." }, { "code": null, "e": 56436, "s": 56179, "text": "A subreport can’t be inserted into another subreport. A subreport can be placed in any report section and the entire subreport will print in that section. However, a subreport cannot stand on its own. It is always inserted as an element into a main report." }, { "code": null, "e": 56511, "s": 56436, "text": "Go to Insert tab, click Subreport → The program displays an element frame." }, { "code": null, "e": 56596, "s": 56511, "text": "Move the cursor to where you want it to appear in the report, and click to place it." }, { "code": null, "e": 56768, "s": 56596, "text": "The Insert Subreport dialog box appears → Select create a new report → Type a name for the report in the Report Name text box. (You can also insert an existing subreport)." }, { "code": null, "e": 56796, "s": 56768, "text": "The Edit Query page appears" }, { "code": null, "e": 56824, "s": 56796, "text": "The Edit Query page appears" }, { "code": null, "e": 56879, "s": 56824, "text": "The Choose a Data Source Connection dialog box appears" }, { "code": null, "e": 56934, "s": 56879, "text": "The Choose a Data Source Connection dialog box appears" }, { "code": null, "e": 56976, "s": 56934, "text": "Select a data source, and then click Next" }, { "code": null, "e": 57018, "s": 56976, "text": "Select a data source, and then click Next" }, { "code": null, "e": 57046, "s": 57018, "text": "The Edit Query page appears" }, { "code": null, "e": 57074, "s": 57046, "text": "The Edit Query page appears" }, { "code": null, "e": 57237, "s": 57074, "text": "Choose an option from the Data Connection area, and click ‘Next’. If you choose Use Main Report Data Source it will open Query panel to add objects in the report." }, { "code": null, "e": 57373, "s": 57237, "text": "If you select connect to a new Data source, it will open New Data source connection window from which you can choose a new data source." }, { "code": null, "e": 57485, "s": 57373, "text": "Once you choose new data source, you need to define the relationship between the main report and the subreport." }, { "code": null, "e": 57594, "s": 57485, "text": "Once you click on ‘Next’ it will prompt you to choose a Sub Report type like Detailed, Chart, Total, Custom." }, { "code": null, "e": 57742, "s": 57594, "text": "Click on finish → it will show in the Structure of the main report. If you click on Page tab it will show the data of Subreport in the main report." }, { "code": null, "e": 57818, "s": 57742, "text": "On the Insert tab, click Subreport → The program displays an element frame." }, { "code": null, "e": 57903, "s": 57818, "text": "Move the cursor to where you want it to appear in the report, and click to place it." }, { "code": null, "e": 57992, "s": 57903, "text": "The Insert Subreport wizard appears → Select Use existing report, and then click Browse." }, { "code": null, "e": 58102, "s": 57992, "text": "The Open dialog box appears → Select the report that you would like to use, and then click Open → Click Next." }, { "code": null, "e": 58187, "s": 58102, "text": "If the report you selected contains parameters, the Data Passing Links page appears." }, { "code": null, "e": 58363, "s": 58187, "text": "Set up the appropriate links, and click ‘Next’. The Create Subreport Filters page appears → Create links between your main report and subreport by clicking Add → Click Finish." }, { "code": null, "e": 58417, "s": 58363, "text": "The report that you selected is added as a subreport." }, { "code": null, "e": 58465, "s": 58417, "text": "You can also save a subreport as a main report." }, { "code": null, "e": 58539, "s": 58465, "text": "Right click on the subreport frame, and click Save Subreport As → Save As" }, { "code": null, "e": 58587, "s": 58539, "text": "Type a new name for the subreport → Click Save." }, { "code": null, "e": 58659, "s": 58587, "text": "The subreport is saved as a main report and you can open it and use it." }, { "code": null, "e": 58775, "s": 58659, "text": "You can edit the properties of a subreport after you have inserted it into your main report. To format subreports −" }, { "code": null, "e": 58838, "s": 58775, "text": "Right click on the subreport frame and click Format Subreport." }, { "code": null, "e": 58887, "s": 58838, "text": "The Format dialog box appears → Edit the values." }, { "code": null, "e": 58975, "s": 58887, "text": "For example, you can change the name of the subreport, edit the font, size, color, etc." }, { "code": null, "e": 58988, "s": 58975, "text": "Click Close." }, { "code": null, "e": 59055, "s": 58988, "text": "Create the report you want to be printed first as the main report." }, { "code": null, "e": 59079, "s": 59055, "text": "Create a new subreport." }, { "code": null, "e": 59175, "s": 59079, "text": "Place the subreport into the Report Footer and it will print immediately after the main report." }, { "code": null, "e": 59289, "s": 59175, "text": "On-demand subreports can be especially useful when you want to create a report that contains multiple subreports." }, { "code": null, "e": 59624, "s": 59289, "text": "The difference between regular subreports and on-demand subreports is that the actual data of an on-demand subreport is not read from the data source until the user isolates it. This way only data for on-demand subreports that are actually viewed will be retrieved from the data source. This makes the subreports much more manageable." }, { "code": null, "e": 59815, "s": 59624, "text": "To create an on-demand subreport: Place an ordinary subreport in your main report. Right click on the subreport, and click Format Subreport. Click the Subreport option, and select On Demand." }, { "code": null, "e": 60040, "s": 59815, "text": "Finished Crystal Reports can be exported to a number of formats like XML, HTM, PDF, spreadsheets and word processors and other common data interchange formats. This allows Crystal Report to use and distribute in an easy way." }, { "code": null, "e": 60327, "s": 60040, "text": "For example, you may want to use the report data to enhance the presentation of data in a desktop publishing package. The exporting process requires you to specify a format and a destination. The format determines the file type, and the destination determines where the file is located." }, { "code": null, "e": 60404, "s": 60327, "text": "In Page mode, click File → Export and select an export format from the list." }, { "code": null, "e": 60470, "s": 60404, "text": "The Export Options dialog box appears. Select the export options." }, { "code": null, "e": 60527, "s": 60470, "text": "Click OK → You can also set a format as default options." }, { "code": null, "e": 60604, "s": 60527, "text": "In the Export Destination dialog box that appears, do one of the following −" }, { "code": null, "e": 60708, "s": 60604, "text": "Click ‘To file’ and enter the report title to save the exported report in the Export Report dialog box." }, { "code": null, "e": 60812, "s": 60708, "text": "Click ‘To file’ and enter the report title to save the exported report in the Export Report dialog box." }, { "code": null, "e": 60901, "s": 60812, "text": "Click ‘To application’ to open the report in the selected application without saving it." }, { "code": null, "e": 60990, "s": 60901, "text": "Click ‘To application’ to open the report in the selected application without saving it." }, { "code": null, "e": 61064, "s": 60990, "text": "There are different Excel options to export the data of a Crystal Report." }, { "code": null, "e": 61282, "s": 61064, "text": "Microsoft Excel (97-2003) Data-Only is a record-based format that concentrates on the data. This format does export most of the formatting, however, it does not merge cells, and each element is added to only one cell." }, { "code": null, "e": 61419, "s": 61282, "text": "This format can also export certain summaries as Excel functions. The summaries that are supported are SUM, AVERAGE, COUNT, MIN and MAX." }, { "code": null, "e": 61621, "s": 61419, "text": "Microsoft Excel Workbook Data-Only is a record based format that concentrates on data as well. This exporting format is an enhancement on the existing Microsoft Excel Workbook Data-Only exporting type." }, { "code": null, "e": 61887, "s": 61621, "text": "The exported result of this format is an XLSX file. XSLX file format is introduced and supported by Microsoft Excel 2007 and later. Microsoft Excel Workbook Data-Only format removes limitations of previous XLS file formats, approximately 65536 rows and 256 columns." }, { "code": null, "e": 62074, "s": 61887, "text": "Microsoft Excel (97-2003) Page-based format converts your report contents into Excel cells on a page-by-page basis. Contents from multiple pages are exported to the same Excel worksheet." }, { "code": null, "e": 62318, "s": 62074, "text": "If a worksheet becomes full and there is more data to export, the export program creates multiple worksheets to accommodate the data. If a report element covers more than one cell, the export program merges cells to represent a report element." }, { "code": null, "e": 62571, "s": 62318, "text": "Microsoft Excel has a limit of 256 columns in a worksheet so any report element that is added to cells beyond 256 columns is not exported. This export format retains most of the formatting, but it does not export line and box elements from your report." }, { "code": null, "e": 62745, "s": 62571, "text": "The Crystal Reports for Enterprise Java runtime engine does not support all of the elements embedded in a report. For example, OLAP Grids and Map elements are not supported." }, { "code": null, "e": 63006, "s": 62745, "text": "The character rendering technology differs between Crystal Reports for Enterprise and Crystal Reports 2013. This means that the size of each individual character can have slight differences (1 pixel) that add up over time and create additional rows or columns." }, { "code": null, "e": 63099, "s": 63006, "text": "XML format is primarily used for exchange of data in the report. It uses Crystal XML Schema." }, { "code": null, "e": 63170, "s": 63099, "text": "The XML expert in Crystal Reports can be used to customize XML output." }, { "code": null, "e": 63374, "s": 63170, "text": "Exporting Crystal Reports in HTML format allows an easy way to access and distribute the report data. It allows you to access your report in many of common browsers like Firefox and MS Internet Explorer." }, { "code": null, "e": 63638, "s": 63374, "text": "The HTML 4.0 format also saves the structure and formatting of the report by using DHTML. All of the images in your report are saved externally and a hyperlink is inserted in the exported HTML output. This export format generates more than one file in the output." }, { "code": null, "e": 63800, "s": 63638, "text": "Go to File → Export and select HTML 4.0 from the list. The Export Options dialog box appears. Select a Base Directory from the Base Directory text box. Click OK." }, { "code": null, "e": 63905, "s": 63800, "text": "The Export Destination dialog box opens. In the Export Destination dialog box, do one of the following −" }, { "code": null, "e": 64009, "s": 63905, "text": "Click ‘To File’ and enter the report title to save the exported report in the Export Report dialog box." }, { "code": null, "e": 64113, "s": 64009, "text": "Click ‘To File’ and enter the report title to save the exported report in the Export Report dialog box." }, { "code": null, "e": 64202, "s": 64113, "text": "Click ‘To Application’ to open the report in the selected application without saving it." }, { "code": null, "e": 64291, "s": 64202, "text": "Click ‘To Application’ to open the report in the selected application without saving it." }, { "code": null, "e": 64540, "s": 64291, "text": "If you select the option Separate HTML pages check box, the entire report is divided into separate pages. The initial HTML page will be saved as <report name>.html. This is the file you open if you want to view your report through your web browser." }, { "code": null, "e": 64756, "s": 64540, "text": "It exports the report elements as a set of values separated by separator and delimiter characters that you specify. When a comma (,) is used to separate elements, the format is known as Comma Separated Values (CSV)." }, { "code": null, "e": 65012, "s": 64756, "text": "This export format is popular among Microsoft Excel users. It creates one line of values for each record in your report and also contains all of the sections of your report like Page Header, Group header, Body, Group footer, Report footer and Page footer." }, { "code": null, "e": 65166, "s": 65012, "text": "This format cannot be used to export reports with cross-tabs. It cannot be used to export reports with subreports in Page Header or Page Footer sections." }, { "code": null, "e": 65354, "s": 65166, "text": "RTF format is page based format but it doesn’t preserve all structure and formatting options in the output. Microsoft Word format and Rich Text Format both produces RTF file as an output." }, { "code": null, "e": 65559, "s": 65354, "text": "This format is intended for use in applications, such as fill-out forms where the space for entering text is reserved as empty text objects. Almost all of the formatting is retained in this export format." }, { "code": null, "e": 65650, "s": 65559, "text": "The exporting file contains drawing objects and text fields to show objects in the report." }, { "code": null, "e": 65719, "s": 65650, "text": "The Rich Text Format (RTF) and Microsoft Word (RTF) format are same." }, { "code": null, "e": 65752, "s": 65719, "text": "\n 37 Lectures \n 2 hours \n" }, { "code": null, "e": 65764, "s": 65752, "text": " Neha Gupta" }, { "code": null, "e": 65799, "s": 65764, "text": "\n 61 Lectures \n 4.5 hours \n" }, { "code": null, "e": 65813, "s": 65799, "text": " Sasha Miller" }, { "code": null, "e": 65845, "s": 65813, "text": "\n 31 Lectures \n 32 mins\n" }, { "code": null, "e": 65868, "s": 65845, "text": " Prof Krishna N Sharma" }, { "code": null, "e": 65901, "s": 65868, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 65924, "s": 65901, "text": " Prof Krishna N Sharma" }, { "code": null, "e": 65957, "s": 65924, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 65980, "s": 65957, "text": " Prof Krishna N Sharma" }, { "code": null, "e": 65987, "s": 65980, "text": " Print" }, { "code": null, "e": 65998, "s": 65987, "text": " Add Notes" } ]
C# Program to add a node after the given node in a Linked List
Set a LinkedList and add elements. string [] students = {"Beth","Jennifer","Amy","Vera"}; LinkedList<string> list = new LinkedList<string>(students); Firstly, add a new node at the end. var newNode = list.AddLast("Emma"); Now, use the AddAfter() method to add a node after the given node. list.AddAfter(newNode, "Matt"); The following is the complete code. Live Demo using System; using System.Collections.Generic; class Demo { static void Main() { string [] students = {"Beth","Jennifer","Amy","Vera"}; LinkedList<string> list = new LinkedList<string>(students); foreach (var stu in list) { Console.WriteLine(stu); } // adding a node at the end var newNode = list.AddLast("Emma"); // adding a new node after the node added above list.AddAfter(newNode, "Matt"); Console.WriteLine("LinkedList after adding new nodes..."); foreach (var stu in list) { Console.WriteLine(stu); } } } Beth Jennifer Amy Vera LinkedList after adding new nodes... Beth Jennifer Amy Vera Emma Matt
[ { "code": null, "e": 1097, "s": 1062, "text": "Set a LinkedList and add elements." }, { "code": null, "e": 1212, "s": 1097, "text": "string [] students = {\"Beth\",\"Jennifer\",\"Amy\",\"Vera\"};\nLinkedList<string> list = new LinkedList<string>(students);" }, { "code": null, "e": 1248, "s": 1212, "text": "Firstly, add a new node at the end." }, { "code": null, "e": 1284, "s": 1248, "text": "var newNode = list.AddLast(\"Emma\");" }, { "code": null, "e": 1351, "s": 1284, "text": "Now, use the AddAfter() method to add a node after the given node." }, { "code": null, "e": 1383, "s": 1351, "text": "list.AddAfter(newNode, \"Matt\");" }, { "code": null, "e": 1419, "s": 1383, "text": "The following is the complete code." }, { "code": null, "e": 1430, "s": 1419, "text": " Live Demo" }, { "code": null, "e": 2035, "s": 1430, "text": "using System;\nusing System.Collections.Generic;\nclass Demo {\n static void Main() {\n string [] students = {\"Beth\",\"Jennifer\",\"Amy\",\"Vera\"};\n LinkedList<string> list = new LinkedList<string>(students);\n foreach (var stu in list) {\n Console.WriteLine(stu);\n }\n\n // adding a node at the end\n var newNode = list.AddLast(\"Emma\");\n\n // adding a new node after the node added above\n list.AddAfter(newNode, \"Matt\");\n\n Console.WriteLine(\"LinkedList after adding new nodes...\");\n foreach (var stu in list) {\n Console.WriteLine(stu);\n }\n }\n}" }, { "code": null, "e": 2128, "s": 2035, "text": "Beth\nJennifer\nAmy\nVera\nLinkedList after adding new nodes...\nBeth\nJennifer\nAmy\nVera\nEmma\nMatt" } ]
Stable Marriage Problem - GeeksforGeeks
23 Feb, 2022 The Stable Marriage Problem states that given N men and N women, where each person has ranked all members of the opposite sex in order of preference, marry the men and women together such that there are no two people of opposite sex who would both rather have each other than their current partners. If there are no such people, all the marriages are “stable” (Source Wiki). Consider the following example.Let there be two men m1 and m2 and two women w1 and w2. Let m1‘s list of preferences be {w1, w2} Let m2‘s list of preferences be {w1, w2} Let w1‘s list of preferences be {m1, m2} Let w2‘s list of preferences be {m1, m2}The matching { {m1, w2}, {w1, m2} } is not stable because m1 and w1 would prefer each other over their assigned partners. The matching {m1, w1} and {m2, w2} is stable because there are no two people of opposite sex that would prefer each other over their assigned partners. It is always possible to form stable marriages from lists of preferences (See references for proof). Following is Gale–Shapley algorithm to find a stable matching: The idea is to iterate through all free men while there is any free man available. Every free man goes to all women in his preference list according to the order. For every woman he goes to, he checks if the woman is free, if yes, they both become engaged. If the woman is not free, then the woman chooses either says no to him or dumps her current engagement according to her preference list. So an engagement done once can be broken if a woman gets better option. Time Complexity of Gale-Shapley Algorithm is O(n2). Following is complete algorithm from Wiki Initialize all men and women to free while there exist a free man m who still has a woman w to propose to { w = m's highest ranked such woman to whom he has not yet proposed if w is free (m, w) become engaged else some pair (m', w) already exists if w prefers m to m' (m, w) become engaged m' becomes free else (m', w) remain engaged } Input & Output: Input is a 2D matrix of size (2*N)*N where N is number of women or men. Rows from 0 to N-1 represent preference lists of men and rows from N to 2*N – 1 represent preference lists of women. So men are numbered from 0 to N-1 and women are numbered from N to 2*N – 1. The output is list of married pairs. Following is the implementation of the above algorithm. C++ Java Python3 C# Javascript // C++ program for stable marriage problem#include <iostream>#include <string.h>#include <stdio.h>using namespace std; // Number of Men or Women#define N 4 // This function returns true if woman 'w' prefers man 'm1' over man 'm'bool wPrefersM1OverM(int prefer[2*N][N], int w, int m, int m1){ // Check if w prefers m over her current engagement m1 for (int i = 0; i < N; i++) { // If m1 comes before m in list of w, then w prefers her // current engagement, don't do anything if (prefer[w][i] == m1) return true; // If m comes before m1 in w's list, then free her current // engagement and engage her with m if (prefer[w][i] == m) return false; }} // Prints stable matching for N boys and N girls. Boys are numbered as 0 to// N-1. Girls are numbered as N to 2N-1.void stableMarriage(int prefer[2*N][N]){ // Stores partner of women. This is our output array that // stores passing information. The value of wPartner[i] // indicates the partner assigned to woman N+i. Note that // the woman numbers between N and 2*N-1. The value -1 // indicates that (N+i)'th woman is free int wPartner[N]; // An array to store availability of men. If mFree[i] is // false, then man 'i' is free, otherwise engaged. bool mFree[N]; // Initialize all men and women as free memset(wPartner, -1, sizeof(wPartner)); memset(mFree, false, sizeof(mFree)); int freeCount = N; // While there are free men while (freeCount > 0) { // Pick the first free man (we could pick any) int m; for (m = 0; m < N; m++) if (mFree[m] == false) break; // One by one go to all women according to m's preferences. // Here m is the picked free man for (int i = 0; i < N && mFree[m] == false; i++) { int w = prefer[m][i]; // The woman of preference is free, w and m become // partners (Note that the partnership maybe changed // later). So we can say they are engaged not married if (wPartner[w-N] == -1) { wPartner[w-N] = m; mFree[m] = true; freeCount--; } else // If w is not free { // Find current engagement of w int m1 = wPartner[w-N]; // If w prefers m over her current engagement m1, // then break the engagement between w and m1 and // engage m with w. if (wPrefersM1OverM(prefer, w, m, m1) == false) { wPartner[w-N] = m; mFree[m] = true; mFree[m1] = false; } } // End of Else } // End of the for loop that goes to all women in m's list } // End of main while loop // Print the solution cout << "Woman Man" << endl; for (int i = 0; i < N; i++) cout << " " << i+N << "\t" << wPartner[i] << endl;} // Driver program to test above functionsint main(){ int prefer[2*N][N] = { {7, 5, 6, 4}, {5, 4, 6, 7}, {4, 5, 6, 7}, {4, 5, 6, 7}, {0, 1, 2, 3}, {0, 1, 2, 3}, {0, 1, 2, 3}, {0, 1, 2, 3}, }; stableMarriage(prefer); return 0;} // Java program for stable marriage problemimport java.util.*; class GFG{ // Number of Men or Womenstatic int N = 4; // This function returns true if woman// 'w' prefers man 'm1' over man 'm'static boolean wPrefersM1OverM(int prefer[][], int w, int m, int m1){ // Check if w prefers m over // her current engagement m1 for (int i = 0; i < N; i++) { // If m1 comes before m in list of w, // then w prefers her current engagement, // don't do anything if (prefer[w][i] == m1) return true; // If m comes before m1 in w's list, // then free her current engagement // and engage her with m if (prefer[w][i] == m) return false; } return false;} // Prints stable matching for N boys and// N girls. Boys are numbered as 0 to// N-1. Girls are numbered as N to 2N-1.static void stableMarriage(int prefer[][]){ // Stores partner of women. This is our // output array that stores passing information. // The value of wPartner[i] indicates the partner // assigned to woman N+i. Note that the woman // numbers between N and 2*N-1. The value -1 // indicates that (N+i)'th woman is free int wPartner[] = new int[N]; // An array to store availability of men. // If mFree[i] is false, then man 'i' is // free, otherwise engaged. boolean mFree[] = new boolean[N]; // Initialize all men and women as free Arrays.fill(wPartner, -1); int freeCount = N; // While there are free men while (freeCount > 0) { // Pick the first free man // (we could pick any) int m; for (m = 0; m < N; m++) if (mFree[m] == false) break; // One by one go to all women // according to m's preferences. // Here m is the picked free man for (int i = 0; i < N && mFree[m] == false; i++) { int w = prefer[m][i]; // The woman of preference is free, // w and m become partners (Note that // the partnership maybe changed later). // So we can say they are engaged not married if (wPartner[w - N] == -1) { wPartner[w - N] = m; mFree[m] = true; freeCount--; } else // If w is not free { // Find current engagement of w int m1 = wPartner[w - N]; // If w prefers m over her current engagement m1, // then break the engagement between w and m1 and // engage m with w. if (wPrefersM1OverM(prefer, w, m, m1) == false) { wPartner[w - N] = m; mFree[m] = true; mFree[m1] = false; } } // End of Else } // End of the for loop that goes // to all women in m's list } // End of main while loop // Print the solutionSystem.out.println("Woman Man");for (int i = 0; i < N; i++){ System.out.print(" "); System.out.println(i + N + " " + wPartner[i]);}} // Driver Codepublic static void main(String[] args){ int prefer[][] = new int[][]{{7, 5, 6, 4}, {5, 4, 6, 7}, {4, 5, 6, 7}, {4, 5, 6, 7}, {0, 1, 2, 3}, {0, 1, 2, 3}, {0, 1, 2, 3}, {0, 1, 2, 3}}; stableMarriage(prefer);}} // This code is contributed by Prerna Saini # Python3 program for stable marriage problem # Number of Men or WomenN = 4 # This function returns true if# woman 'w' prefers man 'm1' over man 'm'def wPrefersM1OverM(prefer, w, m, m1): # Check if w prefers m over her # current engagement m1 for i in range(N): # If m1 comes before m in list of w, # then w prefers her current engagement, # don't do anything if (prefer[w][i] == m1): return True # If m comes before m1 in w's list, # then free her current engagement # and engage her with m if (prefer[w][i] == m): return False # Prints stable matching for N boys and N girls.# Boys are numbered as 0 to N-1.# Girls are numbered as N to 2N-1.def stableMarriage(prefer): # Stores partner of women. This is our output # array that stores passing information. # The value of wPartner[i] indicates the partner # assigned to woman N+i. Note that the woman numbers # between N and 2*N-1. The value -1 indicates # that (N+i)'th woman is free wPartner = [-1 for i in range(N)] # An array to store availability of men. # If mFree[i] is false, then man 'i' is free, # otherwise engaged. mFree = [False for i in range(N)] freeCount = N # While there are free men while (freeCount > 0): # Pick the first free man (we could pick any) m = 0 while (m < N): if (mFree[m] == False): break m += 1 # One by one go to all women according to # m's preferences. Here m is the picked free man i = 0 while i < N and mFree[m] == False: w = prefer[m][i] # The woman of preference is free, # w and m become partners (Note that # the partnership maybe changed later). # So we can say they are engaged not married if (wPartner[w - N] == -1): wPartner[w - N] = m mFree[m] = True freeCount -= 1 else: # If w is not free # Find current engagement of w m1 = wPartner[w - N] # If w prefers m over her current engagement m1, # then break the engagement between w and m1 and # engage m with w. if (wPrefersM1OverM(prefer, w, m, m1) == False): wPartner[w - N] = m mFree[m] = True mFree[m1] = False i += 1 # End of Else # End of the for loop that goes # to all women in m's list # End of main while loop # Print solution print("Woman ", " Man") for i in range(N): print(i + N, "\t", wPartner[i]) # Driver Codeprefer = [[7, 5, 6, 4], [5, 4, 6, 7], [4, 5, 6, 7], [4, 5, 6, 7], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]] stableMarriage(prefer) # This code is contributed by Mohit Kumar // C# program for stable marriage problemusing System;using System.Collections.Generic; class GFG{ // Number of Men or Womenstatic int N = 4; // This function returns true if woman// 'w' prefers man 'm1' over man 'm'static bool wPrefersM1OverM(int [,]prefer, int w, int m, int m1){ // Check if w prefers m over // her current engagement m1 for (int i = 0; i < N; i++) { // If m1 comes before m in list of w, // then w prefers her current engagement, // don't do anything if (prefer[w, i] == m1) return true; // If m comes before m1 in w's list, // then free her current engagement // and engage her with m if (prefer[w, i] == m) return false; } return false;} // Prints stable matching for N boys and// N girls. Boys are numbered as 0 to// N-1. Girls are numbered as N to 2N-1.static void stableMarriage(int [,]prefer){ // Stores partner of women. This is our // output array that stores passing information. // The value of wPartner[i] indicates the partner // assigned to woman N+i. Note that the woman // numbers between N and 2*N-1. The value -1 // indicates that (N+i)'th woman is free int []wPartner = new int[N]; // An array to store availability of men. // If mFree[i] is false, then man 'i' is // free, otherwise engaged. bool []mFree = new bool[N]; // Initialize all men and women as free for (int i = 0; i < N; i++) wPartner[i] = -1; int freeCount = N; // While there are free men while (freeCount > 0) { // Pick the first free man // (we could pick any) int m; for (m = 0; m < N; m++) if (mFree[m] == false) break; // One by one go to all women // according to m's preferences. // Here m is the picked free man for (int i = 0; i < N && mFree[m] == false; i++) { int w = prefer[m,i]; // The woman of preference is free, // w and m become partners (Note that // the partnership maybe changed later). // So we can say they are engaged not married if (wPartner[w - N] == -1) { wPartner[w - N] = m; mFree[m] = true; freeCount--; } else // If w is not free { // Find current engagement of w int m1 = wPartner[w - N]; // If w prefers m over her current engagement m1, // then break the engagement between w and m1 and // engage m with w. if (wPrefersM1OverM(prefer, w, m, m1) == false) { wPartner[w - N] = m; mFree[m] = true; mFree[m1] = false; } } // End of Else } // End of the for loop that goes // to all women in m's list } // End of main while loop // Print the solution Console.WriteLine("Woman Man"); for (int i = 0; i < N; i++) { Console.Write(" "); Console.WriteLine(i + N + " " + wPartner[i]); }} // Driver Codepublic static void Main(String[] args){ int [,]prefer = new int[,]{{7, 5, 6, 4}, {5, 4, 6, 7}, {4, 5, 6, 7}, {4, 5, 6, 7}, {0, 1, 2, 3}, {0, 1, 2, 3}, {0, 1, 2, 3}, {0, 1, 2, 3}}; stableMarriage(prefer);}} // This code is contributed by Rajput-Ji <script>// Javascript program for stable marriage problem // Number of Men or WomenN = 4; // This function returns true if woman 'w' prefers man 'm1' over man 'm'function wPrefersM1OverM( prefer, w, m, m1){ // Check if w prefers m over her current engagement m1 for (var i = 0; i < N; i++) { // If m1 comes before m in list of w, then w prefers her // current engagement, don't do anything if (prefer[w][i] == m1) return true; // If m comes before m1 in w's list, then free her current // engagement and engage her with m if (prefer[w][i] == m) return false; }} // Prints stable matching for N boys and N girls. Boys are numbered as 0 to// N-1. Girls are numbered as N to 2N-1.function stableMarriage( prefer){ // Stores partner of women. This is our output array that // stores passing information. The value of wPartner[i] // indicates the partner assigned to woman N+i. Note that // the woman numbers between N and 2*N-1. The value -1 // indicates that (N+i)'th woman is free var wPartner = new Array(N); // An array to store availability of men. If mFree[i] is // false, then man 'i' is free, otherwise engaged. mFree = new Array(N); // Initialize all men and women as free wPartner.fill(-1); mFree.fill(false); var freeCount = N; // While there are free men while (freeCount > 0) { // Pick the first free man (we could pick any) var m; for (m = 0; m < N; m++) if (mFree[m] == false) break; // One by one go to all women according to m's preferences. // Here m is the picked free man for (var i = 0; i < N && mFree[m] == false; i++) { var w = prefer[m][i]; // The woman of preference is free, w and m become // partners (Note that the partnership maybe changed // later). So we can say they are engaged not married if (wPartner[w-N] == -1) { wPartner[w-N] = m; mFree[m] = true; freeCount--; } else // If w is not free { // Find current engagement of w var m1 = wPartner[w-N]; // If w prefers m over her current engagement m1, // then break the engagement between w and m1 and // engage m with w. if (wPrefersM1OverM(prefer, w, m, m1) == false) { wPartner[w-N] = m; mFree[m] = true; mFree[m1] = false; } } // End of Else } // End of the for loop that goes to all women in m's list } // End of main while loop // Print the solution document.write("Woman Man" +"<br>"); for (var i = 0; i < N; i++) document.write(" " + (i+N) + " " + wPartner[i] +"<br>");} var prefer = [ [7, 5, 6, 4], [5, 4, 6, 7], [4, 5, 6, 7], [4, 5, 6, 7], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], ]; stableMarriage(prefer); // This code is contributed by SoumikMondal</script> Output: Woman Man 4 2 5 1 6 3 7 0 YouTubeGeeksforGeeks500K subscribersStable Marriage Problem | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 13:58•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=o1olHmxDzTw" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> References: http://www.csee.wvu.edu/~ksmani/courses/fa01/random/lecnotes/lecture5.pdfhttp://www.youtube.com/watch?v=5RSMLgy06Ew#t=11m4sPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above ParulShandilya prerna saini Rajput-Ji mohit kumar 29 SoumikMondal simmytarika5 surindertarika1234 surinderdawra388 khushboogoyal499 Graph Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Topological Sorting Bellman–Ford Algorithm | DP-23 Detect Cycle in a Directed Graph Floyd Warshall Algorithm | DP-16 Ford-Fulkerson Algorithm for Maximum Flow Problem Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph) Traveling Salesman Problem (TSP) Implementation Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Strongly Connected Components Detect cycle in an undirected graph
[ { "code": null, "e": 25118, "s": 25090, "text": "\n23 Feb, 2022" }, { "code": null, "e": 25493, "s": 25118, "text": "The Stable Marriage Problem states that given N men and N women, where each person has ranked all members of the opposite sex in order of preference, marry the men and women together such that there are no two people of opposite sex who would both rather have each other than their current partners. If there are no such people, all the marriages are “stable” (Source Wiki)." }, { "code": null, "e": 26017, "s": 25493, "text": "Consider the following example.Let there be two men m1 and m2 and two women w1 and w2. Let m1‘s list of preferences be {w1, w2} Let m2‘s list of preferences be {w1, w2} Let w1‘s list of preferences be {m1, m2} Let w2‘s list of preferences be {m1, m2}The matching { {m1, w2}, {w1, m2} } is not stable because m1 and w1 would prefer each other over their assigned partners. The matching {m1, w1} and {m2, w2} is stable because there are no two people of opposite sex that would prefer each other over their assigned partners." }, { "code": null, "e": 26700, "s": 26017, "text": "It is always possible to form stable marriages from lists of preferences (See references for proof). Following is Gale–Shapley algorithm to find a stable matching: The idea is to iterate through all free men while there is any free man available. Every free man goes to all women in his preference list according to the order. For every woman he goes to, he checks if the woman is free, if yes, they both become engaged. If the woman is not free, then the woman chooses either says no to him or dumps her current engagement according to her preference list. So an engagement done once can be broken if a woman gets better option. Time Complexity of Gale-Shapley Algorithm is O(n2). " }, { "code": null, "e": 26744, "s": 26700, "text": "Following is complete algorithm from Wiki " }, { "code": null, "e": 27149, "s": 26744, "text": "Initialize all men and women to free\nwhile there exist a free man m who still has a woman w to propose to \n{\n w = m's highest ranked such woman to whom he has not yet proposed\n if w is free\n (m, w) become engaged\n else some pair (m', w) already exists\n if w prefers m to m'\n (m, w) become engaged\n m' becomes free\n else\n (m', w) remain engaged \n}" }, { "code": null, "e": 27468, "s": 27149, "text": "Input & Output: Input is a 2D matrix of size (2*N)*N where N is number of women or men. Rows from 0 to N-1 represent preference lists of men and rows from N to 2*N – 1 represent preference lists of women. So men are numbered from 0 to N-1 and women are numbered from N to 2*N – 1. The output is list of married pairs. " }, { "code": null, "e": 27526, "s": 27468, "text": "Following is the implementation of the above algorithm. " }, { "code": null, "e": 27530, "s": 27526, "text": "C++" }, { "code": null, "e": 27535, "s": 27530, "text": "Java" }, { "code": null, "e": 27543, "s": 27535, "text": "Python3" }, { "code": null, "e": 27546, "s": 27543, "text": "C#" }, { "code": null, "e": 27557, "s": 27546, "text": "Javascript" }, { "code": "// C++ program for stable marriage problem#include <iostream>#include <string.h>#include <stdio.h>using namespace std; // Number of Men or Women#define N 4 // This function returns true if woman 'w' prefers man 'm1' over man 'm'bool wPrefersM1OverM(int prefer[2*N][N], int w, int m, int m1){ // Check if w prefers m over her current engagement m1 for (int i = 0; i < N; i++) { // If m1 comes before m in list of w, then w prefers her // current engagement, don't do anything if (prefer[w][i] == m1) return true; // If m comes before m1 in w's list, then free her current // engagement and engage her with m if (prefer[w][i] == m) return false; }} // Prints stable matching for N boys and N girls. Boys are numbered as 0 to// N-1. Girls are numbered as N to 2N-1.void stableMarriage(int prefer[2*N][N]){ // Stores partner of women. This is our output array that // stores passing information. The value of wPartner[i] // indicates the partner assigned to woman N+i. Note that // the woman numbers between N and 2*N-1. The value -1 // indicates that (N+i)'th woman is free int wPartner[N]; // An array to store availability of men. If mFree[i] is // false, then man 'i' is free, otherwise engaged. bool mFree[N]; // Initialize all men and women as free memset(wPartner, -1, sizeof(wPartner)); memset(mFree, false, sizeof(mFree)); int freeCount = N; // While there are free men while (freeCount > 0) { // Pick the first free man (we could pick any) int m; for (m = 0; m < N; m++) if (mFree[m] == false) break; // One by one go to all women according to m's preferences. // Here m is the picked free man for (int i = 0; i < N && mFree[m] == false; i++) { int w = prefer[m][i]; // The woman of preference is free, w and m become // partners (Note that the partnership maybe changed // later). So we can say they are engaged not married if (wPartner[w-N] == -1) { wPartner[w-N] = m; mFree[m] = true; freeCount--; } else // If w is not free { // Find current engagement of w int m1 = wPartner[w-N]; // If w prefers m over her current engagement m1, // then break the engagement between w and m1 and // engage m with w. if (wPrefersM1OverM(prefer, w, m, m1) == false) { wPartner[w-N] = m; mFree[m] = true; mFree[m1] = false; } } // End of Else } // End of the for loop that goes to all women in m's list } // End of main while loop // Print the solution cout << \"Woman Man\" << endl; for (int i = 0; i < N; i++) cout << \" \" << i+N << \"\\t\" << wPartner[i] << endl;} // Driver program to test above functionsint main(){ int prefer[2*N][N] = { {7, 5, 6, 4}, {5, 4, 6, 7}, {4, 5, 6, 7}, {4, 5, 6, 7}, {0, 1, 2, 3}, {0, 1, 2, 3}, {0, 1, 2, 3}, {0, 1, 2, 3}, }; stableMarriage(prefer); return 0;}", "e": 30872, "s": 27557, "text": null }, { "code": "// Java program for stable marriage problemimport java.util.*; class GFG{ // Number of Men or Womenstatic int N = 4; // This function returns true if woman// 'w' prefers man 'm1' over man 'm'static boolean wPrefersM1OverM(int prefer[][], int w, int m, int m1){ // Check if w prefers m over // her current engagement m1 for (int i = 0; i < N; i++) { // If m1 comes before m in list of w, // then w prefers her current engagement, // don't do anything if (prefer[w][i] == m1) return true; // If m comes before m1 in w's list, // then free her current engagement // and engage her with m if (prefer[w][i] == m) return false; } return false;} // Prints stable matching for N boys and// N girls. Boys are numbered as 0 to// N-1. Girls are numbered as N to 2N-1.static void stableMarriage(int prefer[][]){ // Stores partner of women. This is our // output array that stores passing information. // The value of wPartner[i] indicates the partner // assigned to woman N+i. Note that the woman // numbers between N and 2*N-1. The value -1 // indicates that (N+i)'th woman is free int wPartner[] = new int[N]; // An array to store availability of men. // If mFree[i] is false, then man 'i' is // free, otherwise engaged. boolean mFree[] = new boolean[N]; // Initialize all men and women as free Arrays.fill(wPartner, -1); int freeCount = N; // While there are free men while (freeCount > 0) { // Pick the first free man // (we could pick any) int m; for (m = 0; m < N; m++) if (mFree[m] == false) break; // One by one go to all women // according to m's preferences. // Here m is the picked free man for (int i = 0; i < N && mFree[m] == false; i++) { int w = prefer[m][i]; // The woman of preference is free, // w and m become partners (Note that // the partnership maybe changed later). // So we can say they are engaged not married if (wPartner[w - N] == -1) { wPartner[w - N] = m; mFree[m] = true; freeCount--; } else // If w is not free { // Find current engagement of w int m1 = wPartner[w - N]; // If w prefers m over her current engagement m1, // then break the engagement between w and m1 and // engage m with w. if (wPrefersM1OverM(prefer, w, m, m1) == false) { wPartner[w - N] = m; mFree[m] = true; mFree[m1] = false; } } // End of Else } // End of the for loop that goes // to all women in m's list } // End of main while loop // Print the solutionSystem.out.println(\"Woman Man\");for (int i = 0; i < N; i++){ System.out.print(\" \"); System.out.println(i + N + \" \" + wPartner[i]);}} // Driver Codepublic static void main(String[] args){ int prefer[][] = new int[][]{{7, 5, 6, 4}, {5, 4, 6, 7}, {4, 5, 6, 7}, {4, 5, 6, 7}, {0, 1, 2, 3}, {0, 1, 2, 3}, {0, 1, 2, 3}, {0, 1, 2, 3}}; stableMarriage(prefer);}} // This code is contributed by Prerna Saini", "e": 34542, "s": 30872, "text": null }, { "code": "# Python3 program for stable marriage problem # Number of Men or WomenN = 4 # This function returns true if# woman 'w' prefers man 'm1' over man 'm'def wPrefersM1OverM(prefer, w, m, m1): # Check if w prefers m over her # current engagement m1 for i in range(N): # If m1 comes before m in list of w, # then w prefers her current engagement, # don't do anything if (prefer[w][i] == m1): return True # If m comes before m1 in w's list, # then free her current engagement # and engage her with m if (prefer[w][i] == m): return False # Prints stable matching for N boys and N girls.# Boys are numbered as 0 to N-1.# Girls are numbered as N to 2N-1.def stableMarriage(prefer): # Stores partner of women. This is our output # array that stores passing information. # The value of wPartner[i] indicates the partner # assigned to woman N+i. Note that the woman numbers # between N and 2*N-1. The value -1 indicates # that (N+i)'th woman is free wPartner = [-1 for i in range(N)] # An array to store availability of men. # If mFree[i] is false, then man 'i' is free, # otherwise engaged. mFree = [False for i in range(N)] freeCount = N # While there are free men while (freeCount > 0): # Pick the first free man (we could pick any) m = 0 while (m < N): if (mFree[m] == False): break m += 1 # One by one go to all women according to # m's preferences. Here m is the picked free man i = 0 while i < N and mFree[m] == False: w = prefer[m][i] # The woman of preference is free, # w and m become partners (Note that # the partnership maybe changed later). # So we can say they are engaged not married if (wPartner[w - N] == -1): wPartner[w - N] = m mFree[m] = True freeCount -= 1 else: # If w is not free # Find current engagement of w m1 = wPartner[w - N] # If w prefers m over her current engagement m1, # then break the engagement between w and m1 and # engage m with w. if (wPrefersM1OverM(prefer, w, m, m1) == False): wPartner[w - N] = m mFree[m] = True mFree[m1] = False i += 1 # End of Else # End of the for loop that goes # to all women in m's list # End of main while loop # Print solution print(\"Woman \", \" Man\") for i in range(N): print(i + N, \"\\t\", wPartner[i]) # Driver Codeprefer = [[7, 5, 6, 4], [5, 4, 6, 7], [4, 5, 6, 7], [4, 5, 6, 7], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]] stableMarriage(prefer) # This code is contributed by Mohit Kumar", "e": 37537, "s": 34542, "text": null }, { "code": "// C# program for stable marriage problemusing System;using System.Collections.Generic; class GFG{ // Number of Men or Womenstatic int N = 4; // This function returns true if woman// 'w' prefers man 'm1' over man 'm'static bool wPrefersM1OverM(int [,]prefer, int w, int m, int m1){ // Check if w prefers m over // her current engagement m1 for (int i = 0; i < N; i++) { // If m1 comes before m in list of w, // then w prefers her current engagement, // don't do anything if (prefer[w, i] == m1) return true; // If m comes before m1 in w's list, // then free her current engagement // and engage her with m if (prefer[w, i] == m) return false; } return false;} // Prints stable matching for N boys and// N girls. Boys are numbered as 0 to// N-1. Girls are numbered as N to 2N-1.static void stableMarriage(int [,]prefer){ // Stores partner of women. This is our // output array that stores passing information. // The value of wPartner[i] indicates the partner // assigned to woman N+i. Note that the woman // numbers between N and 2*N-1. The value -1 // indicates that (N+i)'th woman is free int []wPartner = new int[N]; // An array to store availability of men. // If mFree[i] is false, then man 'i' is // free, otherwise engaged. bool []mFree = new bool[N]; // Initialize all men and women as free for (int i = 0; i < N; i++) wPartner[i] = -1; int freeCount = N; // While there are free men while (freeCount > 0) { // Pick the first free man // (we could pick any) int m; for (m = 0; m < N; m++) if (mFree[m] == false) break; // One by one go to all women // according to m's preferences. // Here m is the picked free man for (int i = 0; i < N && mFree[m] == false; i++) { int w = prefer[m,i]; // The woman of preference is free, // w and m become partners (Note that // the partnership maybe changed later). // So we can say they are engaged not married if (wPartner[w - N] == -1) { wPartner[w - N] = m; mFree[m] = true; freeCount--; } else // If w is not free { // Find current engagement of w int m1 = wPartner[w - N]; // If w prefers m over her current engagement m1, // then break the engagement between w and m1 and // engage m with w. if (wPrefersM1OverM(prefer, w, m, m1) == false) { wPartner[w - N] = m; mFree[m] = true; mFree[m1] = false; } } // End of Else } // End of the for loop that goes // to all women in m's list } // End of main while loop // Print the solution Console.WriteLine(\"Woman Man\"); for (int i = 0; i < N; i++) { Console.Write(\" \"); Console.WriteLine(i + N + \" \" + wPartner[i]); }} // Driver Codepublic static void Main(String[] args){ int [,]prefer = new int[,]{{7, 5, 6, 4}, {5, 4, 6, 7}, {4, 5, 6, 7}, {4, 5, 6, 7}, {0, 1, 2, 3}, {0, 1, 2, 3}, {0, 1, 2, 3}, {0, 1, 2, 3}}; stableMarriage(prefer);}} // This code is contributed by Rajput-Ji", "e": 41248, "s": 37537, "text": null }, { "code": "<script>// Javascript program for stable marriage problem // Number of Men or WomenN = 4; // This function returns true if woman 'w' prefers man 'm1' over man 'm'function wPrefersM1OverM( prefer, w, m, m1){ // Check if w prefers m over her current engagement m1 for (var i = 0; i < N; i++) { // If m1 comes before m in list of w, then w prefers her // current engagement, don't do anything if (prefer[w][i] == m1) return true; // If m comes before m1 in w's list, then free her current // engagement and engage her with m if (prefer[w][i] == m) return false; }} // Prints stable matching for N boys and N girls. Boys are numbered as 0 to// N-1. Girls are numbered as N to 2N-1.function stableMarriage( prefer){ // Stores partner of women. This is our output array that // stores passing information. The value of wPartner[i] // indicates the partner assigned to woman N+i. Note that // the woman numbers between N and 2*N-1. The value -1 // indicates that (N+i)'th woman is free var wPartner = new Array(N); // An array to store availability of men. If mFree[i] is // false, then man 'i' is free, otherwise engaged. mFree = new Array(N); // Initialize all men and women as free wPartner.fill(-1); mFree.fill(false); var freeCount = N; // While there are free men while (freeCount > 0) { // Pick the first free man (we could pick any) var m; for (m = 0; m < N; m++) if (mFree[m] == false) break; // One by one go to all women according to m's preferences. // Here m is the picked free man for (var i = 0; i < N && mFree[m] == false; i++) { var w = prefer[m][i]; // The woman of preference is free, w and m become // partners (Note that the partnership maybe changed // later). So we can say they are engaged not married if (wPartner[w-N] == -1) { wPartner[w-N] = m; mFree[m] = true; freeCount--; } else // If w is not free { // Find current engagement of w var m1 = wPartner[w-N]; // If w prefers m over her current engagement m1, // then break the engagement between w and m1 and // engage m with w. if (wPrefersM1OverM(prefer, w, m, m1) == false) { wPartner[w-N] = m; mFree[m] = true; mFree[m1] = false; } } // End of Else } // End of the for loop that goes to all women in m's list } // End of main while loop // Print the solution document.write(\"Woman Man\" +\"<br>\"); for (var i = 0; i < N; i++) document.write(\" \" + (i+N) + \" \" + wPartner[i] +\"<br>\");} var prefer = [ [7, 5, 6, 4], [5, 4, 6, 7], [4, 5, 6, 7], [4, 5, 6, 7], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], ]; stableMarriage(prefer); // This code is contributed by SoumikMondal</script>", "e": 44470, "s": 41248, "text": null }, { "code": null, "e": 44479, "s": 44470, "text": "Output: " }, { "code": null, "e": 44533, "s": 44479, "text": "Woman Man\n 4 2\n 5 1\n 6 3\n 7 0\n " }, { "code": null, "e": 45356, "s": 44533, "text": "YouTubeGeeksforGeeks500K subscribersStable Marriage Problem | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 13:58•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=o1olHmxDzTw\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 45616, "s": 45356, "text": "References: http://www.csee.wvu.edu/~ksmani/courses/fa01/random/lecnotes/lecture5.pdfhttp://www.youtube.com/watch?v=5RSMLgy06Ew#t=11m4sPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 45631, "s": 45616, "text": "ParulShandilya" }, { "code": null, "e": 45644, "s": 45631, "text": "prerna saini" }, { "code": null, "e": 45654, "s": 45644, "text": "Rajput-Ji" }, { "code": null, "e": 45669, "s": 45654, "text": "mohit kumar 29" }, { "code": null, "e": 45682, "s": 45669, "text": "SoumikMondal" }, { "code": null, "e": 45695, "s": 45682, "text": "simmytarika5" }, { "code": null, "e": 45714, "s": 45695, "text": "surindertarika1234" }, { "code": null, "e": 45731, "s": 45714, "text": "surinderdawra388" }, { "code": null, "e": 45748, "s": 45731, "text": "khushboogoyal499" }, { "code": null, "e": 45754, "s": 45748, "text": "Graph" }, { "code": null, "e": 45760, "s": 45754, "text": "Graph" }, { "code": null, "e": 45858, "s": 45760, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 45867, "s": 45858, "text": "Comments" }, { "code": null, "e": 45880, "s": 45867, "text": "Old Comments" }, { "code": null, "e": 45900, "s": 45880, "text": "Topological Sorting" }, { "code": null, "e": 45931, "s": 45900, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 45964, "s": 45931, "text": "Detect Cycle in a Directed Graph" }, { "code": null, "e": 45997, "s": 45964, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 46047, "s": 45997, "text": "Ford-Fulkerson Algorithm for Maximum Flow Problem" }, { "code": null, "e": 46122, "s": 46047, "text": "Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)" }, { "code": null, "e": 46170, "s": 46122, "text": "Traveling Salesman Problem (TSP) Implementation" }, { "code": null, "e": 46238, "s": 46170, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 46268, "s": 46238, "text": "Strongly Connected Components" } ]
C++ Vector Library - front() Function
The C++ function std::vector::front() returns a reference to the first element of the vector. Following is the declaration for std::vector::front() function form std::vector header. reference front(); const_reference front() const; None Returns constant reference if object is constant qualified otherwise returns non-constant reference. This member function never throws exception. Constant i.e. O(1) The following example shows the usage of std::vector::front() function. #include <iostream> #include <vector> using namespace std; int main(void) { vector<int> v = {1, 2, 3, 4, 5}; cout << "First element of vector = " << v.front() << endl; return 0; } Let us compile and run the above program, this will produce the following result − First element of vector = 1 Print Add Notes Bookmark this page
[ { "code": null, "e": 2697, "s": 2603, "text": "The C++ function std::vector::front() returns a reference to the first element of the vector." }, { "code": null, "e": 2785, "s": 2697, "text": "Following is the declaration for std::vector::front() function form std::vector header." }, { "code": null, "e": 2836, "s": 2785, "text": "reference front();\nconst_reference front() const;\n" }, { "code": null, "e": 2841, "s": 2836, "text": "None" }, { "code": null, "e": 2942, "s": 2841, "text": "Returns constant reference if object is constant qualified otherwise returns non-constant reference." }, { "code": null, "e": 2987, "s": 2942, "text": "This member function never throws exception." }, { "code": null, "e": 3006, "s": 2987, "text": "Constant i.e. O(1)" }, { "code": null, "e": 3078, "s": 3006, "text": "The following example shows the usage of std::vector::front() function." }, { "code": null, "e": 3271, "s": 3078, "text": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main(void) {\n vector<int> v = {1, 2, 3, 4, 5};\n\n cout << \"First element of vector = \" << v.front() << endl;\n\n return 0;\n}" }, { "code": null, "e": 3354, "s": 3271, "text": "Let us compile and run the above program, this will produce the following result −" }, { "code": null, "e": 3383, "s": 3354, "text": "First element of vector = 1\n" }, { "code": null, "e": 3390, "s": 3383, "text": " Print" }, { "code": null, "e": 3401, "s": 3390, "text": " Add Notes" } ]
Python Design Patterns - Template
A template pattern defines a basic algorithm in a base class using abstract operation where subclasses override the concrete behavior. The template pattern keeps the outline of algorithm in a separate method. This method is referred as the template method. Following are the different features of the template pattern − It defines the skeleton of algorithm in an operation It defines the skeleton of algorithm in an operation It includes subclasses, which redefine certain steps of an algorithm. It includes subclasses, which redefine certain steps of an algorithm. class MakeMeal: def prepare(self): pass def cook(self): pass def eat(self): pass def go(self): self.prepare() self.cook() self.eat() class MakePizza(MakeMeal): def prepare(self): print "Prepare Pizza" def cook(self): print "Cook Pizza" def eat(self): print "Eat Pizza" class MakeTea(MakeMeal): def prepare(self): print "Prepare Tea" def cook(self): print "Cook Tea" def eat(self): print "Eat Tea" makePizza = MakePizza() makePizza.go() print 25*"+" makeTea = MakeTea() makeTea.go() The above program generates the following output − This code creates a template to prepare meal. Here, each parameter represents the attribute to create a part of meal like tea, pizza, etc. The output represents the visualization of attributes. 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2736, "s": 2479, "text": "A template pattern defines a basic algorithm in a base class using abstract operation where subclasses override the concrete behavior. The template pattern keeps the outline of algorithm in a separate method. This method is referred as the template method." }, { "code": null, "e": 2799, "s": 2736, "text": "Following are the different features of the template pattern −" }, { "code": null, "e": 2852, "s": 2799, "text": "It defines the skeleton of algorithm in an operation" }, { "code": null, "e": 2905, "s": 2852, "text": "It defines the skeleton of algorithm in an operation" }, { "code": null, "e": 2975, "s": 2905, "text": "It includes subclasses, which redefine certain steps of an algorithm." }, { "code": null, "e": 3045, "s": 2975, "text": "It includes subclasses, which redefine certain steps of an algorithm." }, { "code": null, "e": 3632, "s": 3045, "text": "class MakeMeal:\n\n def prepare(self): pass\n def cook(self): pass\n def eat(self): pass\n\n def go(self):\n self.prepare()\n self.cook()\n self.eat()\n\nclass MakePizza(MakeMeal):\n def prepare(self):\n print \"Prepare Pizza\"\n \n def cook(self):\n print \"Cook Pizza\"\n \n def eat(self):\n print \"Eat Pizza\"\n\nclass MakeTea(MakeMeal):\n def prepare(self):\n print \"Prepare Tea\"\n\t\n def cook(self):\n print \"Cook Tea\"\n \n def eat(self):\n print \"Eat Tea\"\n\nmakePizza = MakePizza()\nmakePizza.go()\n\nprint 25*\"+\"\n\nmakeTea = MakeTea()\nmakeTea.go()" }, { "code": null, "e": 3683, "s": 3632, "text": "The above program generates the following output −" }, { "code": null, "e": 3822, "s": 3683, "text": "This code creates a template to prepare meal. Here, each parameter represents the attribute to create a part of meal like tea, pizza, etc." }, { "code": null, "e": 3877, "s": 3822, "text": "The output represents the visualization of attributes." }, { "code": null, "e": 3914, "s": 3877, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3930, "s": 3914, "text": " Malhar Lathkar" }, { "code": null, "e": 3963, "s": 3930, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3982, "s": 3963, "text": " Arnab Chakraborty" }, { "code": null, "e": 4017, "s": 3982, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 4039, "s": 4017, "text": " In28Minutes Official" }, { "code": null, "e": 4073, "s": 4039, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 4101, "s": 4073, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4136, "s": 4101, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 4150, "s": 4136, "text": " Lets Kode It" }, { "code": null, "e": 4183, "s": 4150, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 4200, "s": 4183, "text": " Abhilash Nelson" }, { "code": null, "e": 4207, "s": 4200, "text": " Print" }, { "code": null, "e": 4218, "s": 4207, "text": " Add Notes" } ]
MySQL Tryit Editor v1.0
SELECT NOW() + 1; ​ Edit the SQL Statement, and click "Run SQL" to see the result. This SQL-Statement is not supported in the WebSQL Database. The example still works, because it uses a modified version of SQL. Your browser does not support WebSQL. Your are now using a light-version of the Try-SQL Editor, with a read-only Database. If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time. Our Try-SQL Editor uses WebSQL to demonstrate SQL. A Database-object is created in your browser, for testing purposes. You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button. WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object. WebSQL is supported in Chrome, Safari, and Opera. If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
[ { "code": null, "e": 18, "s": 0, "text": "SELECT NOW() + 1;" }, { "code": null, "e": 20, "s": 18, "text": "​" }, { "code": null, "e": 92, "s": 29, "text": "Edit the SQL Statement, and click \"Run SQL\" to see the result." }, { "code": null, "e": 152, "s": 92, "text": "This SQL-Statement is not supported in the WebSQL Database." }, { "code": null, "e": 220, "s": 152, "text": "The example still works, because it uses a modified version of SQL." }, { "code": null, "e": 258, "s": 220, "text": "Your browser does not support WebSQL." }, { "code": null, "e": 343, "s": 258, "text": "Your are now using a light-version of the Try-SQL Editor, with a read-only Database." }, { "code": null, "e": 517, "s": 343, "text": "If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time." }, { "code": null, "e": 568, "s": 517, "text": "Our Try-SQL Editor uses WebSQL to demonstrate SQL." }, { "code": null, "e": 636, "s": 568, "text": "A Database-object is created in your browser, for testing purposes." }, { "code": null, "e": 807, "s": 636, "text": "You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the \"Restore Database\" button." }, { "code": null, "e": 907, "s": 807, "text": "WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object." }, { "code": null, "e": 957, "s": 907, "text": "WebSQL is supported in Chrome, Safari, and Opera." } ]
How to Create a Color Picker Tool in Android using Color Wheel and Slider? - GeeksforGeeks
22 Oct, 2020 In the previous article How to Create a Basic Color Picker Tool in Android, we have discussed to create a basic color picker tool. In this article, we are going to create the same color picker tool but using a color wheel and slider. This is another type of the Color Picker which allows user to pick the brightness level of the color and color intensity. This is also one of the open-source libraries. So in this article its been discussed to implement the following type of color picker tool. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Adding the ColorPicker library dependency Now add the Color picker library’s dependency as (to the app-level gradle file): implementation ‘com.github.duanhong169:colorpicker:1.1.6’ Make sure the system should be connected to the network (so that it downloads the required files) and after invoking the dependency click on the “Sync Now” button. Refer to the following image if unable to locate the app-level gradle file and invoke the dependency. Step 3: Working with the activity_main.xml file Next, go to the activity_main.xml file, which represents the UI of the project. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity" tools:ignore="HardcodedText"> <!--Give all widgets, the proper id to handle them in MainActivity.java--> <!--GeeksforGeeks Text--> <TextView android:id="@+id/gfg_heading" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="32dp" android:text="GeeksforGeeks" android:textSize="42sp" android:textStyle="bold" /> <!--Pick color Button--> <Button android:id="@+id/pick_color_button" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="32dp" android:layout_marginStart="32dp" android:layout_marginEnd="32dp" android:text="Pick Color" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="32dp" android:textSize="18sp" android:text="Your picked color is:" /> <!--sample view to preview selected color by user--> <!--by default this has been set to darker gery--> <!--this can be overridden after user chose the color from color picker--> <!--which has been handled in the MainActivity.java--> <View android:id="@+id/preview_selected_color" android:layout_width="48dp" android:layout_height="48dp" android:layout_gravity="center" android:background="@android:color/darker_gray" android:layout_marginTop="8dp" /> <!--set color button to overwrite the color for GeeksforGeeks text--> <Button android:id="@+id/set_color_button" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="32dp" android:layout_marginStart="32dp" android:layout_marginEnd="32dp" android:text="Set Color" /> </LinearLayout> Output UI: Before going to handle the color picker tool dialog functionality, understanding the parts of the dialog box is necessary so that it can become easier while dealing with parts of the dialog box in java code. Step 4: Working with the MainActivity.java file Finally, go to the MainActivity.java file, and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.graphics.Color;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView;import androidx.appcompat.app.AppCompatActivity;import top.defaults.colorpicker.ColorPickerPopup; public class MainActivity extends AppCompatActivity { // text view variable to set the color for GFG text private TextView gfgTextView; // two buttons to open color picker dialog and one to // set the color for GFG text private Button mSetColorButton, mPickColorButton; // view box to preview the selected color private View mColorPreview; // this is the default color of the preview box private int mDefaultColor; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // register the GFG text with appropriate ID gfgTextView = findViewById(R.id.gfg_heading); // register two of the buttons with their // appropriate IDs mPickColorButton = findViewById(R.id.pick_color_button); mSetColorButton = findViewById(R.id.set_color_button); // and also register the view which shows the // preview of the color chosen by the user mColorPreview = findViewById(R.id.preview_selected_color); // set the default color to 0 as it is black mDefaultColor = 0; // handling the Pick Color Button to open color // picker dialog mPickColorButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(final View v) { new ColorPickerPopup.Builder(MainActivity.this).initialColor( Color.RED) // set initial color // of the color // picker dialog .enableBrightness( true) // enable color brightness // slider or not .enableAlpha( true) // enable color alpha // changer on slider or // not .okTitle( "Choose") // this is top right // Choose button .cancelTitle( "Cancel") // this is top left // Cancel button which // closes the .showIndicator( true) // this is the small box // which shows the chosen // color by user at the // bottom of the cancel // button .showValue( true) // this is the value which // shows the selected // color hex code // the above all values can be made // false to disable them on the // color picker dialog. .build() .show( v, new ColorPickerPopup.ColorPickerObserver() { @Override public void onColorPicked(int color) { // set the color // which is returned // by the color // picker mDefaultColor = color; // now as soon as // the dialog closes // set the preview // box to returned // color mColorPreview.setBackgroundColor(mDefaultColor); } }); } }); // handling the Set Color button to set the selected // color for the GFG text. mSetColorButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { // now change the value of the GFG text // as well. gfgTextView.setTextColor(mDefaultColor); } }); }} android Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Create and Add Data to SQLite Database in Android? Broadcast Receiver in Android With Example Services in Android with Example Content Providers in Android with Example Android RecyclerView in Kotlin Arrays in Java Split() String method in Java with examples For-each loop in Java Arrays.sort() in Java with examples Reverse a string in Java
[ { "code": null, "e": 24773, "s": 24745, "text": "\n22 Oct, 2020" }, { "code": null, "e": 25268, "s": 24773, "text": "In the previous article How to Create a Basic Color Picker Tool in Android, we have discussed to create a basic color picker tool. In this article, we are going to create the same color picker tool but using a color wheel and slider. This is another type of the Color Picker which allows user to pick the brightness level of the color and color intensity. This is also one of the open-source libraries. So in this article its been discussed to implement the following type of color picker tool." }, { "code": null, "e": 25432, "s": 25268, "text": "A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language." }, { "code": null, "e": 25461, "s": 25432, "text": "Step 1: Create a New Project" }, { "code": null, "e": 25572, "s": 25461, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio." }, { "code": null, "e": 25623, "s": 25572, "text": "Note that select Java as the programming language." }, { "code": null, "e": 25673, "s": 25623, "text": "Step 2: Adding the ColorPicker library dependency" }, { "code": null, "e": 25754, "s": 25673, "text": "Now add the Color picker library’s dependency as (to the app-level gradle file):" }, { "code": null, "e": 25812, "s": 25754, "text": "implementation ‘com.github.duanhong169:colorpicker:1.1.6’" }, { "code": null, "e": 25976, "s": 25812, "text": "Make sure the system should be connected to the network (so that it downloads the required files) and after invoking the dependency click on the “Sync Now” button." }, { "code": null, "e": 26078, "s": 25976, "text": "Refer to the following image if unable to locate the app-level gradle file and invoke the dependency." }, { "code": null, "e": 26126, "s": 26078, "text": "Step 3: Working with the activity_main.xml file" }, { "code": null, "e": 26206, "s": 26126, "text": "Next, go to the activity_main.xml file, which represents the UI of the project." }, { "code": null, "e": 26330, "s": 26206, "text": "Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 26334, "s": 26330, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".MainActivity\" tools:ignore=\"HardcodedText\"> <!--Give all widgets, the proper id to handle them in MainActivity.java--> <!--GeeksforGeeks Text--> <TextView android:id=\"@+id/gfg_heading\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center\" android:layout_marginTop=\"32dp\" android:text=\"GeeksforGeeks\" android:textSize=\"42sp\" android:textStyle=\"bold\" /> <!--Pick color Button--> <Button android:id=\"@+id/pick_color_button\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center\" android:layout_marginTop=\"32dp\" android:layout_marginStart=\"32dp\" android:layout_marginEnd=\"32dp\" android:text=\"Pick Color\" /> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center\" android:layout_marginTop=\"32dp\" android:textSize=\"18sp\" android:text=\"Your picked color is:\" /> <!--sample view to preview selected color by user--> <!--by default this has been set to darker gery--> <!--this can be overridden after user chose the color from color picker--> <!--which has been handled in the MainActivity.java--> <View android:id=\"@+id/preview_selected_color\" android:layout_width=\"48dp\" android:layout_height=\"48dp\" android:layout_gravity=\"center\" android:background=\"@android:color/darker_gray\" android:layout_marginTop=\"8dp\" /> <!--set color button to overwrite the color for GeeksforGeeks text--> <Button android:id=\"@+id/set_color_button\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center\" android:layout_marginTop=\"32dp\" android:layout_marginStart=\"32dp\" android:layout_marginEnd=\"32dp\" android:text=\"Set Color\" /> </LinearLayout>", "e": 28689, "s": 26334, "text": null }, { "code": null, "e": 28700, "s": 28689, "text": "Output UI:" }, { "code": null, "e": 28908, "s": 28700, "text": "Before going to handle the color picker tool dialog functionality, understanding the parts of the dialog box is necessary so that it can become easier while dealing with parts of the dialog box in java code." }, { "code": null, "e": 28956, "s": 28908, "text": "Step 4: Working with the MainActivity.java file" }, { "code": null, "e": 29032, "s": 28956, "text": "Finally, go to the MainActivity.java file, and refer to the following code." }, { "code": null, "e": 29156, "s": 29032, "text": "Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 29161, "s": 29156, "text": "Java" }, { "code": "import android.graphics.Color;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView;import androidx.appcompat.app.AppCompatActivity;import top.defaults.colorpicker.ColorPickerPopup; public class MainActivity extends AppCompatActivity { // text view variable to set the color for GFG text private TextView gfgTextView; // two buttons to open color picker dialog and one to // set the color for GFG text private Button mSetColorButton, mPickColorButton; // view box to preview the selected color private View mColorPreview; // this is the default color of the preview box private int mDefaultColor; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // register the GFG text with appropriate ID gfgTextView = findViewById(R.id.gfg_heading); // register two of the buttons with their // appropriate IDs mPickColorButton = findViewById(R.id.pick_color_button); mSetColorButton = findViewById(R.id.set_color_button); // and also register the view which shows the // preview of the color chosen by the user mColorPreview = findViewById(R.id.preview_selected_color); // set the default color to 0 as it is black mDefaultColor = 0; // handling the Pick Color Button to open color // picker dialog mPickColorButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(final View v) { new ColorPickerPopup.Builder(MainActivity.this).initialColor( Color.RED) // set initial color // of the color // picker dialog .enableBrightness( true) // enable color brightness // slider or not .enableAlpha( true) // enable color alpha // changer on slider or // not .okTitle( \"Choose\") // this is top right // Choose button .cancelTitle( \"Cancel\") // this is top left // Cancel button which // closes the .showIndicator( true) // this is the small box // which shows the chosen // color by user at the // bottom of the cancel // button .showValue( true) // this is the value which // shows the selected // color hex code // the above all values can be made // false to disable them on the // color picker dialog. .build() .show( v, new ColorPickerPopup.ColorPickerObserver() { @Override public void onColorPicked(int color) { // set the color // which is returned // by the color // picker mDefaultColor = color; // now as soon as // the dialog closes // set the preview // box to returned // color mColorPreview.setBackgroundColor(mDefaultColor); } }); } }); // handling the Set Color button to set the selected // color for the GFG text. mSetColorButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { // now change the value of the GFG text // as well. gfgTextView.setTextColor(mDefaultColor); } }); }}", "e": 34262, "s": 29161, "text": null }, { "code": null, "e": 34270, "s": 34262, "text": "android" }, { "code": null, "e": 34278, "s": 34270, "text": "Android" }, { "code": null, "e": 34283, "s": 34278, "text": "Java" }, { "code": null, "e": 34288, "s": 34283, "text": "Java" }, { "code": null, "e": 34296, "s": 34288, "text": "Android" }, { "code": null, "e": 34394, "s": 34296, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34452, "s": 34394, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 34495, "s": 34452, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 34528, "s": 34495, "text": "Services in Android with Example" }, { "code": null, "e": 34570, "s": 34528, "text": "Content Providers in Android with Example" }, { "code": null, "e": 34601, "s": 34570, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 34616, "s": 34601, "text": "Arrays in Java" }, { "code": null, "e": 34660, "s": 34616, "text": "Split() String method in Java with examples" }, { "code": null, "e": 34682, "s": 34660, "text": "For-each loop in Java" }, { "code": null, "e": 34718, "s": 34682, "text": "Arrays.sort() in Java with examples" } ]
Developing a DCGAN Model in Tensorflow 2.0 | by Mouhamed Ndoye | Towards Data Science
In early March 2019, TensorFlow 2.0 was released and we decided to create an image generator based on Taehoon Kim’s implementation of DCGAN. Here’s a tutorial on how to develop a DCGAN model in TensorFlow 2.0. “To avoid the fast convergence of D (discriminator) network, G (generator) network is updated twice for each D network update, which differs from original paper.” — Taehoon Kim Jupyter Notebook TensorFlow 2.0 Access to high-performing GPU The image below illustrates the generator referenced in the DCGAN paper. Essentially, this network takes in a 100x1 noise vector, labeled 100z, and maps it into the G(Z) output which is 64x64x3. 100x1 → 1024x4x4 → 512x8x8 → 256x16x16 → 128x32x32 → 64x64x3 The first layer expands the random noise by projecting and reshaping at each step The stride specifies the ‘steps’ of the convolution along the height and width. Here’s an animated example: generator = make_generator_model()noise = tf.random.normal([1,100]) # shape is 1, 100generated_image = generator(noise, training = False)plt.imshow(generated_image[0, :, :, 0], cmap =”gist_rainbow”) In Keras, you can create layers to develop models. A model is usually a network of layers, in which, the most common type is a stack of layers Adding a densely-connected layer to the model will take as input arrays of shape (*, 100). The shape of the data will be (*, 4*4*1024) after the first layer. In this case, you won’t need to specify the size of the input moving forward because of automatic shape inferenceBatch normalization functions similarly to preprocessing at every layer of the network. ReLU is linear for all positive values and set to zero for all negative values. Leaky ReLU has a smaller slope for negative values, instead of altogether zero. For example, leaky ReLU may have y = 0.01x when x < 0 def make_generator_model(): model = tf.keras.Sequential() model.add(layers.Dense(4*4*1024, use_bias = False, input_shape = (100,))) model.add(layers.BatchNormalization()) model.add(layers.LeakyReLU()) The generator uses a transposed convolutional layer (upsampling) to produce an image from seed (random noise). 512 is the dimensionality of the output space (5,5) specifies the height and width of the 2D convolution window Strides = (2,2) model.add(layers.Conv2DTranspose(512, (5, 5), strides = (2,2), padding = “same”, use_bias = False)) assert model.output_shape == (None, 8, 8, 512)model.add(layers.BatchNormalization())model.add(layers.LeakyReLU()) The generator uses a transposed convolutional layer (upsampling) to produce an image from the previous layer. 256 is the dimensionality of the output space (5,5) specifies the height and width of the 2D convolution window Strides = (2,2) model.add(layers.Conv2DTranspose(256, (5,5), strides = (2,2), padding = “same”, use_bias = False))assert model.output_shape == (None, 16, 16, 256)model.add(layers.BatchNormalization())model.add(layers.LeakyReLU()) The generator uses a transposed convolutional layer (upsampling) to produce an image from the previous layer. 128 is the dimensionality of the output space (5,5) specifies the height and width of the 2D convolution window Strides = (2,2) model.add(layers.Conv2DTranspose(128, (5,5), strides = (2,2), padding = “same”, use_bias = False))assert model.output_shape == (None, 32, 32, 128)model.add(layers.BatchNormalization())model.add(layers.LeakyReLU()) The generator uses a transposed convolutional layer (upsampling) to produce an image from the previous layer. 64 is the dimensionality of the output space (5,5) specifies the height and width of the 2D convolution window Strides = (2,2) specifies the strides of the convolution along the height and width model.add(layers.Conv2DTranspose(3, (5,5), strides = (2,2), padding = “same”, use_bias = False, activation = “tanh”))assert model.output_shape == (None, 64, 64, 3) return model The generator’s loss quantifies how well it was able to trick the discriminator. Intuitively, if the generator is performing well, the discriminator will classify the fake images as real (or 1). Here, we will compare the discriminators decisions on the generated images to an array of 1s. def generator_loss(fake_output): return cross_entropy(tf.ones_like(fake_output), fake_output) The discriminator and the generator optimizers are different since we will train two networks, separately. The Adam optimization algorithm is an extension of stochastic gradient descent. Stochastic gradient descent maintains a single learning rate (termed alpha) for all weight updates while the learning rate does not change during training.A learning rate is maintained for each network weight (parameter) and adapts as learning unfolds. generator_optimizer = tf.keras.optimizers.Adam(1e-4)discriminator_optimizer = tf.keras.optimizers.Adam(1e-4) To start off, we trained our DCGAN model with 3 Deconvolutional layers on the MNIST dataset (28 x 28 grayscale images) which resulted in clearer renderings which can be seen below: Using a DCGAN model with 4 DC layers trained on a subset of the CelebA dataset (25,600 / 202,599 images), we were able to generate images resembling faces with a run of 100 epochs. TensorFlow 1.5 — GPU — Py3 — P5000 TensorFlow 2.0 — GPU — Py3 — P5000 TensorFlow 2.0 — GPU — Py3 — Tesla V100 60,000 images 128 x 128 202,599 images Transformed 218 x 178 to 64 x 64 Understanding GAN model created using Tensorflow Developing DCGAN model using Tensorflow 2.0 Resizing/cropping the dataset images from 218 x 178 to 64 x 64 Memory leakage in Jupyter Notebook while training the new model Incompatibilities with TensorFlow 1.3 and 2.0 Paperspace auto-shutdown after 12 hrs Migrate the model to an environment which can compute 100 epochs using the CelebA dataset in its entirety Tune the model architecture to generate better images Develop a solution to resize images for more efficiently github.com We couldn’t have completed this project without the great people of the Internet. Please check out the following resources for your next data science project: Unsupervised Representation Learning with Deep Convolutional Generative Adversarial Networks — https://arxiv.org/abs/1511.06434 Compressed Sensing using Generative Models — https://arxiv.org/pdf/1703.03208.pdf Image Completion with Deep Learning in TensorFlow — http://bamos.github.io/2016/08/09/deep-completion/
[ { "code": null, "e": 382, "s": 172, "text": "In early March 2019, TensorFlow 2.0 was released and we decided to create an image generator based on Taehoon Kim’s implementation of DCGAN. Here’s a tutorial on how to develop a DCGAN model in TensorFlow 2.0." }, { "code": null, "e": 545, "s": 382, "text": "“To avoid the fast convergence of D (discriminator) network, G (generator) network is updated twice for each D network update, which differs from original paper.”" }, { "code": null, "e": 559, "s": 545, "text": "— Taehoon Kim" }, { "code": null, "e": 576, "s": 559, "text": "Jupyter Notebook" }, { "code": null, "e": 591, "s": 576, "text": "TensorFlow 2.0" }, { "code": null, "e": 621, "s": 591, "text": "Access to high-performing GPU" }, { "code": null, "e": 816, "s": 621, "text": "The image below illustrates the generator referenced in the DCGAN paper. Essentially, this network takes in a 100x1 noise vector, labeled 100z, and maps it into the G(Z) output which is 64x64x3." }, { "code": null, "e": 877, "s": 816, "text": "100x1 → 1024x4x4 → 512x8x8 → 256x16x16 → 128x32x32 → 64x64x3" }, { "code": null, "e": 959, "s": 877, "text": "The first layer expands the random noise by projecting and reshaping at each step" }, { "code": null, "e": 1067, "s": 959, "text": "The stride specifies the ‘steps’ of the convolution along the height and width. Here’s an animated example:" }, { "code": null, "e": 1266, "s": 1067, "text": "generator = make_generator_model()noise = tf.random.normal([1,100]) # shape is 1, 100generated_image = generator(noise, training = False)plt.imshow(generated_image[0, :, :, 0], cmap =”gist_rainbow”)" }, { "code": null, "e": 1409, "s": 1266, "text": "In Keras, you can create layers to develop models. A model is usually a network of layers, in which, the most common type is a stack of layers" }, { "code": null, "e": 1768, "s": 1409, "text": "Adding a densely-connected layer to the model will take as input arrays of shape (*, 100). The shape of the data will be (*, 4*4*1024) after the first layer. In this case, you won’t need to specify the size of the input moving forward because of automatic shape inferenceBatch normalization functions similarly to preprocessing at every layer of the network." }, { "code": null, "e": 1928, "s": 1768, "text": "ReLU is linear for all positive values and set to zero for all negative values. Leaky ReLU has a smaller slope for negative values, instead of altogether zero." }, { "code": null, "e": 1982, "s": 1928, "text": "For example, leaky ReLU may have y = 0.01x when x < 0" }, { "code": null, "e": 2185, "s": 1982, "text": "def make_generator_model(): model = tf.keras.Sequential() model.add(layers.Dense(4*4*1024, use_bias = False, input_shape = (100,))) model.add(layers.BatchNormalization()) model.add(layers.LeakyReLU())" }, { "code": null, "e": 2296, "s": 2185, "text": "The generator uses a transposed convolutional layer (upsampling) to produce an image from seed (random noise)." }, { "code": null, "e": 2342, "s": 2296, "text": "512 is the dimensionality of the output space" }, { "code": null, "e": 2408, "s": 2342, "text": "(5,5) specifies the height and width of the 2D convolution window" }, { "code": null, "e": 2424, "s": 2408, "text": "Strides = (2,2)" }, { "code": null, "e": 2638, "s": 2424, "text": "model.add(layers.Conv2DTranspose(512, (5, 5), strides = (2,2), padding = “same”, use_bias = False)) assert model.output_shape == (None, 8, 8, 512)model.add(layers.BatchNormalization())model.add(layers.LeakyReLU())" }, { "code": null, "e": 2748, "s": 2638, "text": "The generator uses a transposed convolutional layer (upsampling) to produce an image from the previous layer." }, { "code": null, "e": 2794, "s": 2748, "text": "256 is the dimensionality of the output space" }, { "code": null, "e": 2860, "s": 2794, "text": "(5,5) specifies the height and width of the 2D convolution window" }, { "code": null, "e": 2876, "s": 2860, "text": "Strides = (2,2)" }, { "code": null, "e": 3090, "s": 2876, "text": "model.add(layers.Conv2DTranspose(256, (5,5), strides = (2,2), padding = “same”, use_bias = False))assert model.output_shape == (None, 16, 16, 256)model.add(layers.BatchNormalization())model.add(layers.LeakyReLU())" }, { "code": null, "e": 3200, "s": 3090, "text": "The generator uses a transposed convolutional layer (upsampling) to produce an image from the previous layer." }, { "code": null, "e": 3246, "s": 3200, "text": "128 is the dimensionality of the output space" }, { "code": null, "e": 3312, "s": 3246, "text": "(5,5) specifies the height and width of the 2D convolution window" }, { "code": null, "e": 3328, "s": 3312, "text": "Strides = (2,2)" }, { "code": null, "e": 3542, "s": 3328, "text": "model.add(layers.Conv2DTranspose(128, (5,5), strides = (2,2), padding = “same”, use_bias = False))assert model.output_shape == (None, 32, 32, 128)model.add(layers.BatchNormalization())model.add(layers.LeakyReLU())" }, { "code": null, "e": 3652, "s": 3542, "text": "The generator uses a transposed convolutional layer (upsampling) to produce an image from the previous layer." }, { "code": null, "e": 3697, "s": 3652, "text": "64 is the dimensionality of the output space" }, { "code": null, "e": 3763, "s": 3697, "text": "(5,5) specifies the height and width of the 2D convolution window" }, { "code": null, "e": 3847, "s": 3763, "text": "Strides = (2,2) specifies the strides of the convolution along the height and width" }, { "code": null, "e": 4024, "s": 3847, "text": "model.add(layers.Conv2DTranspose(3, (5,5), strides = (2,2), padding = “same”, use_bias = False, activation = “tanh”))assert model.output_shape == (None, 64, 64, 3) return model" }, { "code": null, "e": 4219, "s": 4024, "text": "The generator’s loss quantifies how well it was able to trick the discriminator. Intuitively, if the generator is performing well, the discriminator will classify the fake images as real (or 1)." }, { "code": null, "e": 4313, "s": 4219, "text": "Here, we will compare the discriminators decisions on the generated images to an array of 1s." }, { "code": null, "e": 4407, "s": 4313, "text": "def generator_loss(fake_output): return cross_entropy(tf.ones_like(fake_output), fake_output)" }, { "code": null, "e": 4594, "s": 4407, "text": "The discriminator and the generator optimizers are different since we will train two networks, separately. The Adam optimization algorithm is an extension of stochastic gradient descent." }, { "code": null, "e": 4847, "s": 4594, "text": "Stochastic gradient descent maintains a single learning rate (termed alpha) for all weight updates while the learning rate does not change during training.A learning rate is maintained for each network weight (parameter) and adapts as learning unfolds." }, { "code": null, "e": 4956, "s": 4847, "text": "generator_optimizer = tf.keras.optimizers.Adam(1e-4)discriminator_optimizer = tf.keras.optimizers.Adam(1e-4)" }, { "code": null, "e": 5137, "s": 4956, "text": "To start off, we trained our DCGAN model with 3 Deconvolutional layers on the MNIST dataset (28 x 28 grayscale images) which resulted in clearer renderings which can be seen below:" }, { "code": null, "e": 5318, "s": 5137, "text": "Using a DCGAN model with 4 DC layers trained on a subset of the CelebA dataset (25,600 / 202,599 images), we were able to generate images resembling faces with a run of 100 epochs." }, { "code": null, "e": 5353, "s": 5318, "text": "TensorFlow 1.5 — GPU — Py3 — P5000" }, { "code": null, "e": 5388, "s": 5353, "text": "TensorFlow 2.0 — GPU — Py3 — P5000" }, { "code": null, "e": 5428, "s": 5388, "text": "TensorFlow 2.0 — GPU — Py3 — Tesla V100" }, { "code": null, "e": 5442, "s": 5428, "text": "60,000 images" }, { "code": null, "e": 5452, "s": 5442, "text": "128 x 128" }, { "code": null, "e": 5467, "s": 5452, "text": "202,599 images" }, { "code": null, "e": 5500, "s": 5467, "text": "Transformed 218 x 178 to 64 x 64" }, { "code": null, "e": 5549, "s": 5500, "text": "Understanding GAN model created using Tensorflow" }, { "code": null, "e": 5593, "s": 5549, "text": "Developing DCGAN model using Tensorflow 2.0" }, { "code": null, "e": 5656, "s": 5593, "text": "Resizing/cropping the dataset images from 218 x 178 to 64 x 64" }, { "code": null, "e": 5720, "s": 5656, "text": "Memory leakage in Jupyter Notebook while training the new model" }, { "code": null, "e": 5766, "s": 5720, "text": "Incompatibilities with TensorFlow 1.3 and 2.0" }, { "code": null, "e": 5804, "s": 5766, "text": "Paperspace auto-shutdown after 12 hrs" }, { "code": null, "e": 5910, "s": 5804, "text": "Migrate the model to an environment which can compute 100 epochs using the CelebA dataset in its entirety" }, { "code": null, "e": 5964, "s": 5910, "text": "Tune the model architecture to generate better images" }, { "code": null, "e": 6021, "s": 5964, "text": "Develop a solution to resize images for more efficiently" }, { "code": null, "e": 6032, "s": 6021, "text": "github.com" }, { "code": null, "e": 6191, "s": 6032, "text": "We couldn’t have completed this project without the great people of the Internet. Please check out the following resources for your next data science project:" }, { "code": null, "e": 6319, "s": 6191, "text": "Unsupervised Representation Learning with Deep Convolutional Generative Adversarial Networks — https://arxiv.org/abs/1511.06434" }, { "code": null, "e": 6401, "s": 6319, "text": "Compressed Sensing using Generative Models — https://arxiv.org/pdf/1703.03208.pdf" } ]
C library function - memcpy()
The C library function void *memcpy(void *dest, const void *src, size_t n) copies n characters from memory area src to memory area dest. Following is the declaration for memcpy() function. void *memcpy(void *dest, const void * src, size_t n) dest − This is pointer to the destination array where the content is to be copied, type-casted to a pointer of type void*. dest − This is pointer to the destination array where the content is to be copied, type-casted to a pointer of type void*. src − This is pointer to the source of data to be copied, type-casted to a pointer of type void*. src − This is pointer to the source of data to be copied, type-casted to a pointer of type void*. n − This is the number of bytes to be copied. n − This is the number of bytes to be copied. This function returns a pointer to destination, which is str1. The following example shows the usage of memcpy() function. #include <stdio.h> #include <string.h> int main () { const char src[50] = "http://www.tutorialspoint.com"; char dest[50]; strcpy(dest,"Heloooo!!"); printf("Before memcpy dest = %s\n", dest); memcpy(dest, src, strlen(src)+1); printf("After memcpy dest = %s\n", dest); return(0); } Let us compile and run the above program that will produce the following result − Before memcpy dest = Heloooo!! After memcpy dest = http://www.tutorialspoint.com 12 Lectures 2 hours Nishant Malik 12 Lectures 2.5 hours Nishant Malik 48 Lectures 6.5 hours Asif Hussain 12 Lectures 2 hours Richa Maheshwari 20 Lectures 3.5 hours Vandana Annavaram 44 Lectures 1 hours Amit Diwan Print Add Notes Bookmark this page
[ { "code": null, "e": 2144, "s": 2007, "text": "The C library function void *memcpy(void *dest, const void *src, size_t n) copies n characters from memory area src to memory area dest." }, { "code": null, "e": 2196, "s": 2144, "text": "Following is the declaration for memcpy() function." }, { "code": null, "e": 2249, "s": 2196, "text": "void *memcpy(void *dest, const void * src, size_t n)" }, { "code": null, "e": 2372, "s": 2249, "text": "dest − This is pointer to the destination array where the content is to be copied, type-casted to a pointer of type void*." }, { "code": null, "e": 2495, "s": 2372, "text": "dest − This is pointer to the destination array where the content is to be copied, type-casted to a pointer of type void*." }, { "code": null, "e": 2593, "s": 2495, "text": "src − This is pointer to the source of data to be copied, type-casted to a pointer of type void*." }, { "code": null, "e": 2691, "s": 2593, "text": "src − This is pointer to the source of data to be copied, type-casted to a pointer of type void*." }, { "code": null, "e": 2737, "s": 2691, "text": "n − This is the number of bytes to be copied." }, { "code": null, "e": 2783, "s": 2737, "text": "n − This is the number of bytes to be copied." }, { "code": null, "e": 2846, "s": 2783, "text": "This function returns a pointer to destination, which is str1." }, { "code": null, "e": 2906, "s": 2846, "text": "The following example shows the usage of memcpy() function." }, { "code": null, "e": 3212, "s": 2906, "text": "#include <stdio.h>\n#include <string.h>\n\nint main () {\n const char src[50] = \"http://www.tutorialspoint.com\";\n char dest[50];\n strcpy(dest,\"Heloooo!!\");\n printf(\"Before memcpy dest = %s\\n\", dest);\n memcpy(dest, src, strlen(src)+1);\n printf(\"After memcpy dest = %s\\n\", dest);\n \n return(0);\n}" }, { "code": null, "e": 3294, "s": 3212, "text": "Let us compile and run the above program that will produce the following result −" }, { "code": null, "e": 3376, "s": 3294, "text": "Before memcpy dest = Heloooo!!\nAfter memcpy dest = http://www.tutorialspoint.com\n" }, { "code": null, "e": 3409, "s": 3376, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3424, "s": 3409, "text": " Nishant Malik" }, { "code": null, "e": 3459, "s": 3424, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3474, "s": 3459, "text": " Nishant Malik" }, { "code": null, "e": 3509, "s": 3474, "text": "\n 48 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3523, "s": 3509, "text": " Asif Hussain" }, { "code": null, "e": 3556, "s": 3523, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3574, "s": 3556, "text": " Richa Maheshwari" }, { "code": null, "e": 3609, "s": 3574, "text": "\n 20 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3628, "s": 3609, "text": " Vandana Annavaram" }, { "code": null, "e": 3661, "s": 3628, "text": "\n 44 Lectures \n 1 hours \n" }, { "code": null, "e": 3673, "s": 3661, "text": " Amit Diwan" }, { "code": null, "e": 3680, "s": 3673, "text": " Print" }, { "code": null, "e": 3691, "s": 3680, "text": " Add Notes" } ]
AWS Lambda – Configuring Lambda Function
In the previous chapters, we have learnt how to create AWS Lambda function in AWS console. However, there are other parameters for creating a Lambda function. These include memory allocation, timeout etc. In this chapter, let us understand in detail about the following configuration properties for AWS Lambda. Login to AWS console and create or select the existing lambda function. Click the Configuration tab to get the details of the memory allocated. Look at the screenshot shown below − Note that by default the memory allocated is 128MB. If you want to increase the memory you can click the slider. The memory will get incremented to 64MB as you move the slider. Observe that the maximum memory available is 3008MB. Look at the screenshot shown below − You can also use aws cli from command prompt to increase the memory limit. You will have to give the memory in increments of 64MB. Now, let us increase the memory limit of AWS Lambda with name :myfirstlambdafunction. The memory details of the function are shown in the screenshot given below − The command used to change the memory using aws cli is as follows − aws lambda update-function-configuration --function-name your function name -- region region where your function resides --memory-size memory amount -- profile admin user The corresponding output of AWS Lambda function myfirstlambdafunction in AWS console is shown here. Observe that the memory is changed from 128MB to 256MB. Timeout is the time allotted to AWS Lambda function to terminate if the timeout happens. AWS Lambda function will either run within the allocated time or terminate if it exceeds the timeout given. You need to evaluate the time required for the function to execute and accordingly select the time in Configuration tab in AWS console as shown below − When creating AWS Lambda function, the role or the permission needs to be assigned. Incase you need AWS Lambda for S3 or dynamoDB, permission with regard to the services of lambda needs to be assigned. Based on the role assigned, AWS Lambda will decide the steps to be taken. For Example if you give full access of dynamodb, you can add, update and delete the rows from the dynamodb table. This is the start of execution of the AWS Lambda function. Handler function has the details of the event triggered, context object and the callback which has to send back on success or error of AWS Lambda. The format of the handler function in nodejs is shown here − exports.handler = (event, context, callback) => { callback(null, "hello from lambda"); }; In this section, we will create a simple Lambda function using environment variables added in the configuration section. For this purpose, follow the steps given below and refer the respective screenshots − Go to AWS console and create a function in Lambda as shown. Now, add the environment variables as shown − Now, let us fetch the same in Lambda code as follows − exports.handler = (event, context, callback) => { var hostName = process.env.host; var userName = process.env.username; callback(null, "Environment Variables =>"+hostName+" and "+userName); }; To get the details from environment variables we need to use process.env as shown. Note that this syntax is for NodeJS runtime. var hostName = process.env.host; var userName = process.env.username; The output for the Lambda function on execution will be as shown − 35 Lectures 7.5 hours Mr. Pradeep Kshetrapal 30 Lectures 3.5 hours Priyanka Choudhary 44 Lectures 7.5 hours Eduonix Learning Solutions 51 Lectures 6 hours Manuj Aggarwal 41 Lectures 5 hours AR Shankar 14 Lectures 1 hours Zach Miller Print Add Notes Bookmark this page
[ { "code": null, "e": 2611, "s": 2406, "text": "In the previous chapters, we have learnt how to create AWS Lambda function in AWS console. However, there are other parameters for creating a Lambda function. These include memory allocation, timeout etc." }, { "code": null, "e": 2717, "s": 2611, "text": "In this chapter, let us understand in detail about the following configuration properties for AWS Lambda." }, { "code": null, "e": 2898, "s": 2717, "text": "Login to AWS console and create or select the existing lambda function. Click the Configuration tab to get the details of the memory allocated. Look at the screenshot shown below −" }, { "code": null, "e": 3011, "s": 2898, "text": "Note that by default the memory allocated is 128MB. If you want to increase the memory you can click the slider." }, { "code": null, "e": 3165, "s": 3011, "text": "The memory will get incremented to 64MB as you move the slider. Observe that the maximum memory available is 3008MB. Look at the screenshot shown below −" }, { "code": null, "e": 3296, "s": 3165, "text": "You can also use aws cli from command prompt to increase the memory limit. You will have to give the memory in increments of 64MB." }, { "code": null, "e": 3382, "s": 3296, "text": "Now, let us increase the memory limit of AWS Lambda with name :myfirstlambdafunction." }, { "code": null, "e": 3459, "s": 3382, "text": "The memory details of the function are shown in the screenshot given below −" }, { "code": null, "e": 3527, "s": 3459, "text": "The command used to change the memory using aws cli is as follows −" }, { "code": null, "e": 3699, "s": 3527, "text": "aws lambda update-function-configuration --function-name your function name --\nregion region where your function resides --memory-size memory amount --\nprofile admin user\n" }, { "code": null, "e": 3855, "s": 3699, "text": "The corresponding output of AWS Lambda function myfirstlambdafunction in AWS console is shown here. Observe that the memory is changed from 128MB to 256MB." }, { "code": null, "e": 4204, "s": 3855, "text": "Timeout is the time allotted to AWS Lambda function to terminate if the timeout happens. AWS Lambda function will either run within the allocated time or terminate if it exceeds the timeout given. You need to evaluate the time required for the function to execute and accordingly select the time in Configuration tab in AWS console as shown below −" }, { "code": null, "e": 4594, "s": 4204, "text": "When creating AWS Lambda function, the role or the permission needs to be assigned. Incase you need AWS Lambda for S3 or dynamoDB, permission with regard to the services of lambda needs to be assigned. Based on the role assigned, AWS Lambda will decide the steps to be taken. For Example if you give full access of dynamodb, you can add, update and delete the rows from the dynamodb table." }, { "code": null, "e": 4800, "s": 4594, "text": "This is the start of execution of the AWS Lambda function. Handler function has the details of the event triggered, context object and the callback which has to send back on success or error of AWS Lambda." }, { "code": null, "e": 4861, "s": 4800, "text": "The format of the handler function in nodejs is shown here −" }, { "code": null, "e": 4954, "s": 4861, "text": "exports.handler = (event, context, callback) => {\n callback(null, \"hello from lambda\");\n};" }, { "code": null, "e": 5161, "s": 4954, "text": "In this section, we will create a simple Lambda function using environment variables added in the configuration section. For this purpose, follow the steps given below and refer the respective screenshots −" }, { "code": null, "e": 5221, "s": 5161, "text": "Go to AWS console and create a function in Lambda as shown." }, { "code": null, "e": 5267, "s": 5221, "text": "Now, add the environment variables as shown −" }, { "code": null, "e": 5322, "s": 5267, "text": "Now, let us fetch the same in Lambda code as follows −" }, { "code": null, "e": 5527, "s": 5322, "text": "exports.handler = (event, context, callback) => {\n var hostName = process.env.host; \n var userName = process.env.username;\n callback(null, \"Environment Variables =>\"+hostName+\" and \"+userName);\n};" }, { "code": null, "e": 5655, "s": 5527, "text": "To get the details from environment variables we need to use process.env as shown. Note that this syntax is for NodeJS runtime." }, { "code": null, "e": 5729, "s": 5655, "text": "var hostName = process.env.host; \nvar userName = process.env.username;\n" }, { "code": null, "e": 5796, "s": 5729, "text": "The output for the Lambda function on execution will be as shown −" }, { "code": null, "e": 5831, "s": 5796, "text": "\n 35 Lectures \n 7.5 hours \n" }, { "code": null, "e": 5855, "s": 5831, "text": " Mr. Pradeep Kshetrapal" }, { "code": null, "e": 5890, "s": 5855, "text": "\n 30 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5910, "s": 5890, "text": " Priyanka Choudhary" }, { "code": null, "e": 5945, "s": 5910, "text": "\n 44 Lectures \n 7.5 hours \n" }, { "code": null, "e": 5973, "s": 5945, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 6006, "s": 5973, "text": "\n 51 Lectures \n 6 hours \n" }, { "code": null, "e": 6022, "s": 6006, "text": " Manuj Aggarwal" }, { "code": null, "e": 6055, "s": 6022, "text": "\n 41 Lectures \n 5 hours \n" }, { "code": null, "e": 6067, "s": 6055, "text": " AR Shankar" }, { "code": null, "e": 6100, "s": 6067, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 6113, "s": 6100, "text": " Zach Miller" }, { "code": null, "e": 6120, "s": 6113, "text": " Print" }, { "code": null, "e": 6131, "s": 6120, "text": " Add Notes" } ]
How to Fix: runtimewarning: invalid value encountered in double_scalars
18 Feb, 2022 In this article, we will discuss how to fix runtimewarning: invalid value encountered in double_scalars using Python. The error which we basically encounter when we use the Numpy library is Runtimewarning: invalid value encountered in doubled_scalars. We face this error basically when we do mathematical operations on a list of very large numbers or vary the small number and when we supply any invalid input to NumPy operation like NaN or null as input. This error simply occurs when we performing a math operation and we encounter which is not valid as input. When we perform some complex mathematical operation that requires a very large number or vary small number some libraries cannot handle such a large number so it throws an error. It turns these numbers to null or NaN which causes an error in operation. The easiest way to prevent this error is to use the function which is able to handle that big number so the operation cannot throw an error. Or in place or complex mathematical function use built-in function so we avoid human error. We can do some mathematical change in operation so the value should not rise above value so it can’t raise an error. Here we will see some examples which raise the error and see some solutions. Program to show error code Python # In this program we are demonstrating how wrong# input course invalid value# encountered in double_scalarsimport numpy array1 = [1, 2, 4, 7, 8] # this input array causes errorarray2 = [] Marray1 = numpy.mean(array1)# this line causes the errorMarray2 = numpy.mean(array2) print(Marray1)print(Marray2) Output: RuntimeWarning: Mean of empty slice. RuntimeWarning: invalid value encountered in double_scalars We can fix this error if we check the array before calculating the mean of the array that it providing the valid input of not: Syntax: if array1: expression; In this program, we are demonstrating how wrong input course invalid value encountered in double_scalars Python import numpy array1 = [1, 2, 4, 7, 8] # this input array causes errorarray2 = [] # Here we check errorif array1 and array2: print("Mean of the array 1 is : ", numpy.mean(array1)) print("Mean of the array is :", numpy.mean(array2))else: print("please Enter valid array") Output: please Enter valid array Python program showing invalid error encounter in double scaler. Python import numpy as npfrom numpy import sinh x = 900y = 711 # This operation raise errorsol1 = np.log(np.sum(np.exp(x)))/np.log(np.sum(np.exp(y))) print(sol1) Output: main.py:14: RuntimeWarning: overflow encountered in exp sol1 = np.log(np.sum(np.exp(x)))/np.log(np.sum(np.exp(y))); main.py:14: RuntimeWarning: invalid value encountered in double_scalars sol1 = np.log(np.sum(np.exp(x)))/np.log(np.sum(np.exp(y))); nan Here we have seen that error cause this because NumPy library cannot handle this large number on so complex a structure so we have to use some built-in function that can handle small numbers. For this purpose, we use numpy.special.logsumexp function which is use for calculating the value for expression “np.log(np.sum(np.exp(x)))” : Syntax: numpy.special.logsumexp(x); Example: Fixed code Python # Python program showing# invalid error encounter in double scaler import numpy as npfrom scipy.special import logsumexp x = 900y = 711 # Solution of the error with the# help of built-in functionsol1 = logsumexp(x) - logsumexp(y) # sol1 = np.log(np.sum(np.exp(x)))/np.log(np.sum(np.exp(y)))print("Now we can print our Answer :")print(sol1) Output: Now we can print our Answer : 189.0 adnanirshad158 germanshephered48 kk9826225 Picked Python How-to-fix 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 ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Check if element exists in list in Python Python | os.path.join() method How To Convert Python Dictionary To JSON? Python | Get unique values from a list Defaultdict in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Feb, 2022" }, { "code": null, "e": 146, "s": 28, "text": "In this article, we will discuss how to fix runtimewarning: invalid value encountered in double_scalars using Python." }, { "code": null, "e": 489, "s": 146, "text": "The error which we basically encounter when we use the Numpy library is Runtimewarning: invalid value encountered in doubled_scalars. We face this error basically when we do mathematical operations on a list of very large numbers or vary the small number and when we supply any invalid input to NumPy operation like NaN or null as input. " }, { "code": null, "e": 851, "s": 489, "text": "This error simply occurs when we performing a math operation and we encounter which is not valid as input. When we perform some complex mathematical operation that requires a very large number or vary small number some libraries cannot handle such a large number so it throws an error. It turns these numbers to null or NaN which causes an error in operation. " }, { "code": null, "e": 992, "s": 851, "text": "The easiest way to prevent this error is to use the function which is able to handle that big number so the operation cannot throw an error." }, { "code": null, "e": 1084, "s": 992, "text": "Or in place or complex mathematical function use built-in function so we avoid human error." }, { "code": null, "e": 1201, "s": 1084, "text": "We can do some mathematical change in operation so the value should not rise above value so it can’t raise an error." }, { "code": null, "e": 1278, "s": 1201, "text": "Here we will see some examples which raise the error and see some solutions." }, { "code": null, "e": 1306, "s": 1278, "text": "Program to show error code " }, { "code": null, "e": 1313, "s": 1306, "text": "Python" }, { "code": "# In this program we are demonstrating how wrong# input course invalid value# encountered in double_scalarsimport numpy array1 = [1, 2, 4, 7, 8] # this input array causes errorarray2 = [] Marray1 = numpy.mean(array1)# this line causes the errorMarray2 = numpy.mean(array2) print(Marray1)print(Marray2)", "e": 1616, "s": 1313, "text": null }, { "code": null, "e": 1624, "s": 1616, "text": "Output:" }, { "code": null, "e": 1662, "s": 1624, "text": " RuntimeWarning: Mean of empty slice." }, { "code": null, "e": 1723, "s": 1662, "text": " RuntimeWarning: invalid value encountered in double_scalars" }, { "code": null, "e": 1850, "s": 1723, "text": "We can fix this error if we check the array before calculating the mean of the array that it providing the valid input of not:" }, { "code": null, "e": 1858, "s": 1850, "text": "Syntax:" }, { "code": null, "e": 1869, "s": 1858, "text": "if array1:" }, { "code": null, "e": 1884, "s": 1869, "text": " expression;" }, { "code": null, "e": 1989, "s": 1884, "text": "In this program, we are demonstrating how wrong input course invalid value encountered in double_scalars" }, { "code": null, "e": 1996, "s": 1989, "text": "Python" }, { "code": "import numpy array1 = [1, 2, 4, 7, 8] # this input array causes errorarray2 = [] # Here we check errorif array1 and array2: print(\"Mean of the array 1 is : \", numpy.mean(array1)) print(\"Mean of the array is :\", numpy.mean(array2))else: print(\"please Enter valid array\")", "e": 2275, "s": 1996, "text": null }, { "code": null, "e": 2283, "s": 2275, "text": "Output:" }, { "code": null, "e": 2308, "s": 2283, "text": "please Enter valid array" }, { "code": null, "e": 2373, "s": 2308, "text": "Python program showing invalid error encounter in double scaler." }, { "code": null, "e": 2380, "s": 2373, "text": "Python" }, { "code": "import numpy as npfrom numpy import sinh x = 900y = 711 # This operation raise errorsol1 = np.log(np.sum(np.exp(x)))/np.log(np.sum(np.exp(y))) print(sol1)", "e": 2536, "s": 2380, "text": null }, { "code": null, "e": 2544, "s": 2536, "text": "Output:" }, { "code": null, "e": 2600, "s": 2544, "text": "main.py:14: RuntimeWarning: overflow encountered in exp" }, { "code": null, "e": 2660, "s": 2600, "text": "sol1 = np.log(np.sum(np.exp(x)))/np.log(np.sum(np.exp(y)));" }, { "code": null, "e": 2732, "s": 2660, "text": "main.py:14: RuntimeWarning: invalid value encountered in double_scalars" }, { "code": null, "e": 2792, "s": 2732, "text": "sol1 = np.log(np.sum(np.exp(x)))/np.log(np.sum(np.exp(y)));" }, { "code": null, "e": 2796, "s": 2792, "text": "nan" }, { "code": null, "e": 3130, "s": 2796, "text": "Here we have seen that error cause this because NumPy library cannot handle this large number on so complex a structure so we have to use some built-in function that can handle small numbers. For this purpose, we use numpy.special.logsumexp function which is use for calculating the value for expression “np.log(np.sum(np.exp(x)))” :" }, { "code": null, "e": 3166, "s": 3130, "text": "Syntax: numpy.special.logsumexp(x);" }, { "code": null, "e": 3186, "s": 3166, "text": "Example: Fixed code" }, { "code": null, "e": 3193, "s": 3186, "text": "Python" }, { "code": "# Python program showing# invalid error encounter in double scaler import numpy as npfrom scipy.special import logsumexp x = 900y = 711 # Solution of the error with the# help of built-in functionsol1 = logsumexp(x) - logsumexp(y) # sol1 = np.log(np.sum(np.exp(x)))/np.log(np.sum(np.exp(y)))print(\"Now we can print our Answer :\")print(sol1)", "e": 3534, "s": 3193, "text": null }, { "code": null, "e": 3542, "s": 3534, "text": "Output:" }, { "code": null, "e": 3578, "s": 3542, "text": "Now we can print our Answer :\n189.0" }, { "code": null, "e": 3593, "s": 3578, "text": "adnanirshad158" }, { "code": null, "e": 3611, "s": 3593, "text": "germanshephered48" }, { "code": null, "e": 3621, "s": 3611, "text": "kk9826225" }, { "code": null, "e": 3628, "s": 3621, "text": "Picked" }, { "code": null, "e": 3646, "s": 3628, "text": "Python How-to-fix" }, { "code": null, "e": 3659, "s": 3646, "text": "Python-numpy" }, { "code": null, "e": 3666, "s": 3659, "text": "Python" }, { "code": null, "e": 3764, "s": 3666, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3796, "s": 3764, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3823, "s": 3796, "text": "Python Classes and Objects" }, { "code": null, "e": 3844, "s": 3823, "text": "Python OOPs Concepts" }, { "code": null, "e": 3867, "s": 3844, "text": "Introduction To PYTHON" }, { "code": null, "e": 3923, "s": 3867, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 3965, "s": 3923, "text": "Check if element exists in list in Python" }, { "code": null, "e": 3996, "s": 3965, "text": "Python | os.path.join() method" }, { "code": null, "e": 4038, "s": 3996, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 4077, "s": 4038, "text": "Python | Get unique values from a list" } ]
How to check if a jQuery plugin is loaded?
02 Jun, 2020 There are multiple ways by which we can simply check whether the jQuery plugins are loaded successfully or not using jQuery. We can also check whether a particular function within the plugin is accessible or not. This tutorial will demonstrate how to check if a jQuery plugin is loaded or not. Step 1: Install Browsersync using npm. We will use Browsersync to start a server and provide a URL to view the HTML site and to load jQuery using CDN (Content Delivery Network). We will install Browsersync globally.npm install -g browser-sync npm install -g browser-sync Step 2: We will be using jQuery-UI plugin for this tutorial. We will test whether this plugin is successfully loaded or not using jQuery. Download the latest version of this plugin and extract it to your project root folder. Step 3: Create a index.html fileExample 1: The jQuery plugins are namespaces on the jQuery scope. The jquery-ui plugin does not extend the fn namespace, hence we can check if the plugin is loaded successfully by using the above code. ui represents the name of the plugin and can be replaced with the plugin name to be checked. We have loaded jQuery in the head tag because it needs to be available before it can be used in the application. It is recommended practice to load all JavaScript files at the end of the body tag for increasing performance and render the page faster. Hence, we have used the $(document).ready() function before we can check if the plugin was loaded successfully or not. The typeof operator returns the data type of its operand in the form of a string. In this case, the operand is the jQuery $ operator itself.htmlhtml<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>JQuery Plugin</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script></head><body> <div>Hello GeeksForGeeks</div> <script type="text/javascript"> $(document).ready(function () { if (typeof $.ui !== 'undefined') { console.log('jquery-ui is loaded successfully') } }); </script> <script src="jquery-ui-1.12.1/jquery-ui.js" type="text/javascript"></script></body></html>Example 2: Since every plugin is guaranteed to have some function definitions or values that equate to true, we can use the shorter version as shown in the code.JavascriptJavascriptif ($.ui) { console.log('jquery-ui is loaded successfully')}Note: For all the jQuery plugins that do extend the fn namespace, the correct way to check is:JavascriptJavascript<script type="text/javascript">$(document).ready(function () { if (typeof $.fn.pluginname !== 'undefined') { console.log('jquery-ui is loaded - 2') } if ($.fn.pluginname) { console.log('jquery-ui is loaded - 3') }});</script>The $.fn.pluginname extends the jQuery objects and is a function callable on all jQuery.init objects whereas the $.pluginname extends the $ object itself. html <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>JQuery Plugin</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script></head><body> <div>Hello GeeksForGeeks</div> <script type="text/javascript"> $(document).ready(function () { if (typeof $.ui !== 'undefined') { console.log('jquery-ui is loaded successfully') } }); </script> <script src="jquery-ui-1.12.1/jquery-ui.js" type="text/javascript"></script></body></html> Example 2: Since every plugin is guaranteed to have some function definitions or values that equate to true, we can use the shorter version as shown in the code. Javascript if ($.ui) { console.log('jquery-ui is loaded successfully')} Note: For all the jQuery plugins that do extend the fn namespace, the correct way to check is: Javascript <script type="text/javascript">$(document).ready(function () { if (typeof $.fn.pluginname !== 'undefined') { console.log('jquery-ui is loaded - 2') } if ($.fn.pluginname) { console.log('jquery-ui is loaded - 3') }});</script> The $.fn.pluginname extends the jQuery objects and is a function callable on all jQuery.init objects whereas the $.pluginname extends the $ object itself. Step 4: We will now check if the plugin functions are accessible or not. This automatically signifies that the plugin itself has loaded successfully.index.htmlJavascriptJavascript<input type="text" name="date" id="date"><script type="text/javascript"> $(document).ready(function () { if (jQuery().datepicker()) { console.log('jquery-ui datepicker() function is accessible') } if (typeof $.fn.datepicker() !== 'undefined') { console.log('jquery-ui datepicker() function is accessible') } if ($.fn.datepicker()) { console.log('jquery-ui datepicker() function is accessible') } $("#date").datepicker(); });</script>Note: The jQuery function jQuery() returns a new jQuery.init object. The jQuery() is also replacable with the $() operator in most cases. Javascript <input type="text" name="date" id="date"><script type="text/javascript"> $(document).ready(function () { if (jQuery().datepicker()) { console.log('jquery-ui datepicker() function is accessible') } if (typeof $.fn.datepicker() !== 'undefined') { console.log('jquery-ui datepicker() function is accessible') } if ($.fn.datepicker()) { console.log('jquery-ui datepicker() function is accessible') } $("#date").datepicker(); });</script> Note: The jQuery function jQuery() returns a new jQuery.init object. The jQuery() is also replacable with the $() operator in most cases. Step 5: To launch the application using Browsersync, run the following command in the project directory:browser-sync start --server --files "*"This starts Browsersync in server mode and watches all the files within the directory for changes as specified by the * wildcard. The application will be launched at http://localhost:3000/ by default.Output: browser-sync start --server --files "*" This starts Browsersync in server mode and watches all the files within the directory for changes as specified by the * wildcard. The application will be launched at http://localhost:3000/ by default.Output: jQuery-Plugin Picked JQuery Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Form validation using jQuery jQuery | children() with Examples Scroll to the top of the page using JavaScript/jQuery How to Dynamically Add/Remove Table Rows using jQuery ? How to get the value in an input text box using jQuery ? Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Jun, 2020" }, { "code": null, "e": 324, "s": 28, "text": "There are multiple ways by which we can simply check whether the jQuery plugins are loaded successfully or not using jQuery. We can also check whether a particular function within the plugin is accessible or not. This tutorial will demonstrate how to check if a jQuery plugin is loaded or not. " }, { "code": null, "e": 567, "s": 324, "text": "Step 1: Install Browsersync using npm. We will use Browsersync to start a server and provide a URL to view the HTML site and to load jQuery using CDN (Content Delivery Network). We will install Browsersync globally.npm install -g browser-sync" }, { "code": null, "e": 595, "s": 567, "text": "npm install -g browser-sync" }, { "code": null, "e": 820, "s": 595, "text": "Step 2: We will be using jQuery-UI plugin for this tutorial. We will test whether this plugin is successfully loaded or not using jQuery. Download the latest version of this plugin and extract it to your project root folder." }, { "code": null, "e": 3002, "s": 820, "text": "Step 3: Create a index.html fileExample 1: The jQuery plugins are namespaces on the jQuery scope. The jquery-ui plugin does not extend the fn namespace, hence we can check if the plugin is loaded successfully by using the above code. ui represents the name of the plugin and can be replaced with the plugin name to be checked. We have loaded jQuery in the head tag because it needs to be available before it can be used in the application. It is recommended practice to load all JavaScript files at the end of the body tag for increasing performance and render the page faster. Hence, we have used the $(document).ready() function before we can check if the plugin was loaded successfully or not. The typeof operator returns the data type of its operand in the form of a string. In this case, the operand is the jQuery $ operator itself.htmlhtml<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <title>JQuery Plugin</title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"> </script></head><body> <div>Hello GeeksForGeeks</div> <script type=\"text/javascript\"> $(document).ready(function () { if (typeof $.ui !== 'undefined') { console.log('jquery-ui is loaded successfully') } }); </script> <script src=\"jquery-ui-1.12.1/jquery-ui.js\" type=\"text/javascript\"></script></body></html>Example 2: Since every plugin is guaranteed to have some function definitions or values that equate to true, we can use the shorter version as shown in the code.JavascriptJavascriptif ($.ui) { console.log('jquery-ui is loaded successfully')}Note: For all the jQuery plugins that do extend the fn namespace, the correct way to check is:JavascriptJavascript<script type=\"text/javascript\">$(document).ready(function () { if (typeof $.fn.pluginname !== 'undefined') { console.log('jquery-ui is loaded - 2') } if ($.fn.pluginname) { console.log('jquery-ui is loaded - 3') }});</script>The $.fn.pluginname extends the jQuery objects and is a function callable on all jQuery.init objects whereas the $.pluginname extends the $ object itself." }, { "code": null, "e": 3007, "s": 3002, "text": "html" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <title>JQuery Plugin</title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"> </script></head><body> <div>Hello GeeksForGeeks</div> <script type=\"text/javascript\"> $(document).ready(function () { if (typeof $.ui !== 'undefined') { console.log('jquery-ui is loaded successfully') } }); </script> <script src=\"jquery-ui-1.12.1/jquery-ui.js\" type=\"text/javascript\"></script></body></html>", "e": 3581, "s": 3007, "text": null }, { "code": null, "e": 3743, "s": 3581, "text": "Example 2: Since every plugin is guaranteed to have some function definitions or values that equate to true, we can use the shorter version as shown in the code." }, { "code": null, "e": 3754, "s": 3743, "text": "Javascript" }, { "code": "if ($.ui) { console.log('jquery-ui is loaded successfully')}", "e": 3818, "s": 3754, "text": null }, { "code": null, "e": 3913, "s": 3818, "text": "Note: For all the jQuery plugins that do extend the fn namespace, the correct way to check is:" }, { "code": null, "e": 3924, "s": 3913, "text": "Javascript" }, { "code": "<script type=\"text/javascript\">$(document).ready(function () { if (typeof $.fn.pluginname !== 'undefined') { console.log('jquery-ui is loaded - 2') } if ($.fn.pluginname) { console.log('jquery-ui is loaded - 3') }});</script>", "e": 4176, "s": 3924, "text": null }, { "code": null, "e": 4331, "s": 4176, "text": "The $.fn.pluginname extends the jQuery objects and is a function callable on all jQuery.init objects whereas the $.pluginname extends the $ object itself." }, { "code": null, "e": 5159, "s": 4331, "text": "Step 4: We will now check if the plugin functions are accessible or not. This automatically signifies that the plugin itself has loaded successfully.index.htmlJavascriptJavascript<input type=\"text\" name=\"date\" id=\"date\"><script type=\"text/javascript\"> $(document).ready(function () { if (jQuery().datepicker()) { console.log('jquery-ui datepicker() function is accessible') } if (typeof $.fn.datepicker() !== 'undefined') { console.log('jquery-ui datepicker() function is accessible') } if ($.fn.datepicker()) { console.log('jquery-ui datepicker() function is accessible') } $(\"#date\").datepicker(); });</script>Note: The jQuery function jQuery() returns a new jQuery.init object. The jQuery() is also replacable with the $() operator in most cases." }, { "code": null, "e": 5170, "s": 5159, "text": "Javascript" }, { "code": "<input type=\"text\" name=\"date\" id=\"date\"><script type=\"text/javascript\"> $(document).ready(function () { if (jQuery().datepicker()) { console.log('jquery-ui datepicker() function is accessible') } if (typeof $.fn.datepicker() !== 'undefined') { console.log('jquery-ui datepicker() function is accessible') } if ($.fn.datepicker()) { console.log('jquery-ui datepicker() function is accessible') } $(\"#date\").datepicker(); });</script>", "e": 5682, "s": 5170, "text": null }, { "code": null, "e": 5820, "s": 5682, "text": "Note: The jQuery function jQuery() returns a new jQuery.init object. The jQuery() is also replacable with the $() operator in most cases." }, { "code": null, "e": 6171, "s": 5820, "text": "Step 5: To launch the application using Browsersync, run the following command in the project directory:browser-sync start --server --files \"*\"This starts Browsersync in server mode and watches all the files within the directory for changes as specified by the * wildcard. The application will be launched at http://localhost:3000/ by default.Output:" }, { "code": null, "e": 6211, "s": 6171, "text": "browser-sync start --server --files \"*\"" }, { "code": null, "e": 6419, "s": 6211, "text": "This starts Browsersync in server mode and watches all the files within the directory for changes as specified by the * wildcard. The application will be launched at http://localhost:3000/ by default.Output:" }, { "code": null, "e": 6433, "s": 6419, "text": "jQuery-Plugin" }, { "code": null, "e": 6440, "s": 6433, "text": "Picked" }, { "code": null, "e": 6447, "s": 6440, "text": "JQuery" }, { "code": null, "e": 6464, "s": 6447, "text": "Web Technologies" }, { "code": null, "e": 6491, "s": 6464, "text": "Web technologies Questions" }, { "code": null, "e": 6589, "s": 6491, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6618, "s": 6589, "text": "Form validation using jQuery" }, { "code": null, "e": 6652, "s": 6618, "text": "jQuery | children() with Examples" }, { "code": null, "e": 6706, "s": 6652, "text": "Scroll to the top of the page using JavaScript/jQuery" }, { "code": null, "e": 6762, "s": 6706, "text": "How to Dynamically Add/Remove Table Rows using jQuery ?" }, { "code": null, "e": 6819, "s": 6762, "text": "How to get the value in an input text box using jQuery ?" }, { "code": null, "e": 6881, "s": 6819, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 6914, "s": 6881, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 6975, "s": 6914, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 7025, "s": 6975, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
ListView Class in Flutter
10 Nov, 2021 In Flutter, ListView is a scrollable list of widgets arranged linearly. It displays its children one after another in the scroll direction i.e, vertical or horizontal. There are different types of ListViews : ListView ListView.builder ListView.separated ListView.custom ListView( {Key key, Axis scrollDirection: Axis.vertical, bool reverse: false, ScrollController controller, bool primary, ScrollPhysics physics, bool shrinkWrap: false, EdgeInsetsGeometry padding, double itemExtent, bool addAutomaticKeepAlives: true, bool addRepaintBoundaries: true, bool addSemanticIndexes: true, double cacheExtent, List<Widget> children: const <Widget>[], int semanticChildCount, DragStartBehavior dragStartBehavior: DragStartBehavior.start, ScrollViewKeyboardDismissBehavior keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.manual, String restorationId, Clip clipBehavior: Clip.hardEdge} ) ListView.builder( {Key key, Axis scrollDirection: Axis.vertical, bool reverse: false, ScrollController controller, bool primary, ScrollPhysics physics, bool shrinkWrap: false, EdgeInsetsGeometry padding, double itemExtent, @required IndexedWidgetBuilder itemBuilder, int itemCount, bool addAutomaticKeepAlives: true, bool addRepaintBoundaries: true, bool addSemanticIndexes: true, double cacheExtent, int semanticChildCount, DragStartBehavior dragStartBehavior: DragStartBehavior.start, ScrollViewKeyboardDismissBehavior keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.manual, String restorationId, Clip clipBehavior: Clip.hardEdge} ) const ListView.custom( {Key key, Axis scrollDirection: Axis.vertical, bool reverse: false, ScrollController controller, bool primary, ScrollPhysics physics, bool shrinkWrap: false, EdgeInsetsGeometry padding, double itemExtent, @required SliverChildDelegate childrenDelegate, double cacheExtent, int semanticChildCount, DragStartBehavior dragStartBehavior: DragStartBehavior.start, ScrollViewKeyboardDismissBehavior keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.manual, String restorationId, Clip clipBehavior: Clip.hardEdge} ) ListView.separated( {Key key, Axis scrollDirection: Axis.vertical, bool reverse: false, ScrollController controller, bool primary, ScrollPhysics physics, bool shrinkWrap: false, EdgeInsetsGeometry padding, @required IndexedWidgetBuilder itemBuilder, @required IndexedWidgetBuilder separatorBuilder, @required int itemCount, bool addAutomaticKeepAlives: true, bool addRepaintBoundaries: true, bool addSemanticIndexes: true, double cacheExtent, DragStartBehavior dragStartBehavior: DragStartBehavior.start, ScrollViewKeyboardDismissBehavior keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.manual, String restorationId, Clip clipBehavior: Clip.hardEdge} ) childrenDelegate: This property takes SliverChildDelegate as the object. It serves as a delegate that provided the children for the ListView. clipBehaviour: This property holds Clip enum (final) as the object. It controls whether the content in the ListView will be clipped or not. itemExtent: The itemExtent takes in a double value as the object to controls the scrollable area in the ListView. padding: It holds EdgeInsetsGeometryI as the object to give space between the Listview and its children. scrollDirection: This property takes in Axis enum as the object to decide the direction of the scroll on the ListView. shrinkWrap: This property takes in a boolean value as the object to decide whether the size of the scrollable area will be determined by the contents inside the ListView. This is the default constructor of the ListView class. A ListView simply takes a list of widgets and makes it scrollable. Usually, this is used with a few children as the List will also construct invisible elements in the list, so numerous widgets may render this inefficiently. Dart ListView( padding: EdgeInsets.all(20), children: <Widget>[ CircleAvatar( maxRadius: 50, backgroundColor: Colors.black, child: Icon(Icons.person, color: Colors.white, size: 50), ), Center( child: Text( 'Sooraj S Nair', style: TextStyle( fontSize: 50, ), ), ), Text( "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a gallery of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum,It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).", style: TextStyle( fontSize: 20, ), ), ], ), Output: The builder() constructor constructs a repeating list of widgets. The constructor takes two main parameters: An itemCount for the number of repetitions for the widget to be constructed (not compulsory). An itemBuilder for constructing the widget which will be generated ‘itemCount‘ times (compulsory). If the itemCount is not specified, infinite widgets will be constructed by default. Dart ListView.builder( itemCount: 20, itemBuilder: (context, position) { return Card( child: Padding( padding: const EdgeInsets.all(20.0), child: Text( position.toString(), style: TextStyle(fontSize: 22.0), ), ), ); }, ), Output: The ListView.separated() constructor is used to generate a list of widgets, but in addition, a separator widget can also be generated to separate the widgets. In short, these are two intertwined list of widgets: the main list and the separator list. Unlike the builder() constructor, the itemCount parameter is compulsory here. Dart ListView.separated( itemBuilder: (context, position) { return Card( child: Padding( padding: const EdgeInsets.all(15.0), child: Text( 'List Item $position', ), ), ); }, separatorBuilder: (context, position) { return Card( color: Colors.grey, child: Padding( padding: const EdgeInsets.all(5.0), child: Text( 'Separator $position', style: TextStyle(color: Colors.white), ), ), ); }, itemCount: 20, ), Output: As the name suggests, the ListView.custom() constructor lets us build ListViews with custom functionality for how the children of the list are built. The main parameter of this constructor is a SliverChildDelegate which builds the items. The types of SliverChildDelegates are : SliverChildListDelegate SliverChildBuilderDelegate The SliverChildListDelegate accepts a list of children widgets. whereas the SliverChildBuilderDelegate accepts an IndexedWidgetBuilder, simply a builder() function. Digging deeper, we can infer that ListView.builder was created using a ListView.custom with a SliverChildBuilderDelegate. Also, the default ListView() constructor is a ListView.custom with a SliverChildListDelegate. ankit_kumar_ varshagumber28 kalrap615 Flutter Dart Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n10 Nov, 2021" }, { "code": null, "e": 220, "s": 52, "text": "In Flutter, ListView is a scrollable list of widgets arranged linearly. It displays its children one after another in the scroll direction i.e, vertical or horizontal." }, { "code": null, "e": 261, "s": 220, "text": "There are different types of ListViews :" }, { "code": null, "e": 270, "s": 261, "text": "ListView" }, { "code": null, "e": 287, "s": 270, "text": "ListView.builder" }, { "code": null, "e": 306, "s": 287, "text": "ListView.separated" }, { "code": null, "e": 322, "s": 306, "text": "ListView.custom" }, { "code": null, "e": 942, "s": 322, "text": "ListView(\n{Key key,\nAxis scrollDirection: Axis.vertical,\nbool reverse: false,\nScrollController controller,\nbool primary,\nScrollPhysics physics,\nbool shrinkWrap: false,\nEdgeInsetsGeometry padding,\ndouble itemExtent,\nbool addAutomaticKeepAlives: true,\nbool addRepaintBoundaries: true,\nbool addSemanticIndexes: true,\ndouble cacheExtent,\nList<Widget> children: const <Widget>[],\nint semanticChildCount,\nDragStartBehavior dragStartBehavior: DragStartBehavior.start,\nScrollViewKeyboardDismissBehavior keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.manual,\nString restorationId,\nClip clipBehavior: Clip.hardEdge}\n)" }, { "code": null, "e": 1588, "s": 942, "text": "ListView.builder(\n{Key key,\nAxis scrollDirection: Axis.vertical,\nbool reverse: false,\nScrollController controller,\nbool primary,\nScrollPhysics physics,\nbool shrinkWrap: false,\nEdgeInsetsGeometry padding,\ndouble itemExtent,\n@required IndexedWidgetBuilder itemBuilder,\nint itemCount,\nbool addAutomaticKeepAlives: true,\nbool addRepaintBoundaries: true,\nbool addSemanticIndexes: true,\ndouble cacheExtent,\nint semanticChildCount,\nDragStartBehavior dragStartBehavior: DragStartBehavior.start,\nScrollViewKeyboardDismissBehavior keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.manual,\nString restorationId,\nClip clipBehavior: Clip.hardEdge}\n)" }, { "code": null, "e": 2129, "s": 1588, "text": "const ListView.custom(\n{Key key,\nAxis scrollDirection: Axis.vertical,\nbool reverse: false,\nScrollController controller,\nbool primary,\nScrollPhysics physics,\nbool shrinkWrap: false,\nEdgeInsetsGeometry padding,\ndouble itemExtent,\n@required SliverChildDelegate childrenDelegate,\ndouble cacheExtent,\nint semanticChildCount,\nDragStartBehavior dragStartBehavior: DragStartBehavior.start,\nScrollViewKeyboardDismissBehavior keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.manual,\nString restorationId,\nClip clipBehavior: Clip.hardEdge}\n)" }, { "code": null, "e": 2793, "s": 2129, "text": "ListView.separated(\n{Key key,\nAxis scrollDirection: Axis.vertical,\nbool reverse: false,\nScrollController controller,\nbool primary,\nScrollPhysics physics,\nbool shrinkWrap: false,\nEdgeInsetsGeometry padding,\n@required IndexedWidgetBuilder itemBuilder,\n@required IndexedWidgetBuilder separatorBuilder,\n@required int itemCount,\nbool addAutomaticKeepAlives: true,\nbool addRepaintBoundaries: true,\nbool addSemanticIndexes: true,\ndouble cacheExtent,\nDragStartBehavior dragStartBehavior: DragStartBehavior.start,\nScrollViewKeyboardDismissBehavior keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.manual,\nString restorationId,\nClip clipBehavior: Clip.hardEdge}\n)" }, { "code": null, "e": 2935, "s": 2793, "text": "childrenDelegate: This property takes SliverChildDelegate as the object. It serves as a delegate that provided the children for the ListView." }, { "code": null, "e": 3075, "s": 2935, "text": "clipBehaviour: This property holds Clip enum (final) as the object. It controls whether the content in the ListView will be clipped or not." }, { "code": null, "e": 3189, "s": 3075, "text": "itemExtent: The itemExtent takes in a double value as the object to controls the scrollable area in the ListView." }, { "code": null, "e": 3294, "s": 3189, "text": "padding: It holds EdgeInsetsGeometryI as the object to give space between the Listview and its children." }, { "code": null, "e": 3413, "s": 3294, "text": "scrollDirection: This property takes in Axis enum as the object to decide the direction of the scroll on the ListView." }, { "code": null, "e": 3584, "s": 3413, "text": "shrinkWrap: This property takes in a boolean value as the object to decide whether the size of the scrollable area will be determined by the contents inside the ListView." }, { "code": null, "e": 3863, "s": 3584, "text": "This is the default constructor of the ListView class. A ListView simply takes a list of widgets and makes it scrollable. Usually, this is used with a few children as the List will also construct invisible elements in the list, so numerous widgets may render this inefficiently." }, { "code": null, "e": 3868, "s": 3863, "text": "Dart" }, { "code": "ListView( padding: EdgeInsets.all(20), children: <Widget>[ CircleAvatar( maxRadius: 50, backgroundColor: Colors.black, child: Icon(Icons.person, color: Colors.white, size: 50), ), Center( child: Text( 'Sooraj S Nair', style: TextStyle( fontSize: 50, ), ), ), Text( \"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a gallery of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum,It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).\", style: TextStyle( fontSize: 20, ), ), ], ),", "e": 5650, "s": 3868, "text": null }, { "code": null, "e": 5661, "s": 5653, "text": "Output:" }, { "code": null, "e": 5774, "s": 5663, "text": "The builder() constructor constructs a repeating list of widgets. The constructor takes two main parameters: " }, { "code": null, "e": 5868, "s": 5774, "text": "An itemCount for the number of repetitions for the widget to be constructed (not compulsory)." }, { "code": null, "e": 5967, "s": 5868, "text": "An itemBuilder for constructing the widget which will be generated ‘itemCount‘ times (compulsory)." }, { "code": null, "e": 6052, "s": 5967, "text": "If the itemCount is not specified, infinite widgets will be constructed by default. " }, { "code": null, "e": 6057, "s": 6052, "text": "Dart" }, { "code": "ListView.builder( itemCount: 20, itemBuilder: (context, position) { return Card( child: Padding( padding: const EdgeInsets.all(20.0), child: Text( position.toString(), style: TextStyle(fontSize: 22.0), ), ), ); }, ),", "e": 6435, "s": 6057, "text": null }, { "code": null, "e": 6446, "s": 6438, "text": "Output:" }, { "code": null, "e": 6776, "s": 6448, "text": "The ListView.separated() constructor is used to generate a list of widgets, but in addition, a separator widget can also be generated to separate the widgets. In short, these are two intertwined list of widgets: the main list and the separator list. Unlike the builder() constructor, the itemCount parameter is compulsory here." }, { "code": null, "e": 6783, "s": 6778, "text": "Dart" }, { "code": "ListView.separated( itemBuilder: (context, position) { return Card( child: Padding( padding: const EdgeInsets.all(15.0), child: Text( 'List Item $position', ), ), ); }, separatorBuilder: (context, position) { return Card( color: Colors.grey, child: Padding( padding: const EdgeInsets.all(5.0), child: Text( 'Separator $position', style: TextStyle(color: Colors.white), ), ), ); }, itemCount: 20, ),", "e": 7484, "s": 6783, "text": null }, { "code": null, "e": 7495, "s": 7487, "text": "Output:" }, { "code": null, "e": 7736, "s": 7497, "text": "As the name suggests, the ListView.custom() constructor lets us build ListViews with custom functionality for how the children of the list are built. The main parameter of this constructor is a SliverChildDelegate which builds the items. " }, { "code": null, "e": 7779, "s": 7736, "text": " The types of SliverChildDelegates are : " }, { "code": null, "e": 7803, "s": 7779, "text": "SliverChildListDelegate" }, { "code": null, "e": 7830, "s": 7803, "text": "SliverChildBuilderDelegate" }, { "code": null, "e": 8212, "s": 7830, "text": "The SliverChildListDelegate accepts a list of children widgets. whereas the SliverChildBuilderDelegate accepts an IndexedWidgetBuilder, simply a builder() function. Digging deeper, we can infer that ListView.builder was created using a ListView.custom with a SliverChildBuilderDelegate. Also, the default ListView() constructor is a ListView.custom with a SliverChildListDelegate." }, { "code": null, "e": 8225, "s": 8212, "text": "ankit_kumar_" }, { "code": null, "e": 8240, "s": 8225, "text": "varshagumber28" }, { "code": null, "e": 8250, "s": 8240, "text": "kalrap615" }, { "code": null, "e": 8258, "s": 8250, "text": "Flutter" }, { "code": null, "e": 8263, "s": 8258, "text": "Dart" } ]
Reversing a Stack with the help of another empty Stack
31 May, 2021 Given a Stack consisting of N elements, the task is to reverse the Stack using an extra stack. Examples: Input: stack = {1, 2, 3, 4, 5} Output: 1 2 3 4 5 Explanation: Input Stack: 5 4 3 2 1 Reversed Stack: 1 2 3 4 5 Input: stack = {1, 3, 5, 4, 2} Output: 1 3 5 4 2 Approach: Follow the steps below to solve the problem: Initialize an empty stack. Pop the top element of the given stack S and store it in a temporary variable. Transfer all the elements of the given stack to the stack initialized above. Push the temporary variable into the original stack. Transfer all the elements present in the new stack into the original stack. Below is the implementation of the above approach. C++ Java Python3 C# Javascript // C++ program to reverse a stack// by using an extra stack#include <bits/stdc++.h>using namespace std; // Function to transfer elements of// the stack s1 to the stack s2void transfer(stack<int>& s1, stack<int>& s2, int n){ for (int i = 0; i < n; i++) { // Store the top element // in a temporary variable int temp = s1.top(); // Pop out of the stack s1.pop(); // Push it into s2 s2.push(temp); }} // Function to reverse a stack using another stackvoid reverse_stack_by_using_extra_stack(stack<int>& s, int n){ stack<int> s2; for (int i = 0; i < n; i++) { // Store the top element // of the given stack int x = s.top(); // Pop that element // out of the stack s.pop(); transfer(s, s2, n - i - 1); s.push(x); transfer(s2, s, n - i - 1); }} // Driver Codeint main(){ int n = 5; stack<int> s; s.push(1); s.push(2); s.push(3); s.push(4); s.push(5); reverse_stack_by_using_extra_stack(s, n); for (int i = 0; i < n; i++) { cout << s.top() << " "; s.pop(); } return 0;} // Java program to reverse a stack// by using an extra stackimport java.io.*;import java.util.*; class GFG{ // Function to transfer elements of// the stack s1 to the stack s2static void transfer(Stack<Integer> s1, Stack<Integer> s2, int n){ for(int i = 0; i < n; i++) { // Store the top element // in a temporary variable int temp = s1.peek(); // Pop out of the stack s1.pop(); // Push it into s2 s2.push(temp); }} // Function to reverse a stack using another stackstatic void reverse_stack_by_using_extra_stack(Stack<Integer> s, int n){ Stack<Integer> s2 = new Stack<Integer>(); for(int i = 0; i < n; i++) { // Store the top element // of the given stack int x = s.peek(); // Pop that element // out of the stack s.pop(); transfer(s, s2, n - i - 1); s.push(x); transfer(s2, s, n - i - 1); }} // Driver Codepublic static void main(String[] args){ int n = 5; Stack<Integer> s = new Stack<Integer>(); s.push(1); s.push(2); s.push(3); s.push(4); s.push(5); reverse_stack_by_using_extra_stack(s, n); for(int i = 0; i < n; i++) { System.out.print(s.peek() + " "); s.pop(); }}} // This code is contributed by Dharanendra L V. # Python3 program to reverse a stack# by using an extra stack # Function to transfer elements of# the stack s1 to the stack s2def transfer(s1, s2, n): for i in range(n): # Store the top element # in a temporary variable temp = s1[-1] # Pop out of the stack s1.pop() # Push it into s2 s2.append(temp) # Function to reverse a stack using another stackdef reverse_stack_by_using_extra_stack(s, n): s2 = [] for i in range(n): # Store the top element # of the given stack x = s[-1] # Pop that element # out of the stack s.pop() transfer(s, s2, n - i - 1) s.append(x) transfer(s2, s, n - i - 1) # Driver Codeif __name__ == "__main__": n = 5 s = [] s.append(1) s.append(2) s.append(3) s.append(4) s.append(5) reverse_stack_by_using_extra_stack(s, n) for i in range(n): print(s[-1], end = " ") s.pop() # This code is contributed by ukasp // C# program to reverse a stack// by using an extra stackusing System;using System.Collections.Generic; class GFG{ // Function to transfer elements of// the stack s1 to the stack s2static void transfer(Stack<int> s1, Stack<int> s2, int n){ for (int i = 0; i < n; i++) { // Store the top element // in a temporary variable int temp = s1.Peek(); // Pop out of the stack s1.Pop(); // Push it into s2 s2.Push(temp); }} // Function to reverse a stack using another stackstatic void reverse_stack_by_using_extra_stack(Stack<int> s, int n){ Stack<int> s2 = new Stack<int>(); for (int i = 0; i < n; i++) { // Store the top element // of the given stack int x = s.Peek(); // Pop that element // out of the stack s.Pop(); transfer(s, s2, n - i - 1); s.Push(x); transfer(s2, s, n - i - 1); }} // Driver Codepublic static void Main(){ int n = 5; Stack<int> s = new Stack<int>(); s.Push(1); s.Push(2); s.Push(3); s.Push(4); s.Push(5); reverse_stack_by_using_extra_stack(s, n); for (int i = 0; i < n; i++) { Console.Write(s.Peek() + " "); s.Pop(); }}} // This code is contributed by SURENDRA_GANGWAR. <script> // JavaScript program to reverse a stack// by using an extra stack // Function to transfer elements of// the stack s1 to the stack s2function transfer(s1, s2, n){ for (i = 0; i < n; i++) { // Store the top element // in a temporary variable var temp = s1[s1.length-1]; // Pop out of the stack s1.pop(); // Push it into s2 s2.push(temp); }} // Function to reverse a stack using another stackfunction reverse_stack_by_using_extra_stack(s,n){ var s2 = []; var i; for (i = 0; i < n; i++) { // Store the top element // of the given stack var x = s[s.length-1]; // Pop that element // out of the stack s.pop(); transfer(s, s2, n - i - 1); s.push(x); transfer(s2, s, n - i - 1); }} // Driver Code var n = 5; var s = [] s.push(1); s.push(2); s.push(3); s.push(4); s.push(5); reverse_stack_by_using_extra_stack(s, n); var i; for (i = 0; i < n; i++) { document.write(s[s.length-1] + ' '); s.pop(); } </script> 1 2 3 4 5 Time Complexity: O(N2) Auxiliary Space: O(N) ukasp dharanendralv23 SURENDRA_GANGWAR ipg2016107 cpp-stack-functions Reverse Stack Stack Reverse Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures What is Data Structure: Types, Classifications and Applications Design a stack with operations on middle element How to efficiently implement k stacks in a single array? Next Smaller Element Real-time application of Data Structures Construct Binary Tree from String with bracket representation ZigZag Tree Traversal Reverse individual words Length of the longest valid substring
[ { "code": null, "e": 54, "s": 26, "text": "\n31 May, 2021" }, { "code": null, "e": 149, "s": 54, "text": "Given a Stack consisting of N elements, the task is to reverse the Stack using an extra stack." }, { "code": null, "e": 159, "s": 149, "text": "Examples:" }, { "code": null, "e": 270, "s": 159, "text": "Input: stack = {1, 2, 3, 4, 5} Output: 1 2 3 4 5 Explanation: Input Stack: 5 4 3 2 1 Reversed Stack: 1 2 3 4 5" }, { "code": null, "e": 319, "s": 270, "text": "Input: stack = {1, 3, 5, 4, 2} Output: 1 3 5 4 2" }, { "code": null, "e": 374, "s": 319, "text": "Approach: Follow the steps below to solve the problem:" }, { "code": null, "e": 401, "s": 374, "text": "Initialize an empty stack." }, { "code": null, "e": 480, "s": 401, "text": "Pop the top element of the given stack S and store it in a temporary variable." }, { "code": null, "e": 557, "s": 480, "text": "Transfer all the elements of the given stack to the stack initialized above." }, { "code": null, "e": 610, "s": 557, "text": "Push the temporary variable into the original stack." }, { "code": null, "e": 686, "s": 610, "text": "Transfer all the elements present in the new stack into the original stack." }, { "code": null, "e": 737, "s": 686, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 741, "s": 737, "text": "C++" }, { "code": null, "e": 746, "s": 741, "text": "Java" }, { "code": null, "e": 754, "s": 746, "text": "Python3" }, { "code": null, "e": 757, "s": 754, "text": "C#" }, { "code": null, "e": 768, "s": 757, "text": "Javascript" }, { "code": "// C++ program to reverse a stack// by using an extra stack#include <bits/stdc++.h>using namespace std; // Function to transfer elements of// the stack s1 to the stack s2void transfer(stack<int>& s1, stack<int>& s2, int n){ for (int i = 0; i < n; i++) { // Store the top element // in a temporary variable int temp = s1.top(); // Pop out of the stack s1.pop(); // Push it into s2 s2.push(temp); }} // Function to reverse a stack using another stackvoid reverse_stack_by_using_extra_stack(stack<int>& s, int n){ stack<int> s2; for (int i = 0; i < n; i++) { // Store the top element // of the given stack int x = s.top(); // Pop that element // out of the stack s.pop(); transfer(s, s2, n - i - 1); s.push(x); transfer(s2, s, n - i - 1); }} // Driver Codeint main(){ int n = 5; stack<int> s; s.push(1); s.push(2); s.push(3); s.push(4); s.push(5); reverse_stack_by_using_extra_stack(s, n); for (int i = 0; i < n; i++) { cout << s.top() << \" \"; s.pop(); } return 0;}", "e": 1967, "s": 768, "text": null }, { "code": "// Java program to reverse a stack// by using an extra stackimport java.io.*;import java.util.*; class GFG{ // Function to transfer elements of// the stack s1 to the stack s2static void transfer(Stack<Integer> s1, Stack<Integer> s2, int n){ for(int i = 0; i < n; i++) { // Store the top element // in a temporary variable int temp = s1.peek(); // Pop out of the stack s1.pop(); // Push it into s2 s2.push(temp); }} // Function to reverse a stack using another stackstatic void reverse_stack_by_using_extra_stack(Stack<Integer> s, int n){ Stack<Integer> s2 = new Stack<Integer>(); for(int i = 0; i < n; i++) { // Store the top element // of the given stack int x = s.peek(); // Pop that element // out of the stack s.pop(); transfer(s, s2, n - i - 1); s.push(x); transfer(s2, s, n - i - 1); }} // Driver Codepublic static void main(String[] args){ int n = 5; Stack<Integer> s = new Stack<Integer>(); s.push(1); s.push(2); s.push(3); s.push(4); s.push(5); reverse_stack_by_using_extra_stack(s, n); for(int i = 0; i < n; i++) { System.out.print(s.peek() + \" \"); s.pop(); }}} // This code is contributed by Dharanendra L V.", "e": 3361, "s": 1967, "text": null }, { "code": "# Python3 program to reverse a stack# by using an extra stack # Function to transfer elements of# the stack s1 to the stack s2def transfer(s1, s2, n): for i in range(n): # Store the top element # in a temporary variable temp = s1[-1] # Pop out of the stack s1.pop() # Push it into s2 s2.append(temp) # Function to reverse a stack using another stackdef reverse_stack_by_using_extra_stack(s, n): s2 = [] for i in range(n): # Store the top element # of the given stack x = s[-1] # Pop that element # out of the stack s.pop() transfer(s, s2, n - i - 1) s.append(x) transfer(s2, s, n - i - 1) # Driver Codeif __name__ == \"__main__\": n = 5 s = [] s.append(1) s.append(2) s.append(3) s.append(4) s.append(5) reverse_stack_by_using_extra_stack(s, n) for i in range(n): print(s[-1], end = \" \") s.pop() # This code is contributed by ukasp", "e": 4382, "s": 3361, "text": null }, { "code": "// C# program to reverse a stack// by using an extra stackusing System;using System.Collections.Generic; class GFG{ // Function to transfer elements of// the stack s1 to the stack s2static void transfer(Stack<int> s1, Stack<int> s2, int n){ for (int i = 0; i < n; i++) { // Store the top element // in a temporary variable int temp = s1.Peek(); // Pop out of the stack s1.Pop(); // Push it into s2 s2.Push(temp); }} // Function to reverse a stack using another stackstatic void reverse_stack_by_using_extra_stack(Stack<int> s, int n){ Stack<int> s2 = new Stack<int>(); for (int i = 0; i < n; i++) { // Store the top element // of the given stack int x = s.Peek(); // Pop that element // out of the stack s.Pop(); transfer(s, s2, n - i - 1); s.Push(x); transfer(s2, s, n - i - 1); }} // Driver Codepublic static void Main(){ int n = 5; Stack<int> s = new Stack<int>(); s.Push(1); s.Push(2); s.Push(3); s.Push(4); s.Push(5); reverse_stack_by_using_extra_stack(s, n); for (int i = 0; i < n; i++) { Console.Write(s.Peek() + \" \"); s.Pop(); }}} // This code is contributed by SURENDRA_GANGWAR.", "e": 5705, "s": 4382, "text": null }, { "code": "<script> // JavaScript program to reverse a stack// by using an extra stack // Function to transfer elements of// the stack s1 to the stack s2function transfer(s1, s2, n){ for (i = 0; i < n; i++) { // Store the top element // in a temporary variable var temp = s1[s1.length-1]; // Pop out of the stack s1.pop(); // Push it into s2 s2.push(temp); }} // Function to reverse a stack using another stackfunction reverse_stack_by_using_extra_stack(s,n){ var s2 = []; var i; for (i = 0; i < n; i++) { // Store the top element // of the given stack var x = s[s.length-1]; // Pop that element // out of the stack s.pop(); transfer(s, s2, n - i - 1); s.push(x); transfer(s2, s, n - i - 1); }} // Driver Code var n = 5; var s = [] s.push(1); s.push(2); s.push(3); s.push(4); s.push(5); reverse_stack_by_using_extra_stack(s, n); var i; for (i = 0; i < n; i++) { document.write(s[s.length-1] + ' '); s.pop(); } </script>", "e": 6799, "s": 5705, "text": null }, { "code": null, "e": 6809, "s": 6799, "text": "1 2 3 4 5" }, { "code": null, "e": 6856, "s": 6811, "text": "Time Complexity: O(N2) Auxiliary Space: O(N)" }, { "code": null, "e": 6864, "s": 6858, "text": "ukasp" }, { "code": null, "e": 6880, "s": 6864, "text": "dharanendralv23" }, { "code": null, "e": 6897, "s": 6880, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 6908, "s": 6897, "text": "ipg2016107" }, { "code": null, "e": 6928, "s": 6908, "text": "cpp-stack-functions" }, { "code": null, "e": 6936, "s": 6928, "text": "Reverse" }, { "code": null, "e": 6942, "s": 6936, "text": "Stack" }, { "code": null, "e": 6948, "s": 6942, "text": "Stack" }, { "code": null, "e": 6956, "s": 6948, "text": "Reverse" }, { "code": null, "e": 7054, "s": 6956, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7086, "s": 7054, "text": "Introduction to Data Structures" }, { "code": null, "e": 7150, "s": 7086, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 7199, "s": 7150, "text": "Design a stack with operations on middle element" }, { "code": null, "e": 7256, "s": 7199, "text": "How to efficiently implement k stacks in a single array?" }, { "code": null, "e": 7277, "s": 7256, "text": "Next Smaller Element" }, { "code": null, "e": 7318, "s": 7277, "text": "Real-time application of Data Structures" }, { "code": null, "e": 7380, "s": 7318, "text": "Construct Binary Tree from String with bracket representation" }, { "code": null, "e": 7402, "s": 7380, "text": "ZigZag Tree Traversal" }, { "code": null, "e": 7427, "s": 7402, "text": "Reverse individual words" } ]
Youtube Data API | Set-1
03 Dec, 2018 Google provides a large set of API’s for the developer to choose from. Each and every service provided by Google has an associated API. Being on of them, Youtube Data API is very simple to use provides features like – Search for videos Handle videos like retrieve information about a video, insert a video, delete a video etc. Handle Subscriptions like lists all the subscriptions, insert or delete a subscription. Retrieve information about comments like replies to a specific comment identified by a parentId etc. In this article, we will discuss Google Youtube API. Please follow the steps below to enable the API and start using it. Create New Project, Enable API and Create Credentials: In this step we will create a project and will enable the API.Go to Google Developers Console and Click on Sign In in the upper rightmost corner of the page. Sign In using the credentials of the valid Google Account. If you don’t have a google account, setup a account first and then use the details to Sign In on the Google Developers Homepage.Now navigate to the Developer Dashboard and create a new Project.Click on Enable API option.In the search field, search for Youtube Data API and select the Youtube Data API option that comes in the drop down list.You will be redirected to a screen that says information about the Youtube Data API, along with two options : ENABLE and TRY APIClick on ENABLE option to get started with the API.In the sidebar under APIs & Services, select Credentials.In the Credentials tab, select the Create credentials drop-down list, and choose API key.There are two types of Credentials: API Key and OAuth. OAuth provides you with Client Id and a Secret Key in the form of a .json file. OAuth is generally used where authorization is required like in the case of retrieving liked videos of a user. So for the rest cases where authorization is not required like searching for the videos using a keyword or for searching for the related videos etc we will be using API Key.Installation: Google API client for python can be installed using simple pip command:pip install --upgrade google-api-python-client Create New Project, Enable API and Create Credentials: In this step we will create a project and will enable the API.Go to Google Developers Console and Click on Sign In in the upper rightmost corner of the page. Sign In using the credentials of the valid Google Account. If you don’t have a google account, setup a account first and then use the details to Sign In on the Google Developers Homepage.Now navigate to the Developer Dashboard and create a new Project.Click on Enable API option.In the search field, search for Youtube Data API and select the Youtube Data API option that comes in the drop down list.You will be redirected to a screen that says information about the Youtube Data API, along with two options : ENABLE and TRY APIClick on ENABLE option to get started with the API.In the sidebar under APIs & Services, select Credentials.In the Credentials tab, select the Create credentials drop-down list, and choose API key.There are two types of Credentials: API Key and OAuth. OAuth provides you with Client Id and a Secret Key in the form of a .json file. OAuth is generally used where authorization is required like in the case of retrieving liked videos of a user. So for the rest cases where authorization is not required like searching for the videos using a keyword or for searching for the related videos etc we will be using API Key. Go to Google Developers Console and Click on Sign In in the upper rightmost corner of the page. Sign In using the credentials of the valid Google Account. If you don’t have a google account, setup a account first and then use the details to Sign In on the Google Developers Homepage. Now navigate to the Developer Dashboard and create a new Project. Click on Enable API option. In the search field, search for Youtube Data API and select the Youtube Data API option that comes in the drop down list. You will be redirected to a screen that says information about the Youtube Data API, along with two options : ENABLE and TRY API Click on ENABLE option to get started with the API. In the sidebar under APIs & Services, select Credentials. In the Credentials tab, select the Create credentials drop-down list, and choose API key.There are two types of Credentials: API Key and OAuth. OAuth provides you with Client Id and a Secret Key in the form of a .json file. OAuth is generally used where authorization is required like in the case of retrieving liked videos of a user. So for the rest cases where authorization is not required like searching for the videos using a keyword or for searching for the related videos etc we will be using API Key. Installation: Google API client for python can be installed using simple pip command:pip install --upgrade google-api-python-client pip install --upgrade google-api-python-client Let’s start with the Search function. There are five variants of search method – Search by Keyword, Search by Location, Search Live Events, Search Related Videos and Search My videos. Let’s cover first two types of search method. Search by Keyword function: This will return the list of videos, channels and playlists according to the search query. By default, if the type parameter is skipped, method will display videos, channels and playlists. Default value of max results parameter is 5. This example retrieves results associated with the keyword “Geeksforgeeks”. from apiclient.discovery import build # Arguments that need to passed to the build functionDEVELOPER_KEY = "your_API_Key" YOUTUBE_API_SERVICE_NAME = "youtube"YOUTUBE_API_VERSION = "v3" # creating Youtube Resource Objectyoutube_object = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey = DEVELOPER_KEY) def youtube_search_keyword(query, max_results): # calling the search.list method to # retrieve youtube search results search_keyword = youtube_object.search().list(q = query, part = "id, snippet", maxResults = max_results).execute() # extracting the results from search response results = search_keyword.get("items", []) # empty list to store video, # channel, playlist metadata videos = [] playlists = [] channels = [] # extracting required info from each result object for result in results: # video result object if result['id']['kind'] == "youtube# video": videos.append("% s (% s) (% s) (% s)" % (result["snippet"]["title"], result["id"]["videoId"], result['snippet']['description'], result['snippet']['thumbnails']['default']['url'])) # playlist result object elif result['id']['kind'] == "youtube# playlist": playlists.append("% s (% s) (% s) (% s)" % (result["snippet"]["title"], result["id"]["playlistId"], result['snippet']['description'], result['snippet']['thumbnails']['default']['url'])) # channel result object elif result['id']['kind'] == "youtube# channel": channels.append("% s (% s) (% s) (% s)" % (result["snippet"]["title"], result["id"]["channelId"], result['snippet']['description'], result['snippet']['thumbnails']['default']['url'])) print("Videos:\n", "\n".join(videos), "\n") print("Channels:\n", "\n".join(channels), "\n") print("Playlists:\n", "\n".join(playlists), "\n") if __name__ == "__main__": youtube_search_keyword('Geeksforgeeks', max_results = 10) Output: Search by Location function: This example retrieves results associated with the keyword “Geeksforgeeks”. The request retrieves top 5 results within 100km (specified by the locationRadius parameter value) of the point specified by the location parameter value. from apiclient.discovery import build # Arguments that need to passed to the build functionDEVELOPER_KEY = "your_API_Key" YOUTUBE_API_SERVICE_NAME = "youtube"YOUTUBE_API_VERSION = "v3" # creating Youtube Resource Objectyoutube_object = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey = DEVELOPER_KEY) def youtube_search_location(query, max_results = 5): # calling the search.list method to retrieve youtube search results search_location = youtube_object.search().list(q = query, type ='video', location ='20.593683, 78.962883', locationRadius ='100km', part = "id, snippet", maxResults = max_results).execute() # extracting the results from search response results = search_location.get("items", []) # empty list to store video metadata videos = [] # extracting required info from each result object for result in results: # video result object videos.append(result["id"]["videoId"]) video_ids = ", ".join(videos) video_response = youtube_object.videos().list(id = video_ids, part ='snippet, recordingDetails').execute() search_videos = [] for video_result in video_response.get("items", []): search_videos.append("% s, (% s, % s)" %(video_result["snippet"]["title"], video_result["recordingDetails"]["location"]["latitude"], video_result["recordingDetails"]["location"]["longitude"])) print ("Videos:\n", "\n".join(search_videos), "\n") if __name__ == "__main__": youtube_search_location('Geeksforgeeks', max_results = 5) Output: Note: location parameter is a string that specifies Latitude/Longitude coordinates of a geographic location. location parameter identifies the point at the center of the area. locationRadius parameter specifies the maximum distance that the location associated with a video can be from that point for the video to still be included in the search results. type argument can only be video in this search method type. In this example, we have used Latitude/ Longitude coordinates for Delhi, India. Note: We have used only limited parameters in the above example. There are many other parameters that can be set and if not set then what default value they take can be found from Youtube Search List Documentation. Please refer to the documentation to have a full understanding of the available parameters. References:https://developers.google.com/youtube/v3/docs/search/list GBlog Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You! Geek Streak - 24 Days POTD Challenge How to Learn Data Science in 10 weeks? What is Hashing | A Complete Tutorial Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function Python Dictionary How to get column names in Pandas dataframe
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Dec, 2018" }, { "code": null, "e": 246, "s": 28, "text": "Google provides a large set of API’s for the developer to choose from. Each and every service provided by Google has an associated API. Being on of them, Youtube Data API is very simple to use provides features like –" }, { "code": null, "e": 264, "s": 246, "text": "Search for videos" }, { "code": null, "e": 355, "s": 264, "text": "Handle videos like retrieve information about a video, insert a video, delete a video etc." }, { "code": null, "e": 443, "s": 355, "text": "Handle Subscriptions like lists all the subscriptions, insert or delete a subscription." }, { "code": null, "e": 544, "s": 443, "text": "Retrieve information about comments like replies to a specific comment identified by a parentId etc." }, { "code": null, "e": 665, "s": 544, "text": "In this article, we will discuss Google Youtube API. Please follow the steps below to enable the API and start using it." }, { "code": null, "e": 2154, "s": 665, "text": "Create New Project, Enable API and Create Credentials: In this step we will create a project and will enable the API.Go to Google Developers Console and Click on Sign In in the upper rightmost corner of the page. Sign In using the credentials of the valid Google Account. If you don’t have a google account, setup a account first and then use the details to Sign In on the Google Developers Homepage.Now navigate to the Developer Dashboard and create a new Project.Click on Enable API option.In the search field, search for Youtube Data API and select the Youtube Data API option that comes in the drop down list.You will be redirected to a screen that says information about the Youtube Data API, along with two options : ENABLE and TRY APIClick on ENABLE option to get started with the API.In the sidebar under APIs & Services, select Credentials.In the Credentials tab, select the Create credentials drop-down list, and choose API key.There are two types of Credentials: API Key and OAuth. OAuth provides you with Client Id and a Secret Key in the form of a .json file. OAuth is generally used where authorization is required like in the case of retrieving liked videos of a user. So for the rest cases where authorization is not required like searching for the videos using a keyword or for searching for the related videos etc we will be using API Key.Installation: Google API client for python can be installed using simple pip command:pip install --upgrade google-api-python-client" }, { "code": null, "e": 3512, "s": 2154, "text": "Create New Project, Enable API and Create Credentials: In this step we will create a project and will enable the API.Go to Google Developers Console and Click on Sign In in the upper rightmost corner of the page. Sign In using the credentials of the valid Google Account. If you don’t have a google account, setup a account first and then use the details to Sign In on the Google Developers Homepage.Now navigate to the Developer Dashboard and create a new Project.Click on Enable API option.In the search field, search for Youtube Data API and select the Youtube Data API option that comes in the drop down list.You will be redirected to a screen that says information about the Youtube Data API, along with two options : ENABLE and TRY APIClick on ENABLE option to get started with the API.In the sidebar under APIs & Services, select Credentials.In the Credentials tab, select the Create credentials drop-down list, and choose API key.There are two types of Credentials: API Key and OAuth. OAuth provides you with Client Id and a Secret Key in the form of a .json file. OAuth is generally used where authorization is required like in the case of retrieving liked videos of a user. So for the rest cases where authorization is not required like searching for the videos using a keyword or for searching for the related videos etc we will be using API Key." }, { "code": null, "e": 3796, "s": 3512, "text": "Go to Google Developers Console and Click on Sign In in the upper rightmost corner of the page. Sign In using the credentials of the valid Google Account. If you don’t have a google account, setup a account first and then use the details to Sign In on the Google Developers Homepage." }, { "code": null, "e": 3862, "s": 3796, "text": "Now navigate to the Developer Dashboard and create a new Project." }, { "code": null, "e": 3890, "s": 3862, "text": "Click on Enable API option." }, { "code": null, "e": 4012, "s": 3890, "text": "In the search field, search for Youtube Data API and select the Youtube Data API option that comes in the drop down list." }, { "code": null, "e": 4141, "s": 4012, "text": "You will be redirected to a screen that says information about the Youtube Data API, along with two options : ENABLE and TRY API" }, { "code": null, "e": 4193, "s": 4141, "text": "Click on ENABLE option to get started with the API." }, { "code": null, "e": 4251, "s": 4193, "text": "In the sidebar under APIs & Services, select Credentials." }, { "code": null, "e": 4760, "s": 4251, "text": "In the Credentials tab, select the Create credentials drop-down list, and choose API key.There are two types of Credentials: API Key and OAuth. OAuth provides you with Client Id and a Secret Key in the form of a .json file. OAuth is generally used where authorization is required like in the case of retrieving liked videos of a user. So for the rest cases where authorization is not required like searching for the videos using a keyword or for searching for the related videos etc we will be using API Key." }, { "code": null, "e": 4892, "s": 4760, "text": "Installation: Google API client for python can be installed using simple pip command:pip install --upgrade google-api-python-client" }, { "code": null, "e": 4939, "s": 4892, "text": "pip install --upgrade google-api-python-client" }, { "code": null, "e": 4977, "s": 4939, "text": "Let’s start with the Search function." }, { "code": null, "e": 5169, "s": 4977, "text": "There are five variants of search method – Search by Keyword, Search by Location, Search Live Events, Search Related Videos and Search My videos. Let’s cover first two types of search method." }, { "code": null, "e": 5507, "s": 5169, "text": "Search by Keyword function: This will return the list of videos, channels and playlists according to the search query. By default, if the type parameter is skipped, method will display videos, channels and playlists. Default value of max results parameter is 5. This example retrieves results associated with the keyword “Geeksforgeeks”." }, { "code": "from apiclient.discovery import build # Arguments that need to passed to the build functionDEVELOPER_KEY = \"your_API_Key\" YOUTUBE_API_SERVICE_NAME = \"youtube\"YOUTUBE_API_VERSION = \"v3\" # creating Youtube Resource Objectyoutube_object = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey = DEVELOPER_KEY) def youtube_search_keyword(query, max_results): # calling the search.list method to # retrieve youtube search results search_keyword = youtube_object.search().list(q = query, part = \"id, snippet\", maxResults = max_results).execute() # extracting the results from search response results = search_keyword.get(\"items\", []) # empty list to store video, # channel, playlist metadata videos = [] playlists = [] channels = [] # extracting required info from each result object for result in results: # video result object if result['id']['kind'] == \"youtube# video\": videos.append(\"% s (% s) (% s) (% s)\" % (result[\"snippet\"][\"title\"], result[\"id\"][\"videoId\"], result['snippet']['description'], result['snippet']['thumbnails']['default']['url'])) # playlist result object elif result['id']['kind'] == \"youtube# playlist\": playlists.append(\"% s (% s) (% s) (% s)\" % (result[\"snippet\"][\"title\"], result[\"id\"][\"playlistId\"], result['snippet']['description'], result['snippet']['thumbnails']['default']['url'])) # channel result object elif result['id']['kind'] == \"youtube# channel\": channels.append(\"% s (% s) (% s) (% s)\" % (result[\"snippet\"][\"title\"], result[\"id\"][\"channelId\"], result['snippet']['description'], result['snippet']['thumbnails']['default']['url'])) print(\"Videos:\\n\", \"\\n\".join(videos), \"\\n\") print(\"Channels:\\n\", \"\\n\".join(channels), \"\\n\") print(\"Playlists:\\n\", \"\\n\".join(playlists), \"\\n\") if __name__ == \"__main__\": youtube_search_keyword('Geeksforgeeks', max_results = 10) ", "e": 7830, "s": 5507, "text": null }, { "code": null, "e": 8098, "s": 7830, "text": "Output: Search by Location function: This example retrieves results associated with the keyword “Geeksforgeeks”. The request retrieves top 5 results within 100km (specified by the locationRadius parameter value) of the point specified by the location parameter value." }, { "code": "from apiclient.discovery import build # Arguments that need to passed to the build functionDEVELOPER_KEY = \"your_API_Key\" YOUTUBE_API_SERVICE_NAME = \"youtube\"YOUTUBE_API_VERSION = \"v3\" # creating Youtube Resource Objectyoutube_object = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey = DEVELOPER_KEY) def youtube_search_location(query, max_results = 5): # calling the search.list method to retrieve youtube search results search_location = youtube_object.search().list(q = query, type ='video', location ='20.593683, 78.962883', locationRadius ='100km', part = \"id, snippet\", maxResults = max_results).execute() # extracting the results from search response results = search_location.get(\"items\", []) # empty list to store video metadata videos = [] # extracting required info from each result object for result in results: # video result object videos.append(result[\"id\"][\"videoId\"]) video_ids = \", \".join(videos) video_response = youtube_object.videos().list(id = video_ids, part ='snippet, recordingDetails').execute() search_videos = [] for video_result in video_response.get(\"items\", []): search_videos.append(\"% s, (% s, % s)\" %(video_result[\"snippet\"][\"title\"], video_result[\"recordingDetails\"][\"location\"][\"latitude\"], video_result[\"recordingDetails\"][\"location\"][\"longitude\"])) print (\"Videos:\\n\", \"\\n\".join(search_videos), \"\\n\") if __name__ == \"__main__\": youtube_search_location('Geeksforgeeks', max_results = 5)", "e": 9903, "s": 8098, "text": null }, { "code": null, "e": 9911, "s": 9903, "text": "Output:" }, { "code": null, "e": 10020, "s": 9911, "text": "Note: location parameter is a string that specifies Latitude/Longitude coordinates of a geographic location." }, { "code": null, "e": 10087, "s": 10020, "text": "location parameter identifies the point at the center of the area." }, { "code": null, "e": 10266, "s": 10087, "text": "locationRadius parameter specifies the maximum distance that the location associated with a video can be from that point for the video to still be included in the search results." }, { "code": null, "e": 10406, "s": 10266, "text": "type argument can only be video in this search method type. In this example, we have used Latitude/ Longitude coordinates for Delhi, India." }, { "code": null, "e": 10713, "s": 10406, "text": "Note: We have used only limited parameters in the above example. There are many other parameters that can be set and if not set then what default value they take can be found from Youtube Search List Documentation. Please refer to the documentation to have a full understanding of the available parameters." }, { "code": null, "e": 10782, "s": 10713, "text": "References:https://developers.google.com/youtube/v3/docs/search/list" }, { "code": null, "e": 10788, "s": 10782, "text": "GBlog" }, { "code": null, "e": 10795, "s": 10788, "text": "Python" }, { "code": null, "e": 10814, "s": 10795, "text": "Technical Scripter" }, { "code": null, "e": 10912, "s": 10814, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10937, "s": 10912, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 10992, "s": 10937, "text": "GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You!" }, { "code": null, "e": 11029, "s": 10992, "text": "Geek Streak - 24 Days POTD Challenge" }, { "code": null, "e": 11068, "s": 11029, "text": "How to Learn Data Science in 10 weeks?" }, { "code": null, "e": 11106, "s": 11068, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 11134, "s": 11106, "text": "Read JSON file using Python" }, { "code": null, "e": 11184, "s": 11134, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 11206, "s": 11184, "text": "Python map() function" }, { "code": null, "e": 11224, "s": 11206, "text": "Python Dictionary" } ]
Python program to count Even and Odd numbers in a List
26 Oct, 2018 Given a list of numbers, write a Python program to count Even and Odd numbers in a List. Example: Input: list1 = [2, 7, 5, 64, 14] Output: Even = 3, odd = 2 Input: list2 = [12, 14, 95, 3] Output: Even = 2, odd = 2 Example 1: count Even and Odd numbers from given list using for loop Iterate each element in the list using for loop and check if num % 2 == 0, the condition to check even numbers. If the condition satisfies, then increase even count else increase odd count. # Python program to count Even# and Odd numbers in a List # list of numberslist1 = [10, 21, 4, 45, 66, 93, 1] even_count, odd_count = 0, 0 # iterating each number in listfor num in list1: # checking condition if num % 2 == 0: even_count += 1 else: odd_count += 1 print("Even numbers in the list: ", even_count)print("Odd numbers in the list: ", odd_count) Even numbers in the list: 3 Odd numbers in the list: 4 Example 2: Using while loop # Python program to count Even and Odd numbers in a List # list of numberslist1 = [10, 21, 4, 45, 66, 93, 11] even_count, odd_count = 0, 0num = 0 # using while loop while(num < len(list1)): # checking condition if list1[num] % 2 == 0: even_count += 1 else: odd_count += 1 # increment num num += 1 print("Even numbers in the list: ", even_count)print("Odd numbers in the list: ", odd_count) Even numbers in the list: 3 Odd numbers in the list: 4 Example 3 : Using Python Lambda Expressions # list of numberslist1 = [10, 21, 4, 45, 66, 93, 11] odd_count = len(list(filter(lambda x: (x%2 != 0) , list1))) # we can also do len(list1) - odd_counteven_count = len(list(filter(lambda x: (x%2 == 0) , list1))) print("Even numbers in the list: ", even_count)print("Odd numbers in the list: ", odd_count) Even numbers in the list: 3 Odd numbers in the list: 4 Example 4 : Using List Comprehension # Python program to print odd Numbers in a List # list of numberslist1 = [10, 21, 4, 45, 66, 93, 11] only_odd = [num for num in list1 if num % 2 == 1]odd_count = len(only_odd) print("Even numbers in the list: ", len(list1) - odd_count)print("Odd numbers in the list: ", odd_count) Even numbers in the list: 3 Odd numbers in the list: 4 Python list-programs python-lambda python-list Python Python Programs School Programming python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 53, "s": 25, "text": "\n26 Oct, 2018" }, { "code": null, "e": 142, "s": 53, "text": "Given a list of numbers, write a Python program to count Even and Odd numbers in a List." }, { "code": null, "e": 151, "s": 142, "text": "Example:" }, { "code": null, "e": 268, "s": 151, "text": "Input: list1 = [2, 7, 5, 64, 14]\nOutput: Even = 3, odd = 2\n\nInput: list2 = [12, 14, 95, 3]\nOutput: Even = 2, odd = 2" }, { "code": null, "e": 337, "s": 268, "text": "Example 1: count Even and Odd numbers from given list using for loop" }, { "code": null, "e": 527, "s": 337, "text": "Iterate each element in the list using for loop and check if num % 2 == 0, the condition to check even numbers. If the condition satisfies, then increase even count else increase odd count." }, { "code": "# Python program to count Even# and Odd numbers in a List # list of numberslist1 = [10, 21, 4, 45, 66, 93, 1] even_count, odd_count = 0, 0 # iterating each number in listfor num in list1: # checking condition if num % 2 == 0: even_count += 1 else: odd_count += 1 print(\"Even numbers in the list: \", even_count)print(\"Odd numbers in the list: \", odd_count)", "e": 926, "s": 527, "text": null }, { "code": null, "e": 984, "s": 926, "text": "Even numbers in the list: 3\nOdd numbers in the list: 4\n" }, { "code": null, "e": 1012, "s": 984, "text": "Example 2: Using while loop" }, { "code": "# Python program to count Even and Odd numbers in a List # list of numberslist1 = [10, 21, 4, 45, 66, 93, 11] even_count, odd_count = 0, 0num = 0 # using while loop while(num < len(list1)): # checking condition if list1[num] % 2 == 0: even_count += 1 else: odd_count += 1 # increment num num += 1 print(\"Even numbers in the list: \", even_count)print(\"Odd numbers in the list: \", odd_count)", "e": 1456, "s": 1012, "text": null }, { "code": null, "e": 1514, "s": 1456, "text": "Even numbers in the list: 3\nOdd numbers in the list: 4\n" }, { "code": null, "e": 1558, "s": 1514, "text": "Example 3 : Using Python Lambda Expressions" }, { "code": "# list of numberslist1 = [10, 21, 4, 45, 66, 93, 11] odd_count = len(list(filter(lambda x: (x%2 != 0) , list1))) # we can also do len(list1) - odd_counteven_count = len(list(filter(lambda x: (x%2 == 0) , list1))) print(\"Even numbers in the list: \", even_count)print(\"Odd numbers in the list: \", odd_count)", "e": 1867, "s": 1558, "text": null }, { "code": null, "e": 1925, "s": 1867, "text": "Even numbers in the list: 3\nOdd numbers in the list: 4\n" }, { "code": null, "e": 1962, "s": 1925, "text": "Example 4 : Using List Comprehension" }, { "code": "# Python program to print odd Numbers in a List # list of numberslist1 = [10, 21, 4, 45, 66, 93, 11] only_odd = [num for num in list1 if num % 2 == 1]odd_count = len(only_odd) print(\"Even numbers in the list: \", len(list1) - odd_count)print(\"Odd numbers in the list: \", odd_count)", "e": 2249, "s": 1962, "text": null }, { "code": null, "e": 2307, "s": 2249, "text": "Even numbers in the list: 3\nOdd numbers in the list: 4\n" }, { "code": null, "e": 2328, "s": 2307, "text": "Python list-programs" }, { "code": null, "e": 2342, "s": 2328, "text": "python-lambda" }, { "code": null, "e": 2354, "s": 2342, "text": "python-list" }, { "code": null, "e": 2361, "s": 2354, "text": "Python" }, { "code": null, "e": 2377, "s": 2361, "text": "Python Programs" }, { "code": null, "e": 2396, "s": 2377, "text": "School Programming" }, { "code": null, "e": 2408, "s": 2396, "text": "python-list" }, { "code": null, "e": 2506, "s": 2408, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2548, "s": 2506, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2570, "s": 2548, "text": "Enumerate() in Python" }, { "code": null, "e": 2596, "s": 2570, "text": "Python String | replace()" }, { "code": null, "e": 2628, "s": 2596, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2657, "s": 2628, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2679, "s": 2657, "text": "Defaultdict in Python" }, { "code": null, "e": 2718, "s": 2679, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2756, "s": 2718, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2805, "s": 2756, "text": "Python | Convert string dictionary to dictionary" } ]
Matplotlib.axes.Axes.grid() in Python
19 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.grid() function in axes module of matplotlib library is used to Configure the grid lines. Syntax: Axes.grid(self, b=None, which=’major’, axis=’both’, **kwargs) Parameters: This method accept the following parameters. b : This parameter is an optional parameter, whether to show the grid lines or not. which : This parameter is also an optional parameter and it is the grid lines to apply the changes on. axis :This parameter is also an optional parameter and it is the axis to apply the changes on. Returns:This method does not return any value. Below examples illustrate the matplotlib.axes.Axes.grid() function in matplotlib.axes: Example 1: # Implementation of matplotlib function import matplotlib.pyplot as pltimport numpy as np fig, ax = plt.subplots()ax.plot([1, 2, 3])ax.grid()ax.set_title('matplotlib.axes.Axes.grid() Example\n', fontsize = 12, fontweight ='bold')plt.show() Output: Example 2: # Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt x = np.arange(-5, 5, 0.01)y1 = -3 * x*x + 10 * x + 10y2 = 3 * x*x + x fig, [ax, ax1] = plt.subplots(2, 1, sharex = True) ax.plot(x, y1, x, y2, color ='black')ax.fill_between(x, y1, y2, where = y2 >y1, facecolor ='green', alpha = 0.8) ax.fill_between(x, y1, y2, where = y2 <= y1, facecolor ='black', alpha = 0.8) ax.xaxis.grid(True, color ="black")ax.set_title('matplotlib.axes.Axes.grid() \Example\n\n Grid in X-axis', fontsize = 12, fontweight ='bold') ax1.plot(x, y1, x, y2, color ='black')ax1.fill_between(x, y1, y2, where = y2 >y1, facecolor ='green', alpha = 0.8) ax1.fill_between(x, y1, y2, where = y2 <= y1, facecolor ='black', alpha = 0.8) ax1.yaxis.grid(True, color ="black")ax1.set_title('Grid in y-axis', fontsize = 12, fontweight ='bold')plt.show() Output: Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n19 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": 427, "s": 328, "text": "The Axes.grid() function in axes module of matplotlib library is used to Configure the grid lines." }, { "code": null, "e": 497, "s": 427, "text": "Syntax: Axes.grid(self, b=None, which=’major’, axis=’both’, **kwargs)" }, { "code": null, "e": 554, "s": 497, "text": "Parameters: This method accept the following parameters." }, { "code": null, "e": 638, "s": 554, "text": "b : This parameter is an optional parameter, whether to show the grid lines or not." }, { "code": null, "e": 741, "s": 638, "text": "which : This parameter is also an optional parameter and it is the grid lines to apply the changes on." }, { "code": null, "e": 836, "s": 741, "text": "axis :This parameter is also an optional parameter and it is the axis to apply the changes on." }, { "code": null, "e": 883, "s": 836, "text": "Returns:This method does not return any value." }, { "code": null, "e": 970, "s": 883, "text": "Below examples illustrate the matplotlib.axes.Axes.grid() function in matplotlib.axes:" }, { "code": null, "e": 981, "s": 970, "text": "Example 1:" }, { "code": "# Implementation of matplotlib function import matplotlib.pyplot as pltimport numpy as np fig, ax = plt.subplots()ax.plot([1, 2, 3])ax.grid()ax.set_title('matplotlib.axes.Axes.grid() Example\\n', fontsize = 12, fontweight ='bold')plt.show()", "e": 1239, "s": 981, "text": null }, { "code": null, "e": 1247, "s": 1239, "text": "Output:" }, { "code": null, "e": 1258, "s": 1247, "text": "Example 2:" }, { "code": "# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt x = np.arange(-5, 5, 0.01)y1 = -3 * x*x + 10 * x + 10y2 = 3 * x*x + x fig, [ax, ax1] = plt.subplots(2, 1, sharex = True) ax.plot(x, y1, x, y2, color ='black')ax.fill_between(x, y1, y2, where = y2 >y1, facecolor ='green', alpha = 0.8) ax.fill_between(x, y1, y2, where = y2 <= y1, facecolor ='black', alpha = 0.8) ax.xaxis.grid(True, color =\"black\")ax.set_title('matplotlib.axes.Axes.grid() \\Example\\n\\n Grid in X-axis', fontsize = 12, fontweight ='bold') ax1.plot(x, y1, x, y2, color ='black')ax1.fill_between(x, y1, y2, where = y2 >y1, facecolor ='green', alpha = 0.8) ax1.fill_between(x, y1, y2, where = y2 <= y1, facecolor ='black', alpha = 0.8) ax1.yaxis.grid(True, color =\"black\")ax1.set_title('Grid in y-axis', fontsize = 12, fontweight ='bold')plt.show()", "e": 2302, "s": 1258, "text": null }, { "code": null, "e": 2310, "s": 2302, "text": "Output:" }, { "code": null, "e": 2328, "s": 2310, "text": "Python-matplotlib" }, { "code": null, "e": 2335, "s": 2328, "text": "Python" }, { "code": null, "e": 2433, "s": 2335, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2451, "s": 2433, "text": "Python Dictionary" }, { "code": null, "e": 2493, "s": 2451, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2515, "s": 2493, "text": "Enumerate() in Python" }, { "code": null, "e": 2550, "s": 2515, "text": "Read a file line by line in Python" }, { "code": null, "e": 2576, "s": 2550, "text": "Python String | replace()" }, { "code": null, "e": 2608, "s": 2576, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2637, "s": 2608, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2664, "s": 2637, "text": "Python Classes and Objects" }, { "code": null, "e": 2694, "s": 2664, "text": "Iterate over a list in Python" } ]
Java Applet | Draw a line using drawLine() method
18 Jan, 2019 This article shall be explaining the code to draw a line using paint in Java. This uses drawLine() method. Syntax: drawLine(int x1, int y1, int x2, int y2) Parameters: The drawLine method takes four arguments: x1 – It takes the first point’s x coordinate. y1 – It takes first point’s y coordinate. x2 – It takes second point’s x coordinate. y2 – It takes second point’s y coordinate Result: This method will draw a line starting from (x1, y1) co-ordinates to (x2, y2) co-ordinates. Below programs illustrate the above problem: Example: // Java program to draw a line in Applet import java.awt.*;import javax.swing.*;import java.awt.geom.Line2D; class MyCanvas extends JComponent { public void paint(Graphics g) { // draw and display the line g.drawLine(30, 20, 80, 90); }} public class GFG1 { public static void main(String[] a) { // creating object of JFrame(Window popup) JFrame window = new JFrame(); // setting closing operation window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // setting size of the pop window window.setBounds(30, 30, 200, 200); // setting canvas for draw window.getContentPane().add(new MyCanvas()); // set visibility window.setVisible(true); }} Output : Note: The above function are a part of java.awt package and belongs to java.awt.Graphics class. Also, these codes might not run in an online compiler please use an offline compiler. The x1, x2, y1 and y2 coordinates can be changed by the programmer according to their need. java-applet Java Java Programs 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 Initializing a List in Java Java Programming Examples Convert a String to Character Array in Java Convert Double to Integer in Java Implementing a Linked List in Java using Class
[ { "code": null, "e": 53, "s": 25, "text": "\n18 Jan, 2019" }, { "code": null, "e": 160, "s": 53, "text": "This article shall be explaining the code to draw a line using paint in Java. This uses drawLine() method." }, { "code": null, "e": 168, "s": 160, "text": "Syntax:" }, { "code": null, "e": 209, "s": 168, "text": "drawLine(int x1, int y1, int x2, int y2)" }, { "code": null, "e": 263, "s": 209, "text": "Parameters: The drawLine method takes four arguments:" }, { "code": null, "e": 309, "s": 263, "text": "x1 – It takes the first point’s x coordinate." }, { "code": null, "e": 351, "s": 309, "text": "y1 – It takes first point’s y coordinate." }, { "code": null, "e": 394, "s": 351, "text": "x2 – It takes second point’s x coordinate." }, { "code": null, "e": 436, "s": 394, "text": "y2 – It takes second point’s y coordinate" }, { "code": null, "e": 535, "s": 436, "text": "Result: This method will draw a line starting from (x1, y1) co-ordinates to (x2, y2) co-ordinates." }, { "code": null, "e": 580, "s": 535, "text": "Below programs illustrate the above problem:" }, { "code": null, "e": 589, "s": 580, "text": "Example:" }, { "code": "// Java program to draw a line in Applet import java.awt.*;import javax.swing.*;import java.awt.geom.Line2D; class MyCanvas extends JComponent { public void paint(Graphics g) { // draw and display the line g.drawLine(30, 20, 80, 90); }} public class GFG1 { public static void main(String[] a) { // creating object of JFrame(Window popup) JFrame window = new JFrame(); // setting closing operation window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // setting size of the pop window window.setBounds(30, 30, 200, 200); // setting canvas for draw window.getContentPane().add(new MyCanvas()); // set visibility window.setVisible(true); }}", "e": 1348, "s": 589, "text": null }, { "code": null, "e": 1357, "s": 1348, "text": "Output :" }, { "code": null, "e": 1631, "s": 1357, "text": "Note: The above function are a part of java.awt package and belongs to java.awt.Graphics class. Also, these codes might not run in an online compiler please use an offline compiler. The x1, x2, y1 and y2 coordinates can be changed by the programmer according to their need." }, { "code": null, "e": 1643, "s": 1631, "text": "java-applet" }, { "code": null, "e": 1648, "s": 1643, "text": "Java" }, { "code": null, "e": 1662, "s": 1648, "text": "Java Programs" }, { "code": null, "e": 1667, "s": 1662, "text": "Java" }, { "code": null, "e": 1765, "s": 1667, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1816, "s": 1765, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 1847, "s": 1816, "text": "How to iterate any Map in Java" }, { "code": null, "e": 1866, "s": 1847, "text": "Interfaces in Java" }, { "code": null, "e": 1896, "s": 1866, "text": "HashMap in Java with Examples" }, { "code": null, "e": 1914, "s": 1896, "text": "ArrayList in Java" }, { "code": null, "e": 1942, "s": 1914, "text": "Initializing a List in Java" }, { "code": null, "e": 1968, "s": 1942, "text": "Java Programming Examples" }, { "code": null, "e": 2012, "s": 1968, "text": "Convert a String to Character Array in Java" }, { "code": null, "e": 2046, "s": 2012, "text": "Convert Double to Integer in Java" } ]
Booth’s Multiplication Algorithm
30 Jun, 2022 Booth’s algorithm is a multiplication algorithm that multiplies two signed binary numbers in 2’s complement notation. Booth used desk calculators that were faster at shifting than adding and created the algorithm to increase their speed. Booth’s algorithm is of interest in the study of computer architecture. Here’s the implementation of the algorithm. Examples: Input : 0110, 0010 Output : qn q[n+1] AC QR sc(step count) initial 0000 0010 4 0 0 rightShift 0000 0001 3 1 0 A = A - BR 1010 rightShift 1101 0000 2 0 1 A = A + BR 0011 rightShift 0001 1000 1 0 0 rightShift 0000 1100 0 Result=1100 Algorithm : Put multiplicand in BR and multiplier in QR and then the algorithm works as per the following conditions : 1. If Qn and Qn+1 are same i.e. 00 or 11 perform arithmetic shift by 1 bit. 2. If Qn Qn+1 = 10 do A= A + BR and perform arithmetic shift by 1 bit. 3. If Qn Qn+1 = 01 do A= A – BR and perform arithmetic shift by 1 bit. C++ Java Python3 C# Javascript // CPP code to implement booth's algorithm#include <bits/stdc++.h> using namespace std; // function to perform adding in the accumulatorvoid add(int ac[], int x[], int qrn){ int i, c = 0; for (i = 0; i < qrn; i++) { // updating accumulator with A = A + BR ac[i] = ac[i] + x[i] + c; if (ac[i] > 1) { ac[i] = ac[i] % 2; c = 1; } else c = 0; }} // function to find the number's complementvoid complement(int a[], int n){ int i; int x[8] = {0}; x[0] = 1; for (i = 0; i < n; i++) { a[i] = (a[i] + 1) % 2; } add(a, x, n);} // function to perform right shiftvoid rightShift(int ac[], int qr[], int& qn, int qrn){ int temp, i; temp = ac[0]; qn = qr[0]; cout << "\t\trightShift\t"; for (i = 0; i < qrn - 1; i++) { ac[i] = ac[i + 1]; qr[i] = qr[i + 1]; } qr[qrn - 1] = temp;} // function to display operationsvoid display(int ac[], int qr[], int qrn){ int i; // accumulator content for (i = qrn - 1; i >= 0; i--) cout << ac[i]; cout << "\t"; // multiplier content for (i = qrn - 1; i >= 0; i--) cout << qr[i];} // Function to implement booth's algovoid boothAlgorithm(int br[], int qr[], int mt[], int qrn, int sc){ int qn = 0, ac[10] = { 0 }; int temp = 0; cout << "qn\tq[n+1]\t\tBR\t\tAC\tQR\t\tsc\n"; cout << "\t\t\tinitial\t\t"; display(ac, qr, qrn); cout << "\t\t" << sc << "\n"; while (sc != 0) { cout << qr[0] << "\t" << qn; // SECOND CONDITION if ((qn + qr[0]) == 1) { if (temp == 0) { // subtract BR from accumulator add(ac, mt, qrn); cout << "\t\tA = A - BR\t"; for (int i = qrn - 1; i >= 0; i--) cout << ac[i]; temp = 1; } // THIRD CONDITION else if (temp == 1) { // add BR to accumulator add(ac, br, qrn); cout << "\t\tA = A + BR\t"; for (int i = qrn - 1; i >= 0; i--) cout << ac[i]; temp = 0; } cout << "\n\t"; rightShift(ac, qr, qn, qrn); } // FIRST CONDITION else if (qn - qr[0] == 0) rightShift(ac, qr, qn, qrn); display(ac, qr, qrn); cout << "\t"; // decrement counter sc--; cout << "\t" << sc << "\n"; }} // driver codeint main(int argc, char** arg){ int mt[10], sc; int brn, qrn; // Number of multiplicand bit brn = 4; // multiplicand int br[] = { 0, 1, 1, 0 }; // copy multiplier to temp array mt[] for (int i = brn - 1; i >= 0; i--) mt[i] = br[i]; reverse(br, br + brn); complement(mt, brn); // No. of multiplier bit qrn = 4; // sequence counter sc = qrn; // multiplier int qr[] = { 1, 0, 1, 0 }; reverse(qr, qr + qrn); boothAlgorithm(br, qr, mt, qrn, sc); cout << endl << "Result = "; for (int i = qrn - 1; i >= 0; i--) cout << qr[i];} // Java code to implement booth's algorithmclass GFG{ // function to perform adding in the accumulator static void add(int ac[], int x[], int qrn) { int i, c = 0; for (i = 0; i < qrn; i++) { // updating accumulator with A = A + BR ac[i] = ac[i] + x[i] + c; if (ac[i] > 1) { ac[i] = ac[i] % 2; c = 1; } else { c = 0; } } } // function to find the number's complement static void complement(int a[], int n) { int i; int[] x = new int[8]; x[0] = 1; for (i = 0; i < n; i++) { a[i] = (a[i] + 1) % 2; } add(a, x, n); } // function ro perform right shift static void rightShift(int ac[], int qr[], int qn, int qrn) { int temp, i; temp = ac[0]; qn = qr[0]; System.out.print("\t\trightShift\t"); for (i = 0; i < qrn - 1; i++) { ac[i] = ac[i + 1]; qr[i] = qr[i + 1]; } qr[qrn - 1] = temp; } // function to display operations static void display(int ac[], int qr[], int qrn) { int i; // accumulator content for (i = qrn - 1; i >= 0; i--) { System.out.print(ac[i]); } System.out.print("\t"); // multiplier content for (i = qrn - 1; i >= 0; i--) { System.out.print(qr[i]); } } // Function to implement booth's algo static void boothAlgorithm(int br[], int qr[], int mt[], int qrn, int sc) { int qn = 0; int[] ac = new int[10]; int temp = 0; System.out.print("qn\tq[n+1]\t\tBR\t\tAC\tQR\t\tsc\n"); System.out.print("\t\t\tinitial\t\t"); display(ac, qr, qrn); System.out.print("\t\t" + sc + "\n"); while (sc != 0) { System.out.print(qr[0] + "\t" + qn); // SECOND CONDITION if ((qn + qr[0]) == 1) { if (temp == 0) { // subtract BR from accumulator add(ac, mt, qrn); System.out.print("\t\tA = A - BR\t"); for (int i = qrn - 1; i >= 0; i--) { System.out.print(ac[i]); } temp = 1; } // THIRD CONDITION else if (temp == 1) { // add BR to accumulator add(ac, br, qrn); System.out.print("\t\tA = A + BR\t"); for (int i = qrn - 1; i >= 0; i--) { System.out.print(ac[i]); } temp = 0; } System.out.print("\n\t"); rightShift(ac, qr, qn, qrn); } // FIRST CONDITION else if (qn - qr[0] == 0) { rightShift(ac, qr, qn, qrn); } display(ac, qr, qrn); System.out.print("\t"); // decrement counter sc--; System.out.print("\t" + sc + "\n"); } } static void reverse(int a[]) { int i, k, n = a.length; int t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } } // Driver code public static void main(String[] args) { int[] mt = new int[10]; int sc; int brn, qrn; // Number of multiplicand bit brn = 4; // multiplicand int br[] = {0, 1, 1, 0}; // copy multiplier to temp array mt[] for (int i = brn - 1; i >= 0; i--) { mt[i] = br[i]; } reverse(br); complement(mt, brn); // No. of multiplier bit qrn = 4; // sequence counter sc = qrn; // multiplier int qr[] = {1, 0, 1, 0}; reverse(qr); boothAlgorithm(br, qr, mt, qrn, sc); System.out.print("\n" + "Result = "); for (int i = qrn - 1; i >= 0; i--) { System.out.print(qr[i]); } }} /* This code contributed by PrinciRaj1992 */ # Python3 code to implement booth's algorithm # function to perform adding in the accumulatordef add(ac, x, qrn): c = 0 for i in range(qrn): # updating accumulator with A = A + BR ac[i] = ac[i] + x[i] + c; if (ac[i] > 1): ac[i] = ac[i] % 2 c = 1 else: c = 0 # function to find the number's complementdef complement(a, n): x = [0] * 8 x[0] = 1 for i in range(n): a[i] = (a[i] + 1) % 2 add(a, x, n) # function to perform right shiftdef rightShift(ac, qr, qn, qrn): temp = ac[0] qn = qr[0] print("\t\trightShift\t", end = ""); for i in range(qrn - 1): ac[i] = ac[i + 1] qr[i] = qr[i + 1] qr[qrn - 1] = temp # function to display operationsdef display(ac, qr, qrn): # accumulator content for i in range(qrn - 1, -1, -1): print(ac[i], end = '') print("\t", end = '') # multiplier content for i in range(qrn - 1, -1, -1): print(qr[i], end = "") # Function to implement booth's algodef boothAlgorithm(br, qr, mt, qrn, sc): qn = 0 ac = [0] * 10 temp = 0 print("qn\tq[n+1]\t\tBR\t\tAC\tQR\t\tsc") print("\t\t\tinitial\t\t", end = "") display(ac, qr, qrn) print("\t\t", sc, sep = "") while (sc != 0): print(qr[0], "\t", qn, sep = "", end = "") # SECOND CONDITION if ((qn + qr[0]) == 1): if (temp == 0): # subtract BR from accumulator add(ac, mt, qrn) print("\t\tA = A - BR\t", end = "") for i in range(qrn - 1, -1, -1): print(ac[i], end = "") temp = 1 # THIRD CONDITION elif (temp == 1): # add BR to accumulator add(ac, br, qrn) print("\t\tA = A + BR\t", end = "") for i in range(qrn - 1, -1, -1): print(ac[i], end = "") temp = 0 print("\n\t", end = "") rightShift(ac, qr, qn, qrn) # FIRST CONDITION elif (qn - qr[0] == 0): rightShift(ac, qr, qn, qrn) display(ac, qr, qrn) print("\t", end = "") # decrement counter sc -= 1 print("\t", sc, sep = "") # driver codedef main(): mt = [0] * 10 # Number of multiplicand bit brn = 4 # multiplicand br = [ 0, 1, 1, 0 ] # copy multiplier to temp array mt[] for i in range(brn - 1, -1, -1): mt[i] = br[i] br.reverse() complement(mt, brn) # No. of multiplier bit qrn = 4 # sequence counter sc = qrn # multiplier qr = [ 1, 0, 1, 0 ] qr.reverse() boothAlgorithm(br, qr, mt, qrn, sc) print("\nResult = ", end = "") for i in range(qrn - 1, -1, -1): print(qr[i], end = "") print() main() #This code is contributed by phasing17 // C# code to implement// booth's algorithmusing System; class GFG{ // function to perform // adding in the accumulator static void add(int []ac, int []x, int qrn) { int i, c = 0; for (i = 0; i < qrn; i++) { // updating accumulator // with A = A + BR ac[i] = ac[i] + x[i] + c; if (ac[i] > 1) { ac[i] = ac[i] % 2; c = 1; } else c = 0; } } // function to find // the number's complement static void complement(int []a, int n) { int i; int []x = new int[8]; Array.Clear(x, 0, 8); x[0] = 1; for (i = 0; i < n; i++) { a[i] = (a[i] + 1) % 2; } add(a, x, n); } // function to perform // right shift static void rightShift(int []ac, int []qr, ref int qn, int qrn) { int temp, i; temp = ac[0]; qn = qr[0]; Console.Write("\t\trightShift\t"); for (i = 0; i < qrn - 1; i++) { ac[i] = ac[i + 1]; qr[i] = qr[i + 1]; } qr[qrn - 1] = temp; } // function to display // operations static void display(int []ac, int []qr, int qrn) { int i; // accumulator content for (i = qrn - 1; i >= 0; i--) Console.Write(ac[i]); Console.Write("\t"); // multiplier content for (i = qrn - 1; i >= 0; i--) Console.Write(qr[i]); } // Function to implement // booth's algo static void boothAlgorithm(int []br, int []qr, int []mt, int qrn, int sc) { int qn = 0; int []ac = new int[10]; Array.Clear(ac, 0, 10); int temp = 0; Console.Write("qn\tq[n + 1]\tBR\t" + "\tAC\tQR\t\tsc\n"); Console.Write("\t\t\tinitial\t\t"); display(ac, qr, qrn); Console.Write("\t\t" + sc + "\n"); while (sc != 0) { Console.Write(qr[0] + "\t" + qn); // SECOND CONDITION if ((qn + qr[0]) == 1) { if (temp == 0) { // subtract BR // from accumulator add(ac, mt, qrn); Console.Write("\t\tA = A - BR\t"); for (int i = qrn - 1; i >= 0; i--) Console.Write(ac[i]); temp = 1; } // THIRD CONDITION else if (temp == 1) { // add BR to accumulator add(ac, br, qrn); Console.Write("\t\tA = A + BR\t"); for (int i = qrn - 1; i >= 0; i--) Console.Write(ac[i]); temp = 0; } Console.Write("\n\t"); rightShift(ac, qr, ref qn, qrn); } // FIRST CONDITION else if (qn - qr[0] == 0) rightShift(ac, qr, ref qn, qrn); display(ac, qr, qrn); Console.Write("\t"); // decrement counter sc--; Console.Write("\t" + sc + "\n"); } } // Driver code static void Main() { int []mt = new int[10]; int sc, brn, qrn; // Number of // multiplicand bit brn = 4; // multiplicand int []br = new int[]{ 0, 1, 1, 0 }; // copy multiplier // to temp array mt[] for (int i = brn - 1; i >= 0; i--) mt[i] = br[i]; Array.Reverse(br); complement(mt, brn); // No. of // multiplier bit qrn = 4; // sequence // counter sc = qrn; // multiplier int []qr = new int[]{ 1, 0, 1, 0 }; Array.Reverse(qr); boothAlgorithm(br, qr, mt, qrn, sc); Console.WriteLine(); Console.Write("Result = "); for (int i = qrn - 1; i >= 0; i--) Console.Write(qr[i]); }} // This code is contributed by// Manish Shaw(manishshaw1) //JavaScript code to implement booth's algorithm // function to perform adding in the accumulatorfunction add(ac, x, qrn){ let c = 0; for (let i = 0; i < qrn; i++) { // updating accumulator with A = A + BR ac[i] = ac[i] + x[i] + c; if (ac[i] > 1) { ac[i] = ac[i] % 2; c = 1; } else c = 0; }} // function to find the number's complementfunction complement(a, n){ let x = new Array(8).fill(0); x[0] = 1; for (let i = 0; i < n; i++) a[i] = (a[i] + 1) % 2; add(a, x, n);} // function to perform right shiftfunction rightShift(ac, qr, qn, qrn){ let temp = ac[0]; qn = qr[0]; process.stdout.write("\t\trightShift\t"); for (let i = 0; i < qrn - 1; i++) { ac[i] = ac[i + 1]; qr[i] = qr[i + 1]; } qr[qrn - 1] = temp;} // function to display operationsfunction display(ac, qr, qrn){ // accumulator content for (let i = qrn - 1; i > -1; i--) process.stdout.write(ac[i] + ""); process.stdout.write("\t"); // multiplier content for (i = qrn - 1; i > -1; i--) process.stdout.write(qr[i] + "");} // Function to implement booth's algofunction boothAlgorithm(br, qr, mt, qrn, sc){ let qn = 0; let ac = new Array(10).fill(0); let temp = 0; process.stdout.write("qn\tq[n+1]\t\tBR\t\tAC\tQR\t\tsc\n"); process.stdout.write("\t\t\tinitial\t\t"); display(ac, qr, qrn); process.stdout.write("\t\t" + sc + "\n"); while (sc != 0) { process.stdout.write(qr[0] + "\t" + qn); // SECOND CONDITION if ((qn + qr[0]) == 1) { if (temp == 0) { // subtract BR from accumulator add(ac, mt, qrn); process.stdout.write("\t\tA = A - BR\t"); for (let i = qrn - 1; i > -1; i--) process.stdout.write(ac[i] + ""); temp = 1; } // THIRD CONDITION else if (temp == 1) { // add BR to accumulator add(ac, br, qrn); process.stdout.write("\t\tA = A + BR\t"); for (i = qrn - 1; i > -1; i--) process.stdout.write(ac[i] + ""); temp = 0; } process.stdout.write("\n\t"); rightShift(ac, qr, qn, qrn); } // FIRST CONDITION else if (qn - qr[0] == 0) rightShift(ac, qr, qn, qrn); display(ac, qr, qrn); process.stdout.write("\t"); // decrement counter sc -= 1; process.stdout.write("\t" + sc + "\n"); }} // driver codelet mt = new Array(10).fill(0); // Number of multiplicand bitlet brn = 4; // multiplicandlet br = [ 0, 1, 1, 0 ]; // copy multiplier to temp array mt[]for (let i = brn - 1; i > -1; i--) mt[i] = br[i]; br.reverse() complement(mt, brn) // No. of multiplier bitqrn = 4; // sequence counterlet sc = qrn; // multiplierlet qr = [ 1, 0, 1, 0 ];qr.reverse(); boothAlgorithm(br, qr, mt, qrn, sc) process.stdout.write("\nResult = "); for (let i = qrn - 1; i > -1; i--) process.stdout.write(qr[i] + ""); process.stdout.write("\n"); //This code is contributed by phasing17 Output : qn q[n + 1] BR AC QR sc initial 0000 1010 4 0 0 rightShift 0000 0101 3 1 0 A = A - BR 1010 rightShift 1101 0010 2 0 1 A = A + BR 0011 rightShift 0001 1001 1 1 0 A = A - BR 1011 rightShift 1101 1100 0 Result = 1100 manishshaw1 princiraj1992 saurabh1990aror anikaseth98 sahilsayani7 phasing17 Bit Magic Computer Organization and Architecture Mathematical Mathematical Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 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? Program to find whether a given number is power of 2 Interrupts in 8085 microprocessor Microprocessor | 8254 programmable interval timer Minimum mode configuration of 8086 microprocessor (Min mode) Maximum mode configuration of 8086 microprocessor (Max mode) GTX vs RTX - Which is better?
[ { "code": null, "e": 54, "s": 26, "text": "\n30 Jun, 2022" }, { "code": null, "e": 420, "s": 54, "text": "Booth’s algorithm is a multiplication algorithm that multiplies two signed binary numbers in 2’s complement notation. Booth used desk calculators that were faster at shifting than adding and created the algorithm to increase their speed. Booth’s algorithm is of interest in the study of computer architecture. Here’s the implementation of the algorithm. Examples: " }, { "code": null, "e": 933, "s": 420, "text": "Input : 0110, 0010\nOutput : qn q[n+1] AC QR sc(step count)\n initial 0000 0010 4\n 0 0 rightShift 0000 0001 3\n 1 0 A = A - BR 1010\n rightShift 1101 0000 2\n 0 1 A = A + BR 0011\n rightShift 0001 1000 1\n 0 0 rightShift 0000 1100 0\n\nResult=1100" }, { "code": null, "e": 949, "s": 935, "text": "Algorithm : " }, { "code": null, "e": 1276, "s": 949, "text": "Put multiplicand in BR and multiplier in QR and then the algorithm works as per the following conditions : 1. If Qn and Qn+1 are same i.e. 00 or 11 perform arithmetic shift by 1 bit. 2. If Qn Qn+1 = 10 do A= A + BR and perform arithmetic shift by 1 bit. 3. If Qn Qn+1 = 01 do A= A – BR and perform arithmetic shift by 1 bit. " }, { "code": null, "e": 1282, "s": 1278, "text": "C++" }, { "code": null, "e": 1287, "s": 1282, "text": "Java" }, { "code": null, "e": 1295, "s": 1287, "text": "Python3" }, { "code": null, "e": 1298, "s": 1295, "text": "C#" }, { "code": null, "e": 1309, "s": 1298, "text": "Javascript" }, { "code": "// CPP code to implement booth's algorithm#include <bits/stdc++.h> using namespace std; // function to perform adding in the accumulatorvoid add(int ac[], int x[], int qrn){ int i, c = 0; for (i = 0; i < qrn; i++) { // updating accumulator with A = A + BR ac[i] = ac[i] + x[i] + c; if (ac[i] > 1) { ac[i] = ac[i] % 2; c = 1; } else c = 0; }} // function to find the number's complementvoid complement(int a[], int n){ int i; int x[8] = {0}; x[0] = 1; for (i = 0; i < n; i++) { a[i] = (a[i] + 1) % 2; } add(a, x, n);} // function to perform right shiftvoid rightShift(int ac[], int qr[], int& qn, int qrn){ int temp, i; temp = ac[0]; qn = qr[0]; cout << \"\\t\\trightShift\\t\"; for (i = 0; i < qrn - 1; i++) { ac[i] = ac[i + 1]; qr[i] = qr[i + 1]; } qr[qrn - 1] = temp;} // function to display operationsvoid display(int ac[], int qr[], int qrn){ int i; // accumulator content for (i = qrn - 1; i >= 0; i--) cout << ac[i]; cout << \"\\t\"; // multiplier content for (i = qrn - 1; i >= 0; i--) cout << qr[i];} // Function to implement booth's algovoid boothAlgorithm(int br[], int qr[], int mt[], int qrn, int sc){ int qn = 0, ac[10] = { 0 }; int temp = 0; cout << \"qn\\tq[n+1]\\t\\tBR\\t\\tAC\\tQR\\t\\tsc\\n\"; cout << \"\\t\\t\\tinitial\\t\\t\"; display(ac, qr, qrn); cout << \"\\t\\t\" << sc << \"\\n\"; while (sc != 0) { cout << qr[0] << \"\\t\" << qn; // SECOND CONDITION if ((qn + qr[0]) == 1) { if (temp == 0) { // subtract BR from accumulator add(ac, mt, qrn); cout << \"\\t\\tA = A - BR\\t\"; for (int i = qrn - 1; i >= 0; i--) cout << ac[i]; temp = 1; } // THIRD CONDITION else if (temp == 1) { // add BR to accumulator add(ac, br, qrn); cout << \"\\t\\tA = A + BR\\t\"; for (int i = qrn - 1; i >= 0; i--) cout << ac[i]; temp = 0; } cout << \"\\n\\t\"; rightShift(ac, qr, qn, qrn); } // FIRST CONDITION else if (qn - qr[0] == 0) rightShift(ac, qr, qn, qrn); display(ac, qr, qrn); cout << \"\\t\"; // decrement counter sc--; cout << \"\\t\" << sc << \"\\n\"; }} // driver codeint main(int argc, char** arg){ int mt[10], sc; int brn, qrn; // Number of multiplicand bit brn = 4; // multiplicand int br[] = { 0, 1, 1, 0 }; // copy multiplier to temp array mt[] for (int i = brn - 1; i >= 0; i--) mt[i] = br[i]; reverse(br, br + brn); complement(mt, brn); // No. of multiplier bit qrn = 4; // sequence counter sc = qrn; // multiplier int qr[] = { 1, 0, 1, 0 }; reverse(qr, qr + qrn); boothAlgorithm(br, qr, mt, qrn, sc); cout << endl << \"Result = \"; for (int i = qrn - 1; i >= 0; i--) cout << qr[i];}", "e": 4618, "s": 1309, "text": null }, { "code": "// Java code to implement booth's algorithmclass GFG{ // function to perform adding in the accumulator static void add(int ac[], int x[], int qrn) { int i, c = 0; for (i = 0; i < qrn; i++) { // updating accumulator with A = A + BR ac[i] = ac[i] + x[i] + c; if (ac[i] > 1) { ac[i] = ac[i] % 2; c = 1; } else { c = 0; } } } // function to find the number's complement static void complement(int a[], int n) { int i; int[] x = new int[8]; x[0] = 1; for (i = 0; i < n; i++) { a[i] = (a[i] + 1) % 2; } add(a, x, n); } // function ro perform right shift static void rightShift(int ac[], int qr[], int qn, int qrn) { int temp, i; temp = ac[0]; qn = qr[0]; System.out.print(\"\\t\\trightShift\\t\"); for (i = 0; i < qrn - 1; i++) { ac[i] = ac[i + 1]; qr[i] = qr[i + 1]; } qr[qrn - 1] = temp; } // function to display operations static void display(int ac[], int qr[], int qrn) { int i; // accumulator content for (i = qrn - 1; i >= 0; i--) { System.out.print(ac[i]); } System.out.print(\"\\t\"); // multiplier content for (i = qrn - 1; i >= 0; i--) { System.out.print(qr[i]); } } // Function to implement booth's algo static void boothAlgorithm(int br[], int qr[], int mt[], int qrn, int sc) { int qn = 0; int[] ac = new int[10]; int temp = 0; System.out.print(\"qn\\tq[n+1]\\t\\tBR\\t\\tAC\\tQR\\t\\tsc\\n\"); System.out.print(\"\\t\\t\\tinitial\\t\\t\"); display(ac, qr, qrn); System.out.print(\"\\t\\t\" + sc + \"\\n\"); while (sc != 0) { System.out.print(qr[0] + \"\\t\" + qn); // SECOND CONDITION if ((qn + qr[0]) == 1) { if (temp == 0) { // subtract BR from accumulator add(ac, mt, qrn); System.out.print(\"\\t\\tA = A - BR\\t\"); for (int i = qrn - 1; i >= 0; i--) { System.out.print(ac[i]); } temp = 1; } // THIRD CONDITION else if (temp == 1) { // add BR to accumulator add(ac, br, qrn); System.out.print(\"\\t\\tA = A + BR\\t\"); for (int i = qrn - 1; i >= 0; i--) { System.out.print(ac[i]); } temp = 0; } System.out.print(\"\\n\\t\"); rightShift(ac, qr, qn, qrn); } // FIRST CONDITION else if (qn - qr[0] == 0) { rightShift(ac, qr, qn, qrn); } display(ac, qr, qrn); System.out.print(\"\\t\"); // decrement counter sc--; System.out.print(\"\\t\" + sc + \"\\n\"); } } static void reverse(int a[]) { int i, k, n = a.length; int t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } } // Driver code public static void main(String[] args) { int[] mt = new int[10]; int sc; int brn, qrn; // Number of multiplicand bit brn = 4; // multiplicand int br[] = {0, 1, 1, 0}; // copy multiplier to temp array mt[] for (int i = brn - 1; i >= 0; i--) { mt[i] = br[i]; } reverse(br); complement(mt, brn); // No. of multiplier bit qrn = 4; // sequence counter sc = qrn; // multiplier int qr[] = {1, 0, 1, 0}; reverse(qr); boothAlgorithm(br, qr, mt, qrn, sc); System.out.print(\"\\n\" + \"Result = \"); for (int i = qrn - 1; i >= 0; i--) { System.out.print(qr[i]); } }} /* This code contributed by PrinciRaj1992 */", "e": 9062, "s": 4618, "text": null }, { "code": "# Python3 code to implement booth's algorithm # function to perform adding in the accumulatordef add(ac, x, qrn): c = 0 for i in range(qrn): # updating accumulator with A = A + BR ac[i] = ac[i] + x[i] + c; if (ac[i] > 1): ac[i] = ac[i] % 2 c = 1 else: c = 0 # function to find the number's complementdef complement(a, n): x = [0] * 8 x[0] = 1 for i in range(n): a[i] = (a[i] + 1) % 2 add(a, x, n) # function to perform right shiftdef rightShift(ac, qr, qn, qrn): temp = ac[0] qn = qr[0] print(\"\\t\\trightShift\\t\", end = \"\"); for i in range(qrn - 1): ac[i] = ac[i + 1] qr[i] = qr[i + 1] qr[qrn - 1] = temp # function to display operationsdef display(ac, qr, qrn): # accumulator content for i in range(qrn - 1, -1, -1): print(ac[i], end = '') print(\"\\t\", end = '') # multiplier content for i in range(qrn - 1, -1, -1): print(qr[i], end = \"\") # Function to implement booth's algodef boothAlgorithm(br, qr, mt, qrn, sc): qn = 0 ac = [0] * 10 temp = 0 print(\"qn\\tq[n+1]\\t\\tBR\\t\\tAC\\tQR\\t\\tsc\") print(\"\\t\\t\\tinitial\\t\\t\", end = \"\") display(ac, qr, qrn) print(\"\\t\\t\", sc, sep = \"\") while (sc != 0): print(qr[0], \"\\t\", qn, sep = \"\", end = \"\") # SECOND CONDITION if ((qn + qr[0]) == 1): if (temp == 0): # subtract BR from accumulator add(ac, mt, qrn) print(\"\\t\\tA = A - BR\\t\", end = \"\") for i in range(qrn - 1, -1, -1): print(ac[i], end = \"\") temp = 1 # THIRD CONDITION elif (temp == 1): # add BR to accumulator add(ac, br, qrn) print(\"\\t\\tA = A + BR\\t\", end = \"\") for i in range(qrn - 1, -1, -1): print(ac[i], end = \"\") temp = 0 print(\"\\n\\t\", end = \"\") rightShift(ac, qr, qn, qrn) # FIRST CONDITION elif (qn - qr[0] == 0): rightShift(ac, qr, qn, qrn) display(ac, qr, qrn) print(\"\\t\", end = \"\") # decrement counter sc -= 1 print(\"\\t\", sc, sep = \"\") # driver codedef main(): mt = [0] * 10 # Number of multiplicand bit brn = 4 # multiplicand br = [ 0, 1, 1, 0 ] # copy multiplier to temp array mt[] for i in range(brn - 1, -1, -1): mt[i] = br[i] br.reverse() complement(mt, brn) # No. of multiplier bit qrn = 4 # sequence counter sc = qrn # multiplier qr = [ 1, 0, 1, 0 ] qr.reverse() boothAlgorithm(br, qr, mt, qrn, sc) print(\"\\nResult = \", end = \"\") for i in range(qrn - 1, -1, -1): print(qr[i], end = \"\") print() main() #This code is contributed by phasing17", "e": 12149, "s": 9062, "text": null }, { "code": "// C# code to implement// booth's algorithmusing System; class GFG{ // function to perform // adding in the accumulator static void add(int []ac, int []x, int qrn) { int i, c = 0; for (i = 0; i < qrn; i++) { // updating accumulator // with A = A + BR ac[i] = ac[i] + x[i] + c; if (ac[i] > 1) { ac[i] = ac[i] % 2; c = 1; } else c = 0; } } // function to find // the number's complement static void complement(int []a, int n) { int i; int []x = new int[8]; Array.Clear(x, 0, 8); x[0] = 1; for (i = 0; i < n; i++) { a[i] = (a[i] + 1) % 2; } add(a, x, n); } // function to perform // right shift static void rightShift(int []ac, int []qr, ref int qn, int qrn) { int temp, i; temp = ac[0]; qn = qr[0]; Console.Write(\"\\t\\trightShift\\t\"); for (i = 0; i < qrn - 1; i++) { ac[i] = ac[i + 1]; qr[i] = qr[i + 1]; } qr[qrn - 1] = temp; } // function to display // operations static void display(int []ac, int []qr, int qrn) { int i; // accumulator content for (i = qrn - 1; i >= 0; i--) Console.Write(ac[i]); Console.Write(\"\\t\"); // multiplier content for (i = qrn - 1; i >= 0; i--) Console.Write(qr[i]); } // Function to implement // booth's algo static void boothAlgorithm(int []br, int []qr, int []mt, int qrn, int sc) { int qn = 0; int []ac = new int[10]; Array.Clear(ac, 0, 10); int temp = 0; Console.Write(\"qn\\tq[n + 1]\\tBR\\t\" + \"\\tAC\\tQR\\t\\tsc\\n\"); Console.Write(\"\\t\\t\\tinitial\\t\\t\"); display(ac, qr, qrn); Console.Write(\"\\t\\t\" + sc + \"\\n\"); while (sc != 0) { Console.Write(qr[0] + \"\\t\" + qn); // SECOND CONDITION if ((qn + qr[0]) == 1) { if (temp == 0) { // subtract BR // from accumulator add(ac, mt, qrn); Console.Write(\"\\t\\tA = A - BR\\t\"); for (int i = qrn - 1; i >= 0; i--) Console.Write(ac[i]); temp = 1; } // THIRD CONDITION else if (temp == 1) { // add BR to accumulator add(ac, br, qrn); Console.Write(\"\\t\\tA = A + BR\\t\"); for (int i = qrn - 1; i >= 0; i--) Console.Write(ac[i]); temp = 0; } Console.Write(\"\\n\\t\"); rightShift(ac, qr, ref qn, qrn); } // FIRST CONDITION else if (qn - qr[0] == 0) rightShift(ac, qr, ref qn, qrn); display(ac, qr, qrn); Console.Write(\"\\t\"); // decrement counter sc--; Console.Write(\"\\t\" + sc + \"\\n\"); } } // Driver code static void Main() { int []mt = new int[10]; int sc, brn, qrn; // Number of // multiplicand bit brn = 4; // multiplicand int []br = new int[]{ 0, 1, 1, 0 }; // copy multiplier // to temp array mt[] for (int i = brn - 1; i >= 0; i--) mt[i] = br[i]; Array.Reverse(br); complement(mt, brn); // No. of // multiplier bit qrn = 4; // sequence // counter sc = qrn; // multiplier int []qr = new int[]{ 1, 0, 1, 0 }; Array.Reverse(qr); boothAlgorithm(br, qr, mt, qrn, sc); Console.WriteLine(); Console.Write(\"Result = \"); for (int i = qrn - 1; i >= 0; i--) Console.Write(qr[i]); }} // This code is contributed by// Manish Shaw(manishshaw1)", "e": 16814, "s": 12149, "text": null }, { "code": "//JavaScript code to implement booth's algorithm // function to perform adding in the accumulatorfunction add(ac, x, qrn){ let c = 0; for (let i = 0; i < qrn; i++) { // updating accumulator with A = A + BR ac[i] = ac[i] + x[i] + c; if (ac[i] > 1) { ac[i] = ac[i] % 2; c = 1; } else c = 0; }} // function to find the number's complementfunction complement(a, n){ let x = new Array(8).fill(0); x[0] = 1; for (let i = 0; i < n; i++) a[i] = (a[i] + 1) % 2; add(a, x, n);} // function to perform right shiftfunction rightShift(ac, qr, qn, qrn){ let temp = ac[0]; qn = qr[0]; process.stdout.write(\"\\t\\trightShift\\t\"); for (let i = 0; i < qrn - 1; i++) { ac[i] = ac[i + 1]; qr[i] = qr[i + 1]; } qr[qrn - 1] = temp;} // function to display operationsfunction display(ac, qr, qrn){ // accumulator content for (let i = qrn - 1; i > -1; i--) process.stdout.write(ac[i] + \"\"); process.stdout.write(\"\\t\"); // multiplier content for (i = qrn - 1; i > -1; i--) process.stdout.write(qr[i] + \"\");} // Function to implement booth's algofunction boothAlgorithm(br, qr, mt, qrn, sc){ let qn = 0; let ac = new Array(10).fill(0); let temp = 0; process.stdout.write(\"qn\\tq[n+1]\\t\\tBR\\t\\tAC\\tQR\\t\\tsc\\n\"); process.stdout.write(\"\\t\\t\\tinitial\\t\\t\"); display(ac, qr, qrn); process.stdout.write(\"\\t\\t\" + sc + \"\\n\"); while (sc != 0) { process.stdout.write(qr[0] + \"\\t\" + qn); // SECOND CONDITION if ((qn + qr[0]) == 1) { if (temp == 0) { // subtract BR from accumulator add(ac, mt, qrn); process.stdout.write(\"\\t\\tA = A - BR\\t\"); for (let i = qrn - 1; i > -1; i--) process.stdout.write(ac[i] + \"\"); temp = 1; } // THIRD CONDITION else if (temp == 1) { // add BR to accumulator add(ac, br, qrn); process.stdout.write(\"\\t\\tA = A + BR\\t\"); for (i = qrn - 1; i > -1; i--) process.stdout.write(ac[i] + \"\"); temp = 0; } process.stdout.write(\"\\n\\t\"); rightShift(ac, qr, qn, qrn); } // FIRST CONDITION else if (qn - qr[0] == 0) rightShift(ac, qr, qn, qrn); display(ac, qr, qrn); process.stdout.write(\"\\t\"); // decrement counter sc -= 1; process.stdout.write(\"\\t\" + sc + \"\\n\"); }} // driver codelet mt = new Array(10).fill(0); // Number of multiplicand bitlet brn = 4; // multiplicandlet br = [ 0, 1, 1, 0 ]; // copy multiplier to temp array mt[]for (let i = brn - 1; i > -1; i--) mt[i] = br[i]; br.reverse() complement(mt, brn) // No. of multiplier bitqrn = 4; // sequence counterlet sc = qrn; // multiplierlet qr = [ 1, 0, 1, 0 ];qr.reverse(); boothAlgorithm(br, qr, mt, qrn, sc) process.stdout.write(\"\\nResult = \"); for (let i = qrn - 1; i > -1; i--) process.stdout.write(qr[i] + \"\"); process.stdout.write(\"\\n\"); //This code is contributed by phasing17", "e": 20220, "s": 16814, "text": null }, { "code": null, "e": 20231, "s": 20220, "text": "Output : " }, { "code": null, "e": 20635, "s": 20231, "text": "qn q[n + 1] BR AC QR sc\n initial 0000 1010 4\n0 0 rightShift 0000 0101 3\n1 0 A = A - BR 1010\n rightShift 1101 0010 2\n0 1 A = A + BR 0011\n rightShift 0001 1001 1\n1 0 A = A - BR 1011\n rightShift 1101 1100 0\n\nResult = 1100" }, { "code": null, "e": 20649, "s": 20637, "text": "manishshaw1" }, { "code": null, "e": 20663, "s": 20649, "text": "princiraj1992" }, { "code": null, "e": 20679, "s": 20663, "text": "saurabh1990aror" }, { "code": null, "e": 20691, "s": 20679, "text": "anikaseth98" }, { "code": null, "e": 20704, "s": 20691, "text": "sahilsayani7" }, { "code": null, "e": 20714, "s": 20704, "text": "phasing17" }, { "code": null, "e": 20724, "s": 20714, "text": "Bit Magic" }, { "code": null, "e": 20763, "s": 20724, "text": "Computer Organization and Architecture" }, { "code": null, "e": 20776, "s": 20763, "text": "Mathematical" }, { "code": null, "e": 20789, "s": 20776, "text": "Mathematical" }, { "code": null, "e": 20799, "s": 20789, "text": "Bit Magic" }, { "code": null, "e": 20897, "s": 20799, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 20943, "s": 20897, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 21011, "s": 20943, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 21040, "s": 21011, "text": "Count set bits in an integer" }, { "code": null, "e": 21100, "s": 21040, "text": "How to swap two numbers without using a temporary variable?" }, { "code": null, "e": 21153, "s": 21100, "text": "Program to find whether a given number is power of 2" }, { "code": null, "e": 21187, "s": 21153, "text": "Interrupts in 8085 microprocessor" }, { "code": null, "e": 21237, "s": 21187, "text": "Microprocessor | 8254 programmable interval timer" }, { "code": null, "e": 21298, "s": 21237, "text": "Minimum mode configuration of 8086 microprocessor (Min mode)" }, { "code": null, "e": 21359, "s": 21298, "text": "Maximum mode configuration of 8086 microprocessor (Max mode)" } ]
PyQt5 QListWidget – Setting Edit Trigger Property
06 Aug, 2020 In this article we will see how we can set the edit trigger property of the QListWidget. QListWidget is a convenience class that provides a list view with a classic item-based interface for adding and removing items. QListWidget uses an internal model to manage each QListWidgetItem in the list. This property describes actions which will initiate item editing. In order to do this we will use setEditTriggers method with the list widget object. Syntax : list_widget.setEditTriggers(et) Argument : It takes edit triggers object argument Return : It returns None Below is the implementation # importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QListWidget list_widget = QListWidget(self) # setting geometry to it list_widget.setGeometry(50, 70, 150, 60) # list widget items item1 = QListWidgetItem("A") item2 = QListWidgetItem("B") item3 = QListWidgetItem("C") # adding items to the list widget list_widget.addItem(item1) list_widget.addItem(item2) list_widget.addItem(item3) # setting edit trigger property list_widget.setEditTriggers(QAbstractItemView.NoEditTriggers) # creating a label label = QLabel("GeesforGeeks", self) # setting geometry to the label label.setGeometry(230, 80, 280, 80) # making label multi line label.setWordWrap(True) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : Python PyQt-QListWidget Python-gui Python-PyQt 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, 2020" }, { "code": null, "e": 390, "s": 28, "text": "In this article we will see how we can set the edit trigger property of the QListWidget. QListWidget is a convenience class that provides a list view with a classic item-based interface for adding and removing items. QListWidget uses an internal model to manage each QListWidgetItem in the list. This property describes actions which will initiate item editing." }, { "code": null, "e": 474, "s": 390, "text": "In order to do this we will use setEditTriggers method with the list widget object." }, { "code": null, "e": 515, "s": 474, "text": "Syntax : list_widget.setEditTriggers(et)" }, { "code": null, "e": 565, "s": 515, "text": "Argument : It takes edit triggers object argument" }, { "code": null, "e": 590, "s": 565, "text": "Return : It returns None" }, { "code": null, "e": 618, "s": 590, "text": "Below is the implementation" }, { "code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QListWidget list_widget = QListWidget(self) # setting geometry to it list_widget.setGeometry(50, 70, 150, 60) # list widget items item1 = QListWidgetItem(\"A\") item2 = QListWidgetItem(\"B\") item3 = QListWidgetItem(\"C\") # adding items to the list widget list_widget.addItem(item1) list_widget.addItem(item2) list_widget.addItem(item3) # setting edit trigger property list_widget.setEditTriggers(QAbstractItemView.NoEditTriggers) # creating a label label = QLabel(\"GeesforGeeks\", self) # setting geometry to the label label.setGeometry(230, 80, 280, 80) # making label multi line label.setWordWrap(True) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 2063, "s": 618, "text": null }, { "code": null, "e": 2072, "s": 2063, "text": "Output :" }, { "code": null, "e": 2096, "s": 2072, "text": "Python PyQt-QListWidget" }, { "code": null, "e": 2107, "s": 2096, "text": "Python-gui" }, { "code": null, "e": 2119, "s": 2107, "text": "Python-PyQt" }, { "code": null, "e": 2126, "s": 2119, "text": "Python" } ]
Python | Difference between two lists
30 Jun, 2021 There are various ways in which the difference between two lists can be generated. In this article, we will see the two most important ways in which this can be done. One by using the set() method, and another by not using it. Examples: Input : list1 = [10, 15, 20, 25, 30, 35, 40] list2 = [25, 40, 35] Output : [10, 20, 30, 15] Explanation: resultant list = list1 - list2 Note: When you have multiple same elements then this would not work. In that case, this code will simply remove the same elements.In that case, you can maintain a count of each element in both lists. In this method, we convert the lists into sets explicitly and then simply reduce one from the other using the subtract operator. For more reference on set visit Sets in Python. Example: Python3 # Python code t get difference of two lists# Using set()def Diff(li1, li2): return list(set(li1) - set(li2)) + list(set(li2) - set(li1)) # Driver Codeli1 = [10, 15, 20, 25, 30, 35, 40]li2 = [25, 40, 35]print(Diff(li1, li2)) Output : [10, 20, 30, 15] In this method, we use the basic combination technique to copy elements from both the list with a regular check if one is present in the other or not. Example: Python3 # Python code t get difference of two lists# Not using set()def Diff(li1, li2): li_dif = [i for i in li1 + li2 if i not in li1 or i not in li2] return li_dif # Driver Codeli1 = [10, 15, 20, 25, 30, 35, 40]li2 = [25, 40, 35]li3 = Diff(li1, li2)print(li3) Output : [10, 20, 30, 15] ashishk2409 mihika0278 utsavp0213 akashdeep8757 python-list python-set Python python-list python-set Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Iterate over a list in Python Python Classes and Objects Convert integer to string in Python
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Jun, 2021" }, { "code": null, "e": 281, "s": 52, "text": "There are various ways in which the difference between two lists can be generated. In this article, we will see the two most important ways in which this can be done. One by using the set() method, and another by not using it. " }, { "code": null, "e": 293, "s": 281, "text": "Examples: " }, { "code": null, "e": 441, "s": 293, "text": "Input :\nlist1 = [10, 15, 20, 25, 30, 35, 40]\nlist2 = [25, 40, 35] \nOutput :\n[10, 20, 30, 15]\nExplanation:\nresultant list = list1 - list2\n " }, { "code": null, "e": 642, "s": 441, "text": " Note: When you have multiple same elements then this would not work. In that case, this code will simply remove the same elements.In that case, you can maintain a count of each element in both lists." }, { "code": null, "e": 823, "s": 644, "text": "In this method, we convert the lists into sets explicitly and then simply reduce one from the other using the subtract operator. For more reference on set visit Sets in Python. " }, { "code": null, "e": 833, "s": 823, "text": "Example: " }, { "code": null, "e": 841, "s": 833, "text": "Python3" }, { "code": "# Python code t get difference of two lists# Using set()def Diff(li1, li2): return list(set(li1) - set(li2)) + list(set(li2) - set(li1)) # Driver Codeli1 = [10, 15, 20, 25, 30, 35, 40]li2 = [25, 40, 35]print(Diff(li1, li2))", "e": 1068, "s": 841, "text": null }, { "code": null, "e": 1079, "s": 1068, "text": "Output : " }, { "code": null, "e": 1096, "s": 1079, "text": "[10, 20, 30, 15]" }, { "code": null, "e": 1251, "s": 1098, "text": "In this method, we use the basic combination technique to copy elements from both the list with a regular check if one is present in the other or not. " }, { "code": null, "e": 1260, "s": 1251, "text": "Example:" }, { "code": null, "e": 1268, "s": 1260, "text": "Python3" }, { "code": "# Python code t get difference of two lists# Not using set()def Diff(li1, li2): li_dif = [i for i in li1 + li2 if i not in li1 or i not in li2] return li_dif # Driver Codeli1 = [10, 15, 20, 25, 30, 35, 40]li2 = [25, 40, 35]li3 = Diff(li1, li2)print(li3)", "e": 1528, "s": 1268, "text": null }, { "code": null, "e": 1538, "s": 1528, "text": "Output : " }, { "code": null, "e": 1555, "s": 1538, "text": "[10, 20, 30, 15]" }, { "code": null, "e": 1567, "s": 1555, "text": "ashishk2409" }, { "code": null, "e": 1578, "s": 1567, "text": "mihika0278" }, { "code": null, "e": 1589, "s": 1578, "text": "utsavp0213" }, { "code": null, "e": 1603, "s": 1589, "text": "akashdeep8757" }, { "code": null, "e": 1615, "s": 1603, "text": "python-list" }, { "code": null, "e": 1626, "s": 1615, "text": "python-set" }, { "code": null, "e": 1633, "s": 1626, "text": "Python" }, { "code": null, "e": 1645, "s": 1633, "text": "python-list" }, { "code": null, "e": 1656, "s": 1645, "text": "python-set" }, { "code": null, "e": 1754, "s": 1656, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1772, "s": 1754, "text": "Python Dictionary" }, { "code": null, "e": 1814, "s": 1772, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1836, "s": 1814, "text": "Enumerate() in Python" }, { "code": null, "e": 1871, "s": 1836, "text": "Read a file line by line in Python" }, { "code": null, "e": 1897, "s": 1871, "text": "Python String | replace()" }, { "code": null, "e": 1929, "s": 1897, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1958, "s": 1929, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1988, "s": 1958, "text": "Iterate over a list in Python" }, { "code": null, "e": 2015, "s": 1988, "text": "Python Classes and Objects" } ]
Python | Add trailing Zeros to string
25 Jun, 2022 Sometimes, we wish to manipulate a string in such a way in which we might need to add additional zeros at the end of string; in case of filling the missing bits or any other specific requirement. The solution to this kind of problems is always handy and is good if one has knowledge of it. Let’s discuss certain ways in which this can be solved. Method #1 : Using ljust() This task can be performed using the simple inbuilt string function of ljust in which we just need to pass no. of zeros required and the element to right pad, in this case being zero. Python3 # Python3 code to demonstrate# adding trailing zeros# using ljust() # initializing stringtest_string = 'GFG' # printing original stringprint("The original string : " + str(test_string)) # No. of zeros requiredN = 4 # using ljust()# adding trailing zerores = test_string.ljust(N + len(test_string), '0') # print resultprint("The string after adding trailing zeros : " + str(res)) The original string : GFG The string after adding trailing zeros : GFG0000 Method #2 : Using format() String formatting using the format function can be used to perform this task easily, we just mention the number of elements total, element needed to pad, and direction of padding, in this case right. Python3 # Python3 code to demonstrate# adding trailing zeros# using format() # initializing stringtest_string = 'GFG' # printing original stringprint("The original string : " + str(test_string)) # No. of zeros requiredN = 4 # using format()# adding trailing zero# N for number of elements, '0' for Zero, and '<' for trailingtemp = '{:<07}'res = temp.format(test_string) # print resultprint("The string after adding trailing zeros : " + str(res)) The original string : GFG The string after adding trailing zeros : GFG0000 Method #3 : Without any built-in methods Python3 # Python3 code to demonstrate# adding trailing zeros # initializing stringtest_string = 'GFG' # printing original stringprint("The original string : " + str(test_string)) # No. of zeros requiredN = 4 # adding trailing zerox = '0'*Nres = test_string+x # print resultprint("The string after adding trailing zeros : " + str(res)) The original string : GFG The string after adding trailing zeros : GFG0000 simranarora5sos kogantibhavya Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Jun, 2022" }, { "code": null, "e": 374, "s": 28, "text": "Sometimes, we wish to manipulate a string in such a way in which we might need to add additional zeros at the end of string; in case of filling the missing bits or any other specific requirement. The solution to this kind of problems is always handy and is good if one has knowledge of it. Let’s discuss certain ways in which this can be solved." }, { "code": null, "e": 585, "s": 374, "text": "Method #1 : Using ljust() This task can be performed using the simple inbuilt string function of ljust in which we just need to pass no. of zeros required and the element to right pad, in this case being zero. " }, { "code": null, "e": 593, "s": 585, "text": "Python3" }, { "code": "# Python3 code to demonstrate# adding trailing zeros# using ljust() # initializing stringtest_string = 'GFG' # printing original stringprint(\"The original string : \" + str(test_string)) # No. of zeros requiredN = 4 # using ljust()# adding trailing zerores = test_string.ljust(N + len(test_string), '0') # print resultprint(\"The string after adding trailing zeros : \" + str(res))", "e": 972, "s": 593, "text": null }, { "code": null, "e": 1047, "s": 972, "text": "The original string : GFG\nThe string after adding trailing zeros : GFG0000" }, { "code": null, "e": 1277, "s": 1047, "text": " Method #2 : Using format() String formatting using the format function can be used to perform this task easily, we just mention the number of elements total, element needed to pad, and direction of padding, in this case right. " }, { "code": null, "e": 1285, "s": 1277, "text": "Python3" }, { "code": "# Python3 code to demonstrate# adding trailing zeros# using format() # initializing stringtest_string = 'GFG' # printing original stringprint(\"The original string : \" + str(test_string)) # No. of zeros requiredN = 4 # using format()# adding trailing zero# N for number of elements, '0' for Zero, and '<' for trailingtemp = '{:<07}'res = temp.format(test_string) # print resultprint(\"The string after adding trailing zeros : \" + str(res))", "e": 1723, "s": 1285, "text": null }, { "code": null, "e": 1798, "s": 1723, "text": "The original string : GFG\nThe string after adding trailing zeros : GFG0000" }, { "code": null, "e": 1839, "s": 1798, "text": "Method #3 : Without any built-in methods" }, { "code": null, "e": 1847, "s": 1839, "text": "Python3" }, { "code": "# Python3 code to demonstrate# adding trailing zeros # initializing stringtest_string = 'GFG' # printing original stringprint(\"The original string : \" + str(test_string)) # No. of zeros requiredN = 4 # adding trailing zerox = '0'*Nres = test_string+x # print resultprint(\"The string after adding trailing zeros : \" + str(res))", "e": 2175, "s": 1847, "text": null }, { "code": null, "e": 2250, "s": 2175, "text": "The original string : GFG\nThe string after adding trailing zeros : GFG0000" }, { "code": null, "e": 2266, "s": 2250, "text": "simranarora5sos" }, { "code": null, "e": 2280, "s": 2266, "text": "kogantibhavya" }, { "code": null, "e": 2303, "s": 2280, "text": "Python string-programs" }, { "code": null, "e": 2310, "s": 2303, "text": "Python" }, { "code": null, "e": 2326, "s": 2310, "text": "Python Programs" }, { "code": null, "e": 2424, "s": 2326, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2442, "s": 2424, "text": "Python Dictionary" }, { "code": null, "e": 2484, "s": 2442, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2506, "s": 2484, "text": "Enumerate() in Python" }, { "code": null, "e": 2541, "s": 2506, "text": "Read a file line by line in Python" }, { "code": null, "e": 2567, "s": 2541, "text": "Python String | replace()" }, { "code": null, "e": 2610, "s": 2567, "text": "Python program to convert a list to string" }, { "code": null, "e": 2632, "s": 2610, "text": "Defaultdict in Python" }, { "code": null, "e": 2671, "s": 2632, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2709, "s": 2671, "text": "Python | Convert a list to dictionary" } ]
TypeScript - String indexOf()
This method returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex or -1 if the value is not found. string.indexOf(searchValue[, fromIndex]) searchValue − A string representing the value to search for. searchValue − A string representing the value to search for. fromIndex − The location within the calling string to start the search from. It can be any integer between 0 and the length of the string. The default value is 0. fromIndex − The location within the calling string to start the search from. It can be any integer between 0 and the length of the string. The default value is 0. Returns the index of the found occurrence, otherwise -1 if not found. var str1 = new String( "This is string one" ); var index = str1.indexOf( "string" ); console.log("indexOf found String :" + index ); var index = str1.indexOf( "one" ); console.log("indexOf found String :" + index ); On compiling, it will generate the same code in JavaScript. Its output is as follows − indexOf found String :8 indexOf found String :15
[ { "code": null, "e": 2359, "s": 2182, "text": "This method returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex or -1 if the value is not found." }, { "code": null, "e": 2401, "s": 2359, "text": "string.indexOf(searchValue[, fromIndex])\n" }, { "code": null, "e": 2462, "s": 2401, "text": "searchValue − A string representing the value to search for." }, { "code": null, "e": 2523, "s": 2462, "text": "searchValue − A string representing the value to search for." }, { "code": null, "e": 2686, "s": 2523, "text": "fromIndex − The location within the calling string to start the search from. It can be any integer between 0 and the length of the string. The default value is 0." }, { "code": null, "e": 2849, "s": 2686, "text": "fromIndex − The location within the calling string to start the search from. It can be any integer between 0 and the length of the string. The default value is 0." }, { "code": null, "e": 2919, "s": 2849, "text": "Returns the index of the found occurrence, otherwise -1 if not found." }, { "code": null, "e": 3145, "s": 2919, "text": "var str1 = new String( \"This is string one\" ); \n \nvar index = str1.indexOf( \"string\" ); \nconsole.log(\"indexOf found String :\" + index ); \n\nvar index = str1.indexOf( \"one\" ); \nconsole.log(\"indexOf found String :\" + index );\n" }, { "code": null, "e": 3205, "s": 3145, "text": "On compiling, it will generate the same code in JavaScript." }, { "code": null, "e": 3232, "s": 3205, "text": "Its output is as follows −" } ]
How to use PSCustomObject in PowerShell foreach parallel loop?
To use the PSCustomObject inside the Foreach Parallel loop, we first need to consider how we are using the variables inside the loop. $Out = "PowerShell" ForEach-Object -Parallel{ Write-Output "Hello.... $($using:Out)" } So let see if we can store or change a value in the $out variable. $Out = @() ForEach-Object -Parallel{ $using:out = "Azure" Write-Output "Hello....$($using:out) " } Line | 4 | $using:out = "Azure" | ~~~~~~~~~~ | The assignment expression is not valid. The input to an assignment operator must be an object that is able to accept | assignments, such as a variable or a property. The error says that the expression is invalid so we can’t manipulate the variable directly. So we have another method that we can use a temporary variable for it. $Out = @() ForEach-Object -Parallel{ $dict = $using:out $dict = "Azure" Write-Output "Hello....$dict" } Similarly, we can use the PSCustomObject using the Temporary variable as shown below. $Out = @() $vms = "Testvm1","Testvm2","Testvm3" $vmout = $vms | ForEach-Object -Parallel{ $dict = $using:out $dict += [PSCustomObject]@{ VMName = $_ Location = 'EastUS' } return $dict } Write-Output "VM Output" $vmout VMName Location ------ -------- Testvm1 EastUS Testvm2 EastUS Testvm3 EastUS
[ { "code": null, "e": 1321, "s": 1187, "text": "To use the PSCustomObject inside the Foreach Parallel loop, we first need to consider how we are using the variables inside the loop." }, { "code": null, "e": 1411, "s": 1321, "text": "$Out = \"PowerShell\"\nForEach-Object -Parallel{\n Write-Output \"Hello.... $($using:Out)\"\n}" }, { "code": null, "e": 1478, "s": 1411, "text": "So let see if we can store or change a value in the $out variable." }, { "code": null, "e": 1583, "s": 1478, "text": "$Out = @()\nForEach-Object -Parallel{\n $using:out = \"Azure\"\n Write-Output \"Hello....$($using:out) \"\n}" }, { "code": null, "e": 1814, "s": 1583, "text": "Line |\n 4 | $using:out = \"Azure\"\n | ~~~~~~~~~~\n | The assignment expression is not valid. The input to an assignment operator must be an object that is able to accept\n | assignments, such as a variable or a property." }, { "code": null, "e": 1977, "s": 1814, "text": "The error says that the expression is invalid so we can’t manipulate the variable directly. So we have another method that we can use a temporary variable for it." }, { "code": null, "e": 2090, "s": 1977, "text": "$Out = @()\nForEach-Object -Parallel{\n $dict = $using:out\n $dict = \"Azure\"\n Write-Output \"Hello....$dict\"\n}" }, { "code": null, "e": 2176, "s": 2090, "text": "Similarly, we can use the PSCustomObject using the Temporary variable as shown below." }, { "code": null, "e": 2418, "s": 2176, "text": "$Out = @()\n$vms = \"Testvm1\",\"Testvm2\",\"Testvm3\"\n$vmout = $vms | ForEach-Object -Parallel{\n $dict = $using:out\n $dict += [PSCustomObject]@{\n VMName = $_\n Location = 'EastUS'\n }\n return $dict\n}\nWrite-Output \"VM Output\"\n$vmout" }, { "code": null, "e": 2495, "s": 2418, "text": "VMName Location\n------ --------\nTestvm1 EastUS\nTestvm2 EastUS\nTestvm3 EastUS" } ]
Python program to find Indices of Overlapping Substrings
29 Dec, 2020 To count the number of overlapping sub strings in Python we can use the Re module. To get the indices we will use the re.finditer() method. But it returns the count of non-overlapping indices only. Examples: Input: String: “geeksforgeeksforgeeks” ; Pattern: “geeksforgeeks”Output: [0, 8]Explanation: The pattern is overlapping the string from 0th index to 12th index and again overlapping it from 8th index to 20th index. Hence, the output is the starting positions of overlapping i.e index 0 and index 8. Input: String: “barfoobarfoobarfoobarfoobarfoo” ; Pattern: “foobarfoo”Output: [3, 9,15, 21]Explanation: The pattern is overlapping the string from index 3, 9 , 15 and 21. This method returns the count of non-overlapping indices only from a string having multiple occurrences overlapping pattern. Below is a program depicting the use of finditer() method. Python3 # Import required moduleimport re # Function to depict use of finditer() methoddef CntSubstr(pattern, string): # Array storing the indices a = [m.start() for m in re.finditer(pattern, string)] return a # Driver Codestring = 'geeksforgeeksforgeeks'pattern = 'geeksforgeeks' # Printing index values of non-overlapping patternprint(CntSubstr(pattern, string)) Output: [0] Therefore, to get the overlapping indices as well we need to do is escape out of the regular expressions in the pattern. The definition in the explicit function helps to select the characters in a partial way. Approach: re.finditer() helps in finding the indices where the match object occurs. As it returns an iterable object, the start() method helps in return the indices or else it would show that a match object has been found at some location.The standard method in matching using re module is greedy which means the maximum number of characters are matched. Therefore, the ?={0} helps in minimum number of matches.To match it so that partial characters are matched, the re.escape() helps in escaping out the special characters which have been added before such as the ?={0}.The result is that by adding som modifications, the finditer() method returns a list of overlapping indices. re.finditer() helps in finding the indices where the match object occurs. As it returns an iterable object, the start() method helps in return the indices or else it would show that a match object has been found at some location. The standard method in matching using re module is greedy which means the maximum number of characters are matched. Therefore, the ?={0} helps in minimum number of matches. To match it so that partial characters are matched, the re.escape() helps in escaping out the special characters which have been added before such as the ?={0}. The result is that by adding som modifications, the finditer() method returns a list of overlapping indices. Below is the implementation of the above approach: Python3 # Import required moduleimport re # Explicit function to Count# Indices of Overlapping Substringsdef CntSubstr(pattern, string): a = [m.start() for m in re.finditer( '(?={0})'.format(re.escape(pattern)), string)] return a # Driver Codestring1 = 'geeksforgeeksforgeeks'pattern1 = 'geeksforgeeks' string2 = 'barfoobarfoobarfoobarfoobarfoo'pattern2 = 'foobarfoo' # Calling the functionprint(CntSubstr(pattern1, string1))print(CntSubstr(pattern2, string2)) Output: [0, 8] [3, 9, 15, 21] Python Regex-programs Python string-programs python-regex Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python | os.path.join() method Introduction To PYTHON Python OOPs Concepts Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Dec, 2020" }, { "code": null, "e": 226, "s": 28, "text": "To count the number of overlapping sub strings in Python we can use the Re module. To get the indices we will use the re.finditer() method. But it returns the count of non-overlapping indices only." }, { "code": null, "e": 236, "s": 226, "text": "Examples:" }, { "code": null, "e": 536, "s": 236, "text": "Input: String: “geeksforgeeksforgeeks” ; Pattern: “geeksforgeeks”Output: [0, 8]Explanation: The pattern is overlapping the string from 0th index to 12th index and again overlapping it from 8th index to 20th index. Hence, the output is the starting positions of overlapping i.e index 0 and index 8. " }, { "code": null, "e": 708, "s": 536, "text": "Input: String: “barfoobarfoobarfoobarfoobarfoo” ; Pattern: “foobarfoo”Output: [3, 9,15, 21]Explanation: The pattern is overlapping the string from index 3, 9 , 15 and 21." }, { "code": null, "e": 892, "s": 708, "text": "This method returns the count of non-overlapping indices only from a string having multiple occurrences overlapping pattern. Below is a program depicting the use of finditer() method." }, { "code": null, "e": 900, "s": 892, "text": "Python3" }, { "code": "# Import required moduleimport re # Function to depict use of finditer() methoddef CntSubstr(pattern, string): # Array storing the indices a = [m.start() for m in re.finditer(pattern, string)] return a # Driver Codestring = 'geeksforgeeksforgeeks'pattern = 'geeksforgeeks' # Printing index values of non-overlapping patternprint(CntSubstr(pattern, string))", "e": 1275, "s": 900, "text": null }, { "code": null, "e": 1283, "s": 1275, "text": "Output:" }, { "code": null, "e": 1288, "s": 1283, "text": "[0]\n" }, { "code": null, "e": 1498, "s": 1288, "text": "Therefore, to get the overlapping indices as well we need to do is escape out of the regular expressions in the pattern. The definition in the explicit function helps to select the characters in a partial way." }, { "code": null, "e": 1508, "s": 1498, "text": "Approach:" }, { "code": null, "e": 2178, "s": 1508, "text": "re.finditer() helps in finding the indices where the match object occurs. As it returns an iterable object, the start() method helps in return the indices or else it would show that a match object has been found at some location.The standard method in matching using re module is greedy which means the maximum number of characters are matched. Therefore, the ?={0} helps in minimum number of matches.To match it so that partial characters are matched, the re.escape() helps in escaping out the special characters which have been added before such as the ?={0}.The result is that by adding som modifications, the finditer() method returns a list of overlapping indices." }, { "code": null, "e": 2408, "s": 2178, "text": "re.finditer() helps in finding the indices where the match object occurs. As it returns an iterable object, the start() method helps in return the indices or else it would show that a match object has been found at some location." }, { "code": null, "e": 2581, "s": 2408, "text": "The standard method in matching using re module is greedy which means the maximum number of characters are matched. Therefore, the ?={0} helps in minimum number of matches." }, { "code": null, "e": 2742, "s": 2581, "text": "To match it so that partial characters are matched, the re.escape() helps in escaping out the special characters which have been added before such as the ?={0}." }, { "code": null, "e": 2851, "s": 2742, "text": "The result is that by adding som modifications, the finditer() method returns a list of overlapping indices." }, { "code": null, "e": 2902, "s": 2851, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 2910, "s": 2902, "text": "Python3" }, { "code": "# Import required moduleimport re # Explicit function to Count# Indices of Overlapping Substringsdef CntSubstr(pattern, string): a = [m.start() for m in re.finditer( '(?={0})'.format(re.escape(pattern)), string)] return a # Driver Codestring1 = 'geeksforgeeksforgeeks'pattern1 = 'geeksforgeeks' string2 = 'barfoobarfoobarfoobarfoobarfoo'pattern2 = 'foobarfoo' # Calling the functionprint(CntSubstr(pattern1, string1))print(CntSubstr(pattern2, string2))", "e": 3386, "s": 2910, "text": null }, { "code": null, "e": 3394, "s": 3386, "text": "Output:" }, { "code": null, "e": 3417, "s": 3394, "text": "[0, 8]\n[3, 9, 15, 21]\n" }, { "code": null, "e": 3439, "s": 3417, "text": "Python Regex-programs" }, { "code": null, "e": 3462, "s": 3439, "text": "Python string-programs" }, { "code": null, "e": 3475, "s": 3462, "text": "python-regex" }, { "code": null, "e": 3482, "s": 3475, "text": "Python" }, { "code": null, "e": 3498, "s": 3482, "text": "Python Programs" }, { "code": null, "e": 3596, "s": 3498, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3628, "s": 3596, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3655, "s": 3628, "text": "Python Classes and Objects" }, { "code": null, "e": 3686, "s": 3655, "text": "Python | os.path.join() method" }, { "code": null, "e": 3709, "s": 3686, "text": "Introduction To PYTHON" }, { "code": null, "e": 3730, "s": 3709, "text": "Python OOPs Concepts" }, { "code": null, "e": 3752, "s": 3730, "text": "Defaultdict in Python" }, { "code": null, "e": 3791, "s": 3752, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 3829, "s": 3791, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 3878, "s": 3829, "text": "Python | Convert string dictionary to dictionary" } ]
Internet Service Provider (ISP) hierarchy
08 Oct, 2020 Internet Service Provider (ISP) is a company which provides internet connection to end user, but there are basically three levels of ISP. There are 3 levels of Internet Service Provider (ISP): Tier-1 ISP, Tier-2 ISP, and Tier-3 ISP. These are explained as following below. Tier-1 ISP: These ISPs are at the top of the hierarchy and they have a global reach they do not pay for any internet traffic through their network instead lower-tier ISPs have to pay a cost for passing their traffic from one geolocation to another which is not under the reach of that ISPs. Generally, ISPs at the same level connect to each other and allow free traffic passes to each other. Such ISPs are called peers. Due to this cost is saved. They build infrastructure, such as the Atlantic Internet sea cables, to provide traffic to all other Internet service providers, not to end users. Examples: Some examples of tier 1 Internet providers: Examples: Some examples of tier 1 Internet providers: Cogent Communications, Hibernia Networks, AT&T Tier-2 ISP: These ISPs are service provider who connect between tier 1 and tier 3 ISPs. They have regional or country reach and they behave just like Tier-1 ISP for Tier-3 ISPs. Examples: Examples of tier 2 ISPs: Examples: Examples of tier 2 ISPs: Vodafone, Easynet, BT Tier-3 ISP: These ISPs are closest to the end users and helps them to connect to the internet by charging some money. These ISPs work on purchasing model. These ISPs have to pay some cost to Tier-2 ISPs based on traffic generated. Examples: Examples of Tier-3 ISPs: Examples: Examples of Tier-3 ISPs: Comcast, Deutsche Telekom, Verizon Communications dhawal_m55 Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Differences between TCP and UDP RSA Algorithm in Cryptography TCP Server-Client implementation in C Socket Programming in Python GSM in Wireless Communication Differences between IPv4 and IPv6 Secure Socket Layer (SSL) Wireless Application Protocol Mobile Internet Protocol (or Mobile IP) Data encryption standard (DES) | Set 1
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Oct, 2020" }, { "code": null, "e": 262, "s": 28, "text": "Internet Service Provider (ISP) is a company which provides internet connection to end user, but there are basically three levels of ISP. There are 3 levels of Internet Service Provider (ISP): Tier-1 ISP, Tier-2 ISP, and Tier-3 ISP. " }, { "code": null, "e": 303, "s": 262, "text": "These are explained as following below. " }, { "code": null, "e": 952, "s": 303, "text": "Tier-1 ISP: These ISPs are at the top of the hierarchy and they have a global reach they do not pay for any internet traffic through their network instead lower-tier ISPs have to pay a cost for passing their traffic from one geolocation to another which is not under the reach of that ISPs. Generally, ISPs at the same level connect to each other and allow free traffic passes to each other. Such ISPs are called peers. Due to this cost is saved. They build infrastructure, such as the Atlantic Internet sea cables, to provide traffic to all other Internet service providers, not to end users. Examples: Some examples of tier 1 Internet providers: " }, { "code": null, "e": 1007, "s": 952, "text": "Examples: Some examples of tier 1 Internet providers: " }, { "code": null, "e": 1055, "s": 1007, "text": "Cogent Communications,\nHibernia Networks,\nAT&T\n" }, { "code": null, "e": 1269, "s": 1055, "text": "Tier-2 ISP: These ISPs are service provider who connect between tier 1 and tier 3 ISPs. They have regional or country reach and they behave just like Tier-1 ISP for Tier-3 ISPs. Examples: Examples of tier 2 ISPs: " }, { "code": null, "e": 1305, "s": 1269, "text": "Examples: Examples of tier 2 ISPs: " }, { "code": null, "e": 1328, "s": 1305, "text": "Vodafone,\nEasynet,\nBT\n" }, { "code": null, "e": 1595, "s": 1328, "text": "Tier-3 ISP: These ISPs are closest to the end users and helps them to connect to the internet by charging some money. These ISPs work on purchasing model. These ISPs have to pay some cost to Tier-2 ISPs based on traffic generated. Examples: Examples of Tier-3 ISPs: " }, { "code": null, "e": 1631, "s": 1595, "text": "Examples: Examples of Tier-3 ISPs: " }, { "code": null, "e": 1684, "s": 1631, "text": "Comcast,\nDeutsche Telekom,\nVerizon Communications \n " }, { "code": null, "e": 1695, "s": 1684, "text": "dhawal_m55" }, { "code": null, "e": 1713, "s": 1695, "text": "Computer Networks" }, { "code": null, "e": 1731, "s": 1713, "text": "Computer Networks" }, { "code": null, "e": 1829, "s": 1731, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1861, "s": 1829, "text": "Differences between TCP and UDP" }, { "code": null, "e": 1891, "s": 1861, "text": "RSA Algorithm in Cryptography" }, { "code": null, "e": 1929, "s": 1891, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 1958, "s": 1929, "text": "Socket Programming in Python" }, { "code": null, "e": 1988, "s": 1958, "text": "GSM in Wireless Communication" }, { "code": null, "e": 2022, "s": 1988, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 2048, "s": 2022, "text": "Secure Socket Layer (SSL)" }, { "code": null, "e": 2078, "s": 2048, "text": "Wireless Application Protocol" }, { "code": null, "e": 2118, "s": 2078, "text": "Mobile Internet Protocol (or Mobile IP)" } ]
Increment (Decrement) operators require L-value Expression
28 May, 2017 What will be the output of the following program? #include<stdio.h>int main(){ int i = 10; printf("%d", ++(-i)); return 0;} A) 11 B) 10 C) -9 D) None Answer: D, None – Compilation Error. Explanation: In C/C++ the pre-increment (decrement) and the post-increment (decrement) operators require an L-value expression as operand. Providing an R-value or a const qualified variable results in compilation error. In the above program, the expression -i results in R-value which is operand of pre-increment operator. The pre-increment operator requires an L-value as operand, hence the compiler throws an error. The increment/decrement operators needs to update the operand after the sequence point, so they need an L-value. The unary operators such as -, +, won’t need L-value as operand. The expression -(++i) is valid. In C++ the rules are little complicated because of references. We can apply these pre/post increment (decrement) operators on references variables that are not qualified by const. References can also be returned from functions. Puzzle phrased by Venki. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. C-Operators C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n28 May, 2017" }, { "code": null, "e": 104, "s": 54, "text": "What will be the output of the following program?" }, { "code": "#include<stdio.h>int main(){ int i = 10; printf(\"%d\", ++(-i)); return 0;}", "e": 184, "s": 104, "text": null }, { "code": null, "e": 210, "s": 184, "text": "A) 11 B) 10 C) -9 D) None" }, { "code": null, "e": 247, "s": 210, "text": "Answer: D, None – Compilation Error." }, { "code": null, "e": 260, "s": 247, "text": "Explanation:" }, { "code": null, "e": 467, "s": 260, "text": "In C/C++ the pre-increment (decrement) and the post-increment (decrement) operators require an L-value expression as operand. Providing an R-value or a const qualified variable results in compilation error." }, { "code": null, "e": 665, "s": 467, "text": "In the above program, the expression -i results in R-value which is operand of pre-increment operator. The pre-increment operator requires an L-value as operand, hence the compiler throws an error." }, { "code": null, "e": 875, "s": 665, "text": "The increment/decrement operators needs to update the operand after the sequence point, so they need an L-value. The unary operators such as -, +, won’t need L-value as operand. The expression -(++i) is valid." }, { "code": null, "e": 1103, "s": 875, "text": "In C++ the rules are little complicated because of references. We can apply these pre/post increment (decrement) operators on references variables that are not qualified by const. References can also be returned from functions." }, { "code": null, "e": 1253, "s": 1103, "text": "Puzzle phrased by Venki. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 1265, "s": 1253, "text": "C-Operators" }, { "code": null, "e": 1276, "s": 1265, "text": "C Language" }, { "code": null, "e": 1280, "s": 1276, "text": "C++" }, { "code": null, "e": 1284, "s": 1280, "text": "CPP" } ]
How to Calculate an Exponential Moving Average in Python?
12 Dec, 2021 Moving Averages are financial indicators which are used to analyze stock values over a long period of time. i.e. Average value for that long period is calculated. Exponential Moving Averages (EMA) is a type of Moving Averages. It helps users to filter noise and produce a smooth curve. In Moving Averages 2 are very popular. Simple Moving AverageExponential Moving Average Simple Moving Average Exponential Moving Average Simple Moving Average just calculates the average value by performing a mean operation on given data but it changes from interval to interval. But whereas in Exponential Moving Average also uses Simple Mean Average in calculating its average but gives more weightage to the newly added value as the latest value has more weightage. Formula EMAToday=( ValueToday*(Constant/ (1+No. Of Days)) )+( EMAYesterday*(1-(Constant/(1+No. Of Days))) ) Exponential Moving Average value for Today is calculated using Previous Value of Exponential Moving Average. Here the older values get less weightage and newer values get more weightage. This decrease in weightage of values is calculated using Constant value called Decay. So as the number of days gets increases value becomes less significant. It helps to prevent the fluctuations of values. The exponential Weighted Mean method is used to calculate EMA which takes a decay constant as a parameter. Syntax DataFrameName.ewm(com=value) Example 1: As the plot of EMA values is little smoothened when compared to Original Stock values indicates the nature of Exponential Moving Averages. Python3 # import necessary packagesimport pandas as pdimport matplotlib.pyplot as plt # create a dataframestockValues = pd.DataFrame( {'Stock_Values': [60, 102, 103, 104, 101, 105, 102, 103, 103, 102]}) # finding EMA# use any constant value that results in# good smoothened curveema = stockValues.ewm(com=0.4).mean() # Comparison plot b/w stock values & EMAplt.plot(stockValues, label="Stock Values")plt.plot(ema, label="EMA Values")plt.xlabel("Days")plt.ylabel("Price")plt.legend()plt.show() Output Example 2: In the below code we will take the same DataFrame we used above with a different com value which is a higher value compared to that of above. It will be passed as an argument to ewm method. Python3 # import necessary packagesimport pandas as pdimport matplotlib.pyplot as plt # create a dataframestockValues = pd.DataFrame( {'Stock_Values': [60, 102, 103, 104, 101, 105, 102, 103, 103, 102]}) # finding EMA# used constant value as 0.8ema = stockValues.ewm(com=0.8).mean() # Comparison plot b/w stock values & EMAplt.plot(stockValues, label="Stock Values", color="black")plt.plot(ema, label="EMA Values", color="red")plt.xlabel("Days")plt.ylabel("Price")plt.legend()plt.show() Output Example 3: Here we will consider the same DataFrame we used in the above 2 examples with a different com value which is almost close to zero, passed as an argument to ewm method. Python3 # import necessary packagesimport pandas as pdimport matplotlib.pyplot as plt # create a dataframestockValues = pd.DataFrame( {'Stock_Values': [60, 102, 103, 104, 101, 105, 102, 103, 103, 102]}) # finding EMA# com value=0.1 (0 approx)ema = stockValues.ewm(com=0.1).mean() # Comparison plot b/w stock values & EMAplt.plot(stockValues, label="Stock Values", color="blue")plt.plot(ema, label="EMA Values", color="green")plt.xlabel("Days")plt.ylabel("Price")plt.legend()plt.show() Output simranarora5sos Picked 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 ? Python Classes and Objects Python OOPs Concepts Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe Introduction To PYTHON How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Dec, 2021" }, { "code": null, "e": 353, "s": 28, "text": "Moving Averages are financial indicators which are used to analyze stock values over a long period of time. i.e. Average value for that long period is calculated. Exponential Moving Averages (EMA) is a type of Moving Averages. It helps users to filter noise and produce a smooth curve. In Moving Averages 2 are very popular." }, { "code": null, "e": 401, "s": 353, "text": "Simple Moving AverageExponential Moving Average" }, { "code": null, "e": 423, "s": 401, "text": "Simple Moving Average" }, { "code": null, "e": 450, "s": 423, "text": "Exponential Moving Average" }, { "code": null, "e": 782, "s": 450, "text": "Simple Moving Average just calculates the average value by performing a mean operation on given data but it changes from interval to interval. But whereas in Exponential Moving Average also uses Simple Mean Average in calculating its average but gives more weightage to the newly added value as the latest value has more weightage." }, { "code": null, "e": 790, "s": 782, "text": "Formula" }, { "code": null, "e": 890, "s": 790, "text": "EMAToday=( ValueToday*(Constant/ (1+No. Of Days)) )+( EMAYesterday*(1-(Constant/(1+No. Of Days))) )" }, { "code": null, "e": 1284, "s": 890, "text": "Exponential Moving Average value for Today is calculated using Previous Value of Exponential Moving Average. Here the older values get less weightage and newer values get more weightage. This decrease in weightage of values is calculated using Constant value called Decay. So as the number of days gets increases value becomes less significant. It helps to prevent the fluctuations of values." }, { "code": null, "e": 1391, "s": 1284, "text": "The exponential Weighted Mean method is used to calculate EMA which takes a decay constant as a parameter." }, { "code": null, "e": 1398, "s": 1391, "text": "Syntax" }, { "code": null, "e": 1427, "s": 1398, "text": "DataFrameName.ewm(com=value)" }, { "code": null, "e": 1438, "s": 1427, "text": "Example 1:" }, { "code": null, "e": 1577, "s": 1438, "text": "As the plot of EMA values is little smoothened when compared to Original Stock values indicates the nature of Exponential Moving Averages." }, { "code": null, "e": 1585, "s": 1577, "text": "Python3" }, { "code": "# import necessary packagesimport pandas as pdimport matplotlib.pyplot as plt # create a dataframestockValues = pd.DataFrame( {'Stock_Values': [60, 102, 103, 104, 101, 105, 102, 103, 103, 102]}) # finding EMA# use any constant value that results in# good smoothened curveema = stockValues.ewm(com=0.4).mean() # Comparison plot b/w stock values & EMAplt.plot(stockValues, label=\"Stock Values\")plt.plot(ema, label=\"EMA Values\")plt.xlabel(\"Days\")plt.ylabel(\"Price\")plt.legend()plt.show()", "e": 2094, "s": 1585, "text": null }, { "code": null, "e": 2101, "s": 2094, "text": "Output" }, { "code": null, "e": 2112, "s": 2101, "text": "Example 2:" }, { "code": null, "e": 2302, "s": 2112, "text": "In the below code we will take the same DataFrame we used above with a different com value which is a higher value compared to that of above. It will be passed as an argument to ewm method." }, { "code": null, "e": 2310, "s": 2302, "text": "Python3" }, { "code": "# import necessary packagesimport pandas as pdimport matplotlib.pyplot as plt # create a dataframestockValues = pd.DataFrame( {'Stock_Values': [60, 102, 103, 104, 101, 105, 102, 103, 103, 102]}) # finding EMA# used constant value as 0.8ema = stockValues.ewm(com=0.8).mean() # Comparison plot b/w stock values & EMAplt.plot(stockValues, label=\"Stock Values\", color=\"black\")plt.plot(ema, label=\"EMA Values\", color=\"red\")plt.xlabel(\"Days\")plt.ylabel(\"Price\")plt.legend()plt.show()", "e": 2812, "s": 2310, "text": null }, { "code": null, "e": 2820, "s": 2812, "text": "Output " }, { "code": null, "e": 2831, "s": 2820, "text": "Example 3:" }, { "code": null, "e": 2999, "s": 2831, "text": "Here we will consider the same DataFrame we used in the above 2 examples with a different com value which is almost close to zero, passed as an argument to ewm method." }, { "code": null, "e": 3007, "s": 2999, "text": "Python3" }, { "code": "# import necessary packagesimport pandas as pdimport matplotlib.pyplot as plt # create a dataframestockValues = pd.DataFrame( {'Stock_Values': [60, 102, 103, 104, 101, 105, 102, 103, 103, 102]}) # finding EMA# com value=0.1 (0 approx)ema = stockValues.ewm(com=0.1).mean() # Comparison plot b/w stock values & EMAplt.plot(stockValues, label=\"Stock Values\", color=\"blue\")plt.plot(ema, label=\"EMA Values\", color=\"green\")plt.xlabel(\"Days\")plt.ylabel(\"Price\")plt.legend()plt.show()", "e": 3508, "s": 3007, "text": null }, { "code": null, "e": 3515, "s": 3508, "text": "Output" }, { "code": null, "e": 3531, "s": 3515, "text": "simranarora5sos" }, { "code": null, "e": 3538, "s": 3531, "text": "Picked" }, { "code": null, "e": 3552, "s": 3538, "text": "Python-pandas" }, { "code": null, "e": 3559, "s": 3552, "text": "Python" }, { "code": null, "e": 3657, "s": 3559, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3689, "s": 3657, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3716, "s": 3689, "text": "Python Classes and Objects" }, { "code": null, "e": 3737, "s": 3716, "text": "Python OOPs Concepts" }, { "code": null, "e": 3768, "s": 3737, "text": "Python | os.path.join() method" }, { "code": null, "e": 3824, "s": 3768, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 3847, "s": 3824, "text": "Introduction To PYTHON" }, { "code": null, "e": 3889, "s": 3847, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 3931, "s": 3889, "text": "Check if element exists in list in Python" }, { "code": null, "e": 3970, "s": 3931, "text": "Python | datetime.timedelta() function" } ]
Python – Itertools.count()
01 Mar, 2020 Python Itertools are a great way of creating complex iterators which helps in getting faster execution time and writing memory-efficient code. Itertools provide us with functions for creating infinite sequences and itertools.count() is one such function and it does exactly what it sounds like, it counts! Note: For more information, refer to Python Itertools itertools.count() are generally used with map() to generate consecutive data points which is useful in when working with data. It can also be used with zip to add sequences by passing count as parameter. Syntax: itertools.count(start=0, step=1) Parameters:start: Start of the sequence (defaults to 0)step: Difference between consecutive numbers (defaults to 1) Returns: Returns a count object whose .__next__() method returns consecutive values. Let us get a deep understanding of this mighty sword using some simple Python programs. Example #1: Creating evenly spaced list of numbersitertools.count() can be used to generate infinite recursive sequences easily. Lets have a look # Program for creating a list of# even and odd list of integers# using count() from itertools import count # creates a count iterator objectiterator =(count(start = 0, step = 2)) # prints a odd list of integersprint("Even list:", list(next(iterator) for _ in range(5))) # creates a count iterator objectiterator = (count(start = 1, step = 2)) # prints a odd list of integersprint("Odd list:", list(next(iterator) for _ in range(5))) Output : Even list: [0, 2, 4, 6, 8] Odd list: [1, 3, 5, 7, 9] In the same way, we can also generate a sequence of negative and floating-point numbers. For better accuracy of floating-point numbers use (start + step * i for i in count()). Example #2: Emulating enumerate() using itertools.count()As mentioned earlier, count() can be used with zip(). Let’s see how can we use it to mimic the functionality of enumerate() without even knowing the length of list beforehand! # Program to emulate enumerate() # using count() # list containing some stringsmy_list =["Geeks", "for", "Geeks"] # count spits out integers for # each value in my listfor i in zip(count(start = 1, step = 1), my_list): # prints tuple in an enumerated # format print(i) Output : (1, 'Geeks') (2, 'for') (3, 'Geeks') Note: Extra care must be taken while using itertools.count() as it is easy to get stuck in an infinite loop. The following code functions the same as while True: thus proper termination condition must be specified. for i in count(start=0, step=2): print(i) Python-itertools 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 Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts Convert integer to string in Python
[ { "code": null, "e": 53, "s": 25, "text": "\n01 Mar, 2020" }, { "code": null, "e": 359, "s": 53, "text": "Python Itertools are a great way of creating complex iterators which helps in getting faster execution time and writing memory-efficient code. Itertools provide us with functions for creating infinite sequences and itertools.count() is one such function and it does exactly what it sounds like, it counts!" }, { "code": null, "e": 413, "s": 359, "text": "Note: For more information, refer to Python Itertools" }, { "code": null, "e": 617, "s": 413, "text": "itertools.count() are generally used with map() to generate consecutive data points which is useful in when working with data. It can also be used with zip to add sequences by passing count as parameter." }, { "code": null, "e": 658, "s": 617, "text": "Syntax: itertools.count(start=0, step=1)" }, { "code": null, "e": 774, "s": 658, "text": "Parameters:start: Start of the sequence (defaults to 0)step: Difference between consecutive numbers (defaults to 1)" }, { "code": null, "e": 859, "s": 774, "text": "Returns: Returns a count object whose .__next__() method returns consecutive values." }, { "code": null, "e": 947, "s": 859, "text": "Let us get a deep understanding of this mighty sword using some simple Python programs." }, { "code": null, "e": 1093, "s": 947, "text": "Example #1: Creating evenly spaced list of numbersitertools.count() can be used to generate infinite recursive sequences easily. Lets have a look" }, { "code": "# Program for creating a list of# even and odd list of integers# using count() from itertools import count # creates a count iterator objectiterator =(count(start = 0, step = 2)) # prints a odd list of integersprint(\"Even list:\", list(next(iterator) for _ in range(5))) # creates a count iterator objectiterator = (count(start = 1, step = 2)) # prints a odd list of integersprint(\"Odd list:\", list(next(iterator) for _ in range(5)))", "e": 1545, "s": 1093, "text": null }, { "code": null, "e": 1554, "s": 1545, "text": "Output :" }, { "code": null, "e": 1608, "s": 1554, "text": "Even list: [0, 2, 4, 6, 8]\nOdd list: [1, 3, 5, 7, 9]\n" }, { "code": null, "e": 1784, "s": 1608, "text": "In the same way, we can also generate a sequence of negative and floating-point numbers. For better accuracy of floating-point numbers use (start + step * i for i in count())." }, { "code": null, "e": 2017, "s": 1784, "text": "Example #2: Emulating enumerate() using itertools.count()As mentioned earlier, count() can be used with zip(). Let’s see how can we use it to mimic the functionality of enumerate() without even knowing the length of list beforehand!" }, { "code": "# Program to emulate enumerate() # using count() # list containing some stringsmy_list =[\"Geeks\", \"for\", \"Geeks\"] # count spits out integers for # each value in my listfor i in zip(count(start = 1, step = 1), my_list): # prints tuple in an enumerated # format print(i)", "e": 2323, "s": 2017, "text": null }, { "code": null, "e": 2332, "s": 2323, "text": "Output :" }, { "code": null, "e": 2370, "s": 2332, "text": "(1, 'Geeks')\n(2, 'for')\n(3, 'Geeks')\n" }, { "code": null, "e": 2479, "s": 2370, "text": "Note: Extra care must be taken while using itertools.count() as it is easy to get stuck in an infinite loop." }, { "code": null, "e": 2585, "s": 2479, "text": "The following code functions the same as while True: thus proper termination condition must be specified." }, { "code": null, "e": 2633, "s": 2585, "text": "for i in count(start=0, step=2): \n print(i)\n" }, { "code": null, "e": 2650, "s": 2633, "text": "Python-itertools" }, { "code": null, "e": 2657, "s": 2650, "text": "Python" }, { "code": null, "e": 2755, "s": 2657, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2773, "s": 2755, "text": "Python Dictionary" }, { "code": null, "e": 2815, "s": 2773, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2850, "s": 2815, "text": "Read a file line by line in Python" }, { "code": null, "e": 2876, "s": 2850, "text": "Python String | replace()" }, { "code": null, "e": 2908, "s": 2876, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2937, "s": 2908, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2964, "s": 2937, "text": "Python Classes and Objects" }, { "code": null, "e": 2994, "s": 2964, "text": "Iterate over a list in Python" }, { "code": null, "e": 3015, "s": 2994, "text": "Python OOPs Concepts" } ]
PHP array_search() Function
01 Dec, 2021 In this article, we will see how to search the specific value in an array & corresponding return the key using the array_search() function in PHP, & will also understand its implementation through the examples. The array_search() is an inbuilt function in PHP that is used to search for a particular value in an array, and if the value is found then it returns its corresponding key. If there are more than one values then the key of the first matching value will be returned. Syntax: array_search($value, $array, strict_parameter) Parameters: This function takes three parameters as described below: $value: This is the mandatory field that refers to the value that needs to be searched in the array. $array: This is the mandatory field that refers to the original array, which needs to be searched. strict_parameter (optional): This is an optional field that can be set to TRUE or FALSE, and refers to the strictness of search. The default value of this parameter is FALSE. If TRUE, then the function checks for identical elements, i.e., an integer 10 will be treated differently from a string 10.If FALSE, strictness is not maintained. If TRUE, then the function checks for identical elements, i.e., an integer 10 will be treated differently from a string 10. If FALSE, strictness is not maintained. Return Value: The function returns the key of the corresponding value that is passed. If not found then FALSE is returned and if there is more than one match, then the first matched key is returned. Example: The below program illustrates the array_search() function in PHP. PHP <?php // PHP function to illustrate the use of array_search() function Search($value, $array) { return (array_search($value, $array)); } $array = array( "ram", "aakash", "saran", "mohan", "saran" ); $value = "saran"; print_r(Search($value, $array));?> Output: 2 Example: This example illustrates the working of function when the strict_parameter is set to FALSE. Note that the data types of the array and to be searched elements are different. PHP <?php // PHP function to illustrate the use of array_search() function Search($value, $array) { return (array_search($value, $array, false)); } $array = array( 45, 5, 1, 22, 22, 10, 10); $value = "10"; print_r(Search($value, $array));?> Output: 5 Example: In this example, we will be utilizing the above code to find out what will happen if we pass the strict_parameter as TRUE. PHP <?php // PHP function to illustrate the use of array_search() function Search($value, $array) { return (array_search($value, $array, true)); } $array = array(45, 5, 1, 22, 22, 10, 10); $value = "10"; print_r(Search($value, $array));?> Output: No Output Reference: http://php.net/manual/en/function.array-search.php bhaskargeeksforgeeks PHP-array PHP-function PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? PHP | Converting string to Date and DateTime How to receive JSON POST with PHP ? Split a comma delimited string into an array in PHP Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Dec, 2021" }, { "code": null, "e": 505, "s": 28, "text": "In this article, we will see how to search the specific value in an array & corresponding return the key using the array_search() function in PHP, & will also understand its implementation through the examples. The array_search() is an inbuilt function in PHP that is used to search for a particular value in an array, and if the value is found then it returns its corresponding key. If there are more than one values then the key of the first matching value will be returned." }, { "code": null, "e": 513, "s": 505, "text": "Syntax:" }, { "code": null, "e": 560, "s": 513, "text": "array_search($value, $array, strict_parameter)" }, { "code": null, "e": 629, "s": 560, "text": "Parameters: This function takes three parameters as described below:" }, { "code": null, "e": 730, "s": 629, "text": "$value: This is the mandatory field that refers to the value that needs to be searched in the array." }, { "code": null, "e": 829, "s": 730, "text": "$array: This is the mandatory field that refers to the original array, which needs to be searched." }, { "code": null, "e": 1167, "s": 829, "text": "strict_parameter (optional): This is an optional field that can be set to TRUE or FALSE, and refers to the strictness of search. The default value of this parameter is FALSE. If TRUE, then the function checks for identical elements, i.e., an integer 10 will be treated differently from a string 10.If FALSE, strictness is not maintained." }, { "code": null, "e": 1291, "s": 1167, "text": "If TRUE, then the function checks for identical elements, i.e., an integer 10 will be treated differently from a string 10." }, { "code": null, "e": 1331, "s": 1291, "text": "If FALSE, strictness is not maintained." }, { "code": null, "e": 1530, "s": 1331, "text": "Return Value: The function returns the key of the corresponding value that is passed. If not found then FALSE is returned and if there is more than one match, then the first matched key is returned." }, { "code": null, "e": 1605, "s": 1530, "text": "Example: The below program illustrates the array_search() function in PHP." }, { "code": null, "e": 1609, "s": 1605, "text": "PHP" }, { "code": "<?php // PHP function to illustrate the use of array_search() function Search($value, $array) { return (array_search($value, $array)); } $array = array( \"ram\", \"aakash\", \"saran\", \"mohan\", \"saran\" ); $value = \"saran\"; print_r(Search($value, $array));?>", "e": 1900, "s": 1609, "text": null }, { "code": null, "e": 1908, "s": 1900, "text": "Output:" }, { "code": null, "e": 1910, "s": 1908, "text": "2" }, { "code": null, "e": 2093, "s": 1910, "text": "Example: This example illustrates the working of function when the strict_parameter is set to FALSE. Note that the data types of the array and to be searched elements are different. " }, { "code": null, "e": 2097, "s": 2093, "text": "PHP" }, { "code": "<?php // PHP function to illustrate the use of array_search() function Search($value, $array) { return (array_search($value, $array, false)); } $array = array( 45, 5, 1, 22, 22, 10, 10); $value = \"10\"; print_r(Search($value, $array));?>", "e": 2370, "s": 2097, "text": null }, { "code": null, "e": 2378, "s": 2370, "text": "Output:" }, { "code": null, "e": 2380, "s": 2378, "text": "5" }, { "code": null, "e": 2512, "s": 2380, "text": "Example: In this example, we will be utilizing the above code to find out what will happen if we pass the strict_parameter as TRUE." }, { "code": null, "e": 2516, "s": 2512, "text": "PHP" }, { "code": "<?php // PHP function to illustrate the use of array_search() function Search($value, $array) { return (array_search($value, $array, true)); } $array = array(45, 5, 1, 22, 22, 10, 10); $value = \"10\"; print_r(Search($value, $array));?>", "e": 2780, "s": 2516, "text": null }, { "code": null, "e": 2788, "s": 2780, "text": "Output:" }, { "code": null, "e": 2798, "s": 2788, "text": "No Output" }, { "code": null, "e": 2860, "s": 2798, "text": "Reference: http://php.net/manual/en/function.array-search.php" }, { "code": null, "e": 2881, "s": 2860, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 2891, "s": 2881, "text": "PHP-array" }, { "code": null, "e": 2904, "s": 2891, "text": "PHP-function" }, { "code": null, "e": 2908, "s": 2904, "text": "PHP" }, { "code": null, "e": 2925, "s": 2908, "text": "Web Technologies" }, { "code": null, "e": 2929, "s": 2925, "text": "PHP" }, { "code": null, "e": 3027, "s": 2929, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3077, "s": 3027, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 3117, "s": 3077, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 3162, "s": 3117, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 3198, "s": 3162, "text": "How to receive JSON POST with PHP ?" }, { "code": null, "e": 3250, "s": 3198, "text": "Split a comma delimited string into an array in PHP" }, { "code": null, "e": 3312, "s": 3250, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3345, "s": 3312, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3406, "s": 3345, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3456, "s": 3406, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
numpy.empty_like() in Python
29 Nov, 2018 numpy.empty_like(a, dtype = None, order = ‘K’, subok = True) : Return a new array with the same shape and type as a given array.Parameters : shape : Number of rows order : C_contiguous or F_contiguous dtype : [optional, float(by Default)] Data type of returned array. subok : [bool, optional] to make subclass of a or not Return : array with the same shape and type as a given array. # Python Program illustrating# numpy.empty_like method import numpy as geek a = geek.empty_like([2, 2], dtype = int)print("\nMatrix a : \n", a) c = a = ([1,2,3], [4,5,6])print("\nMatrix c : \n", geek.empty_like(c)) Output : Matrix a : [ 16843008 1058682594] Matrix c : [[0 0 0] [0 0 0]] Note :These codes won’t run on online-ID. Please run them on your systems to explore the working. This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Python numpy-arrayCreation Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Nov, 2018" }, { "code": null, "e": 169, "s": 28, "text": "numpy.empty_like(a, dtype = None, order = ‘K’, subok = True) : Return a new array with the same shape and type as a given array.Parameters :" }, { "code": null, "e": 353, "s": 169, "text": "shape : Number of rows\norder : C_contiguous or F_contiguous\ndtype : [optional, float(by Default)] Data type of returned array. \nsubok : [bool, optional] to make subclass of a or not\n" }, { "code": null, "e": 362, "s": 353, "text": "Return :" }, { "code": null, "e": 415, "s": 362, "text": "array with the same shape and type as a given array." }, { "code": "# Python Program illustrating# numpy.empty_like method import numpy as geek a = geek.empty_like([2, 2], dtype = int)print(\"\\nMatrix a : \\n\", a) c = a = ([1,2,3], [4,5,6])print(\"\\nMatrix c : \\n\", geek.empty_like(c))", "e": 633, "s": 415, "text": null }, { "code": null, "e": 642, "s": 633, "text": "Output :" }, { "code": null, "e": 713, "s": 642, "text": "Matrix a : \n [ 16843008 1058682594]\n\nMatrix c : \n [[0 0 0]\n [0 0 0]]\n" }, { "code": null, "e": 811, "s": 713, "text": "Note :These codes won’t run on online-ID. Please run them on your systems to explore the working." }, { "code": null, "e": 1115, "s": 811, "text": "This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 1240, "s": 1115, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 1267, "s": 1240, "text": "Python numpy-arrayCreation" }, { "code": null, "e": 1280, "s": 1267, "text": "Python-numpy" }, { "code": null, "e": 1287, "s": 1280, "text": "Python" }, { "code": null, "e": 1385, "s": 1287, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1403, "s": 1385, "text": "Python Dictionary" }, { "code": null, "e": 1445, "s": 1403, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1467, "s": 1445, "text": "Enumerate() in Python" }, { "code": null, "e": 1502, "s": 1467, "text": "Read a file line by line in Python" }, { "code": null, "e": 1528, "s": 1502, "text": "Python String | replace()" }, { "code": null, "e": 1560, "s": 1528, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1589, "s": 1560, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1616, "s": 1589, "text": "Python Classes and Objects" }, { "code": null, "e": 1646, "s": 1616, "text": "Iterate over a list in Python" } ]
MATLAB - Strings
Creating a character string is quite simple in MATLAB. In fact, we have used it many times. For example, you type the following in the command prompt − my_string = 'Tutorials Point' MATLAB will execute the above statement and return the following result − my_string = Tutorials Point MATLAB considers all variables as arrays, and strings are considered as character arrays. Let us use the whos command to check the variable created above − whos MATLAB will execute the above statement and return the following result − Name Size Bytes Class Attributes my_string 1x16 32 char Interestingly, you can use numeric conversion functions like uint8 or uint16 to convert the characters in the string to their numeric codes. The char function converts the integer vector back to characters − Create a script file and type the following code into it − my_string = 'Tutorial''s Point'; str_ascii = uint8(my_string) % 8-bit ascii values str_back_to_char= char(str_ascii) str_16bit = uint16(my_string) % 16-bit ascii values str_back_to_char = char(str_16bit) When you run the file, it displays the following result − str_ascii = 84 117 116 111 114 105 97 108 39 115 32 80 111 105 110 116 str_back_to_char = Tutorial's Point str_16bit = 84 117 116 111 114 105 97 108 39 115 32 80 111 105 110 116 str_back_to_char = Tutorial's Point The strings we have discussed so far are one-dimensional character arrays; however, we need to store more than that. We need to store more dimensional textual data in our program. This is achieved by creating rectangular character arrays. Simplest way of creating a rectangular character array is by concatenating two or more one-dimensional character arrays, either vertically or horizontally as required. You can combine strings vertically in either of the following ways − Using the MATLAB concatenation operator [] and separating each row with a semicolon (;). Please note that in this method each row must contain the same number of characters. For strings with different lengths, you should pad with space characters as needed. Using the MATLAB concatenation operator [] and separating each row with a semicolon (;). Please note that in this method each row must contain the same number of characters. For strings with different lengths, you should pad with space characters as needed. Using the char function. If the strings are of different lengths, char pads the shorter strings with trailing blanks so that each row has the same number of characters. Using the char function. If the strings are of different lengths, char pads the shorter strings with trailing blanks so that each row has the same number of characters. Create a script file and type the following code into it − doc_profile = ['Zara Ali '; ... 'Sr. Surgeon '; ... 'R N Tagore Cardiology Research Center'] doc_profile = char('Zara Ali', 'Sr. Surgeon', ... 'RN Tagore Cardiology Research Center') When you run the file, it displays the following result − doc_profile = Zara Ali Sr. Surgeon R N Tagore Cardiology Research Center doc_profile = Zara Ali Sr. Surgeon RN Tagore Cardiology Research Center You can combine strings horizontally in either of the following ways − Using the MATLAB concatenation operator, [] and separating the input strings with a comma or a space. This method preserves any trailing spaces in the input arrays. Using the MATLAB concatenation operator, [] and separating the input strings with a comma or a space. This method preserves any trailing spaces in the input arrays. Using the string concatenation function, strcat. This method removes trailing spaces in the inputs. Using the string concatenation function, strcat. This method removes trailing spaces in the inputs. Create a script file and type the following code into it − name = 'Zara Ali '; position = 'Sr. Surgeon '; worksAt = 'R N Tagore Cardiology Research Center'; profile = [name ', ' position ', ' worksAt] profile = strcat(name, ', ', position, ', ', worksAt) When you run the file, it displays the following result − profile = Zara Ali , Sr. Surgeon , R N Tagore Cardiology Research Center profile = Zara Ali,Sr. Surgeon,R N Tagore Cardiology Research Center From our previous discussion, it is clear that combining strings with different lengths could be a pain as all strings in the array has to be of the same length. We have used blank spaces at the end of strings to equalize their length. However, a more efficient way to combine the strings is to convert the resulting array into a cell array. MATLAB cell array can hold different sizes and types of data in an array. Cell arrays provide a more flexible way to store strings of varying length. The cellstr function converts a character array into a cell array of strings. Create a script file and type the following code into it − name = 'Zara Ali '; position = 'Sr. Surgeon '; worksAt = 'R N Tagore Cardiology Research Center'; profile = char(name, position, worksAt); profile = cellstr(profile); disp(profile) When you run the file, it displays the following result − { [1,1] = Zara Ali [2,1] = Sr. Surgeon [3,1] = R N Tagore Cardiology Research Center } MATLAB provides numerous string functions creating, combining, parsing, comparing and manipulating strings. Following table provides brief description of the string functions in MATLAB − The following examples illustrate some of the above-mentioned string functions − Create a script file and type the following code into it − A = pi*1000*ones(1,5); sprintf(' %f \n %.2f \n %+.2f \n %12.2f \n %012.2f \n', A) When you run the file, it displays the following result − ans = 3141.592654 3141.59 +3141.59 3141.59 000003141.59 Create a script file and type the following code into it − %cell array of strings str_array = {'red','blue','green', 'yellow', 'orange'}; % Join strings in cell array into single string str1 = strjoin(str_array, "-") str2 = strjoin(str_array, ",") When you run the file, it displays the following result − str1 = red-blue-green-yellow-orange str2 = red,blue,green,yellow,orange Create a script file and type the following code into it − students = {'Zara Ali', 'Neha Bhatnagar', ... 'Monica Malik', 'Madhu Gautam', ... 'Madhu Sharma', 'Bhawna Sharma',... 'Nuha Ali', 'Reva Dutta', ... 'Sunaina Ali', 'Sofia Kabir'}; % The strrep function searches and replaces sub-string. new_student = strrep(students(8), 'Reva', 'Poulomi') % Display first names first_names = strtok(students) When you run the file, it displays the following result − new_student = { [1,1] = Poulomi Dutta } first_names = { [1,1] = Zara [1,2] = Neha [1,3] = Monica [1,4] = Madhu [1,5] = Madhu [1,6] = Bhawna [1,7] = Nuha [1,8] = Reva [1,9] = Sunaina [1,10] = Sofia } Create a script file and type the following code into it − str1 = 'This is test' str2 = 'This is text' if (strcmp(str1, str2)) sprintf('%s and %s are equal', str1, str2) else sprintf('%s and %s are not equal', str1, str2) end When you run the file, it displays the following result − str1 = This is test str2 = This is text ans = This is test and This is text are not equal
[ { "code": null, "e": 2427, "s": 2275, "text": "Creating a character string is quite simple in MATLAB. In fact, we have used it many times. For example, you type the following in the command prompt −" }, { "code": null, "e": 2457, "s": 2427, "text": "my_string = 'Tutorials Point'" }, { "code": null, "e": 2531, "s": 2457, "text": "MATLAB will execute the above statement and return the following result −" }, { "code": null, "e": 2560, "s": 2531, "text": "my_string = Tutorials Point\n" }, { "code": null, "e": 2716, "s": 2560, "text": "MATLAB considers all variables as arrays, and strings are considered as character arrays. Let us use the whos command to check the variable created above −" }, { "code": null, "e": 2721, "s": 2716, "text": "whos" }, { "code": null, "e": 2795, "s": 2721, "text": "MATLAB will execute the above statement and return the following result −" }, { "code": null, "e": 2897, "s": 2795, "text": "Name Size Bytes Class Attributes\nmy_string 1x16 32 char\n" }, { "code": null, "e": 3105, "s": 2897, "text": "Interestingly, you can use numeric conversion functions like uint8 or uint16 to convert the characters in the string to their numeric codes. The char function converts the integer vector back to characters −" }, { "code": null, "e": 3164, "s": 3105, "text": "Create a script file and type the following code into it −" }, { "code": null, "e": 3385, "s": 3164, "text": "my_string = 'Tutorial''s Point';\nstr_ascii = uint8(my_string) % 8-bit ascii values\nstr_back_to_char= char(str_ascii) \nstr_16bit = uint16(my_string) % 16-bit ascii values\nstr_back_to_char = char(str_16bit) " }, { "code": null, "e": 3443, "s": 3385, "text": "When you run the file, it displays the following result −" }, { "code": null, "e": 3706, "s": 3443, "text": "str_ascii =\n\n 84 117 116 111 114 105 97 108 39 115 32 80 111 105 110 116\n\nstr_back_to_char = Tutorial's Point\nstr_16bit =\n\n 84 117 116 111 114 105 97 108 39 115 32 80 111 105 110 116\n\nstr_back_to_char = Tutorial's Point\n" }, { "code": null, "e": 3945, "s": 3706, "text": "The strings we have discussed so far are one-dimensional character arrays; however, we need to store more than that. We need to store more dimensional textual data in our program. This is achieved by creating rectangular character arrays." }, { "code": null, "e": 4113, "s": 3945, "text": "Simplest way of creating a rectangular character array is by concatenating two or more one-dimensional character arrays, either vertically or horizontally as required." }, { "code": null, "e": 4182, "s": 4113, "text": "You can combine strings vertically in either of the following ways −" }, { "code": null, "e": 4440, "s": 4182, "text": "Using the MATLAB concatenation operator [] and separating each row with a semicolon (;). Please note that in this method each row must contain the same number of characters. For strings with different lengths, you should pad with space characters as needed." }, { "code": null, "e": 4698, "s": 4440, "text": "Using the MATLAB concatenation operator [] and separating each row with a semicolon (;). Please note that in this method each row must contain the same number of characters. For strings with different lengths, you should pad with space characters as needed." }, { "code": null, "e": 4867, "s": 4698, "text": "Using the char function. If the strings are of different lengths, char pads the shorter strings with trailing blanks so that each row has the same number of characters." }, { "code": null, "e": 5036, "s": 4867, "text": "Using the char function. If the strings are of different lengths, char pads the shorter strings with trailing blanks so that each row has the same number of characters." }, { "code": null, "e": 5095, "s": 5036, "text": "Create a script file and type the following code into it −" }, { "code": null, "e": 5379, "s": 5095, "text": "doc_profile = ['Zara Ali '; ...\n 'Sr. Surgeon '; ...\n 'R N Tagore Cardiology Research Center']\ndoc_profile = char('Zara Ali', 'Sr. Surgeon', ...\n 'RN Tagore Cardiology Research Center')" }, { "code": null, "e": 5437, "s": 5379, "text": "When you run the file, it displays the following result −" }, { "code": null, "e": 5691, "s": 5437, "text": "doc_profile =\nZara Ali \nSr. Surgeon \nR N Tagore Cardiology Research Center\ndoc_profile =\nZara Ali \nSr. Surgeon \nRN Tagore Cardiology Research Center\n" }, { "code": null, "e": 5762, "s": 5691, "text": "You can combine strings horizontally in either of the following ways −" }, { "code": null, "e": 5927, "s": 5762, "text": "Using the MATLAB concatenation operator, [] and separating the input strings with a comma or a space. This method preserves any trailing spaces in the input arrays." }, { "code": null, "e": 6092, "s": 5927, "text": "Using the MATLAB concatenation operator, [] and separating the input strings with a comma or a space. This method preserves any trailing spaces in the input arrays." }, { "code": null, "e": 6192, "s": 6092, "text": "Using the string concatenation function, strcat. This method removes trailing spaces in the inputs." }, { "code": null, "e": 6292, "s": 6192, "text": "Using the string concatenation function, strcat. This method removes trailing spaces in the inputs." }, { "code": null, "e": 6351, "s": 6292, "text": "Create a script file and type the following code into it −" }, { "code": null, "e": 6606, "s": 6351, "text": "name = 'Zara Ali ';\nposition = 'Sr. Surgeon '; \nworksAt = 'R N Tagore Cardiology Research Center';\nprofile = [name ', ' position ', ' worksAt]\nprofile = strcat(name, ', ', position, ', ', worksAt)" }, { "code": null, "e": 6664, "s": 6606, "text": "When you run the file, it displays the following result −" }, { "code": null, "e": 6817, "s": 6664, "text": "profile = Zara Ali , Sr. Surgeon , R N Tagore Cardiology Research Center\nprofile = Zara Ali,Sr. Surgeon,R N Tagore Cardiology Research Center\n" }, { "code": null, "e": 7053, "s": 6817, "text": "From our previous discussion, it is clear that combining strings with different lengths could be a pain as all strings in the array has to be of the same length. We have used blank spaces at the end of strings to equalize their length." }, { "code": null, "e": 7159, "s": 7053, "text": "However, a more efficient way to combine the strings is to convert the resulting array into a cell array." }, { "code": null, "e": 7309, "s": 7159, "text": "MATLAB cell array can hold different sizes and types of data in an array. Cell arrays provide a more flexible way to store strings of varying length." }, { "code": null, "e": 7387, "s": 7309, "text": "The cellstr function converts a character array into a cell array of strings." }, { "code": null, "e": 7446, "s": 7387, "text": "Create a script file and type the following code into it −" }, { "code": null, "e": 7686, "s": 7446, "text": "name = 'Zara Ali ';\nposition = 'Sr. Surgeon '; \nworksAt = 'R N Tagore Cardiology Research Center';\nprofile = char(name, position, worksAt);\nprofile = cellstr(profile);\ndisp(profile)" }, { "code": null, "e": 7744, "s": 7686, "text": "When you run the file, it displays the following result −" }, { "code": null, "e": 8077, "s": 7744, "text": "{ \n [1,1] = Zara Ali \n [2,1] = Sr. Surgeon \n [3,1] = R N Tagore Cardiology Research Center \n} \n" }, { "code": null, "e": 8185, "s": 8077, "text": "MATLAB provides numerous string functions creating, combining, parsing, comparing and manipulating strings." }, { "code": null, "e": 8264, "s": 8185, "text": "Following table provides brief description of the string functions in MATLAB −" }, { "code": null, "e": 8345, "s": 8264, "text": "The following examples illustrate some of the above-mentioned string functions −" }, { "code": null, "e": 8404, "s": 8345, "text": "Create a script file and type the following code into it −" }, { "code": null, "e": 8486, "s": 8404, "text": "A = pi*1000*ones(1,5);\nsprintf(' %f \\n %.2f \\n %+.2f \\n %12.2f \\n %012.2f \\n', A)" }, { "code": null, "e": 8544, "s": 8486, "text": "When you run the file, it displays the following result −" }, { "code": null, "e": 8622, "s": 8544, "text": "ans = 3141.592654 \n 3141.59 \n +3141.59 \n 3141.59 \n 000003141.59 \n" }, { "code": null, "e": 8681, "s": 8622, "text": "Create a script file and type the following code into it −" }, { "code": null, "e": 8871, "s": 8681, "text": "%cell array of strings\nstr_array = {'red','blue','green', 'yellow', 'orange'};\n\n% Join strings in cell array into single string\nstr1 = strjoin(str_array, \"-\")\nstr2 = strjoin(str_array, \",\")" }, { "code": null, "e": 8929, "s": 8871, "text": "When you run the file, it displays the following result −" }, { "code": null, "e": 9002, "s": 8929, "text": "str1 = red-blue-green-yellow-orange\nstr2 = red,blue,green,yellow,orange\n" }, { "code": null, "e": 9061, "s": 9002, "text": "Create a script file and type the following code into it −" }, { "code": null, "e": 9452, "s": 9061, "text": "students = {'Zara Ali', 'Neha Bhatnagar', ...\n 'Monica Malik', 'Madhu Gautam', ...\n 'Madhu Sharma', 'Bhawna Sharma',...\n 'Nuha Ali', 'Reva Dutta', ...\n 'Sunaina Ali', 'Sofia Kabir'};\n \n% The strrep function searches and replaces sub-string.\nnew_student = strrep(students(8), 'Reva', 'Poulomi')\n% Display first names\nfirst_names = strtok(students)" }, { "code": null, "e": 9510, "s": 9452, "text": "When you run the file, it displays the following result −" }, { "code": null, "e": 9745, "s": 9510, "text": "new_student = \n{\n [1,1] = Poulomi Dutta\n}\nfirst_names = \n{\n [1,1] = Zara\n [1,2] = Neha\n [1,3] = Monica\n [1,4] = Madhu\n [1,5] = Madhu\n [1,6] = Bhawna\n [1,7] = Nuha\n [1,8] = Reva\n [1,9] = Sunaina\n [1,10] = Sofia\n}\n" }, { "code": null, "e": 9804, "s": 9745, "text": "Create a script file and type the following code into it −" }, { "code": null, "e": 9977, "s": 9804, "text": "str1 = 'This is test'\nstr2 = 'This is text'\nif (strcmp(str1, str2))\n sprintf('%s and %s are equal', str1, str2)\nelse\n sprintf('%s and %s are not equal', str1, str2)\nend" }, { "code": null, "e": 10035, "s": 9977, "text": "When you run the file, it displays the following result −" } ]
How to Create Your Own Package in Golang?
15 Sep, 2021 Go language is a high-level programming language developed at Google Inc. A high-level language is in simple words, the programming language category created by humans for human understanding. Before we jump onto high terminologies as packages, modules, functions, etc. let’s write the most basic program in Golang. The most basic program in the programming world is the Hello world. Go package main import "fmt" // Main functionfunc main() { fmt.Printf("Hello World!")} Since Go lang run is not supported on this IDLE, I’ve attached a screenshot of the output below. The first program that prints hello world on the console. The output screen is likely to be as in the image if you use Visual Studio on the Windows platform. We must have seen this program a million times until now but do we really understand what’s in it? Or do we just scan the keywords written in the code and copy-paste it and then implement in further in our programs? We all know the answer! But let’s try to understand the code now. package main This statement makes the package available as an executable code of the program. A package can simply be explained as a capsule that binds multiple pieces of code together which may contain multiple libraries, multiple functionalities all included in one capsule that can be easily used in any program by the user by just importing or mentioning the package. import "fmt" Here fmt is a built-in package provided by Go lang. All basic print operations, scan operations, etc fall under this package. func main() It is a simple declaration of the function main that holds the executable driver code. fmt.Printf("Hello world!") In this line, it may appear simple but there is a logic behind that simple dot (‘.’) that lies in between fmt and Printf. The dot is a mediator that performs an important search. The term preceding the dot here is the package name and the name succeeding the dot here is the set of function that belongs to the package mentioned before the dot. Printf is a function that lies under the fmt package and it offers the “Printing input string (in this case) on the console in one line”. As discussed earlier, fmt is a pre-built package, developed by someone else. We find many things in these pre-built codes but why can we not try building our own packages? Well, building our own packages increases the readability, reusability, and efficiency among our work organization as it will be specific about the work we do and not the rest of the world! Let’s see a demo of how to build a simple new package. Well, before you proceed you need to ensure the following steps, these are essential to ensure smooth workflow: Check your GOPATH in environment variables and set it to the directory which contains all Go files.Create a new folder with the name of the package you wish to create.In the folder created in step 2, create your go file that holds the Go package code you wish to create.It is recommended that you name your file the same name as your package name, it is not mandatory but just ensures less chaotic imports.Watch the detailed demo below to get an idea of how things work! Check your GOPATH in environment variables and set it to the directory which contains all Go files. Create a new folder with the name of the package you wish to create. In the folder created in step 2, create your go file that holds the Go package code you wish to create. It is recommended that you name your file the same name as your package name, it is not mandatory but just ensures less chaotic imports. Watch the detailed demo below to get an idea of how things work! Go package calculator// I'm creating a simple calculator that// performs one calculator operation as per the// user's choice. For readability of code,// I named the package as "calculator"// And remember, the first executable line// must always be as mentioned above:// the keyword package followed by a name// that you wish to give to your package*//* indicates very very important import "fmt"// importing fmt package for basic// printing & scan operations func Calc() { // a simple Calc function that contains // all code within and has no return // type mentioned // Println prints the input string in new line fmt.Println("Welcome to calculator") fmt.Println("********************MAIN MENU*************************") fmt.Println("1. Add") fmt.Println("2. Subtract") fmt.Println("3. Multiply") fmt.Println("4. Divide") fmt.Println("******************************************************") var choice int // choice will store the user's // input as per the menu shown above fmt.Scan(&choice) var a, b int // After the choice of operation, user // will be asked to enter 2 int // values one by one to perform // the operation on fmt.Println("Enter value of a: ") fmt.Scan(&a) fmt.Println("Enter value of b: ") fmt.Scan(&b) if( choice == 1 ){ // choice 1 activates this part --> addition ans := a + b fmt.Println("Answer = ", ans) } else if( choice == 2 ){ // choice 2 activates this part --> subtraction ans := a - b fmt.Println("Answer = ", ans) } else if( choice == 3 ){ // choice 3 activates this part --> multiplication ans := a * b fmt.Println("Answer = ", ans) } else { // choice 4 activates this part --> division // remember not to enter second value as 0 // as that would raise a DivideByZero error // or may display infinity ans := a / b fmt.Println("Answer = ", ans) } fmt.Println("******************************************************") fmt.Println("Thank you for using calculator! Have a nice day ahead. ^-^") fmt.Println("******************************************************")} Well, package codes are different from normal file codes. So our process doesn’t end here. Writing your code inside the package file is the first step. After writing the code, save your file as the name of the package that you mentioned in your first line of code. For Example, In my case: calculator.go After naming your file, you need to perform some important steps. As this is a package that you are creating, you will need the go compiler to build and compile your code. And for that, go to the folder where your package file code is located. Open command prompt in that directory. Run the following command in cmd: go install This command will compile your Go package and make it ready for use. Now create the main file to use your first package. Here, we are sharing the code from our main file Go package main import "myprograms/go-packages/calculator"// this is the local directory// where my package file is located func main() { calculator.Calc() // name of my package dot name of the // function I wish to execute in that // package} Save your code and execute the following command on cmd in the directory where the main file is located ———–> “go build file_name.go” For example: go build main.go And now your main file has compiled successfully. To execute it, enter the following command on your cmd: “file_name” For example: main You will notice that the calc function executes exactly as coded. A demo from my package run is shown below for reference. This is the calculator package code file and in the terminal section are the commands that need to be executed and the outputs are also shown in the screenshot mentioned above. Also, take note of the directories where I’ve opened the terminal and what commands have been executed. This is the main code file where the package is imported and executed. Observe how simple the main file code becomes once you create a package. The package can be reused a million times in any code now. If you make it available on the cloud then anyone on the web can use it. Notice the commands on the terminal and the directory as they’re very important. simranarora5sos Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. strings.Replace() Function in Golang With Examples fmt.Sprintf() Function in Golang With Examples Golang Maps How to Split a String in Golang? Interfaces in Golang Different Ways to Find the Type of Variable in Golang How to Parse JSON in Golang? How to Trim a String in Golang? How to convert a string in lower case in Golang? How to compare times in Golang?
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Sep, 2021" }, { "code": null, "e": 413, "s": 28, "text": "Go language is a high-level programming language developed at Google Inc. A high-level language is in simple words, the programming language category created by humans for human understanding. Before we jump onto high terminologies as packages, modules, functions, etc. let’s write the most basic program in Golang. The most basic program in the programming world is the Hello world. " }, { "code": null, "e": 416, "s": 413, "text": "Go" }, { "code": "package main import \"fmt\" // Main functionfunc main() { fmt.Printf(\"Hello World!\")}", "e": 510, "s": 416, "text": null }, { "code": null, "e": 607, "s": 510, "text": "Since Go lang run is not supported on this IDLE, I’ve attached a screenshot of the output below." }, { "code": null, "e": 765, "s": 607, "text": "The first program that prints hello world on the console. The output screen is likely to be as in the image if you use Visual Studio on the Windows platform." }, { "code": null, "e": 1047, "s": 765, "text": "We must have seen this program a million times until now but do we really understand what’s in it? Or do we just scan the keywords written in the code and copy-paste it and then implement in further in our programs? We all know the answer! But let’s try to understand the code now." }, { "code": null, "e": 1060, "s": 1047, "text": "package main" }, { "code": null, "e": 1419, "s": 1060, "text": "This statement makes the package available as an executable code of the program. A package can simply be explained as a capsule that binds multiple pieces of code together which may contain multiple libraries, multiple functionalities all included in one capsule that can be easily used in any program by the user by just importing or mentioning the package." }, { "code": null, "e": 1432, "s": 1419, "text": "import \"fmt\"" }, { "code": null, "e": 1558, "s": 1432, "text": "Here fmt is a built-in package provided by Go lang. All basic print operations, scan operations, etc fall under this package." }, { "code": null, "e": 1570, "s": 1558, "text": "func main()" }, { "code": null, "e": 1657, "s": 1570, "text": "It is a simple declaration of the function main that holds the executable driver code." }, { "code": null, "e": 1684, "s": 1657, "text": "fmt.Printf(\"Hello world!\")" }, { "code": null, "e": 2167, "s": 1684, "text": "In this line, it may appear simple but there is a logic behind that simple dot (‘.’) that lies in between fmt and Printf. The dot is a mediator that performs an important search. The term preceding the dot here is the package name and the name succeeding the dot here is the set of function that belongs to the package mentioned before the dot. Printf is a function that lies under the fmt package and it offers the “Printing input string (in this case) on the console in one line”." }, { "code": null, "e": 2584, "s": 2167, "text": "As discussed earlier, fmt is a pre-built package, developed by someone else. We find many things in these pre-built codes but why can we not try building our own packages? Well, building our own packages increases the readability, reusability, and efficiency among our work organization as it will be specific about the work we do and not the rest of the world! Let’s see a demo of how to build a simple new package." }, { "code": null, "e": 2696, "s": 2584, "text": "Well, before you proceed you need to ensure the following steps, these are essential to ensure smooth workflow:" }, { "code": null, "e": 3168, "s": 2696, "text": "Check your GOPATH in environment variables and set it to the directory which contains all Go files.Create a new folder with the name of the package you wish to create.In the folder created in step 2, create your go file that holds the Go package code you wish to create.It is recommended that you name your file the same name as your package name, it is not mandatory but just ensures less chaotic imports.Watch the detailed demo below to get an idea of how things work! " }, { "code": null, "e": 3268, "s": 3168, "text": "Check your GOPATH in environment variables and set it to the directory which contains all Go files." }, { "code": null, "e": 3337, "s": 3268, "text": "Create a new folder with the name of the package you wish to create." }, { "code": null, "e": 3441, "s": 3337, "text": "In the folder created in step 2, create your go file that holds the Go package code you wish to create." }, { "code": null, "e": 3578, "s": 3441, "text": "It is recommended that you name your file the same name as your package name, it is not mandatory but just ensures less chaotic imports." }, { "code": null, "e": 3644, "s": 3578, "text": "Watch the detailed demo below to get an idea of how things work! " }, { "code": null, "e": 3647, "s": 3644, "text": "Go" }, { "code": "package calculator// I'm creating a simple calculator that// performs one calculator operation as per the// user's choice. For readability of code,// I named the package as \"calculator\"// And remember, the first executable line// must always be as mentioned above:// the keyword package followed by a name// that you wish to give to your package*//* indicates very very important import \"fmt\"// importing fmt package for basic// printing & scan operations func Calc() { // a simple Calc function that contains // all code within and has no return // type mentioned // Println prints the input string in new line fmt.Println(\"Welcome to calculator\") fmt.Println(\"********************MAIN MENU*************************\") fmt.Println(\"1. Add\") fmt.Println(\"2. Subtract\") fmt.Println(\"3. Multiply\") fmt.Println(\"4. Divide\") fmt.Println(\"******************************************************\") var choice int // choice will store the user's // input as per the menu shown above fmt.Scan(&choice) var a, b int // After the choice of operation, user // will be asked to enter 2 int // values one by one to perform // the operation on fmt.Println(\"Enter value of a: \") fmt.Scan(&a) fmt.Println(\"Enter value of b: \") fmt.Scan(&b) if( choice == 1 ){ // choice 1 activates this part --> addition ans := a + b fmt.Println(\"Answer = \", ans) } else if( choice == 2 ){ // choice 2 activates this part --> subtraction ans := a - b fmt.Println(\"Answer = \", ans) } else if( choice == 3 ){ // choice 3 activates this part --> multiplication ans := a * b fmt.Println(\"Answer = \", ans) } else { // choice 4 activates this part --> division // remember not to enter second value as 0 // as that would raise a DivideByZero error // or may display infinity ans := a / b fmt.Println(\"Answer = \", ans) } fmt.Println(\"******************************************************\") fmt.Println(\"Thank you for using calculator! Have a nice day ahead. ^-^\") fmt.Println(\"******************************************************\")}", "e": 5853, "s": 3647, "text": null }, { "code": null, "e": 6144, "s": 5853, "text": "Well, package codes are different from normal file codes. So our process doesn’t end here. Writing your code inside the package file is the first step. After writing the code, save your file as the name of the package that you mentioned in your first line of code. For Example, In my case: " }, { "code": null, "e": 6158, "s": 6144, "text": "calculator.go" }, { "code": null, "e": 6478, "s": 6158, "text": "After naming your file, you need to perform some important steps. As this is a package that you are creating, you will need the go compiler to build and compile your code. And for that, go to the folder where your package file code is located. Open command prompt in that directory. Run the following command in cmd: " }, { "code": null, "e": 6489, "s": 6478, "text": "go install" }, { "code": null, "e": 6660, "s": 6489, "text": "This command will compile your Go package and make it ready for use. Now create the main file to use your first package. Here, we are sharing the code from our main file " }, { "code": null, "e": 6663, "s": 6660, "text": "Go" }, { "code": "package main import \"myprograms/go-packages/calculator\"// this is the local directory// where my package file is located func main() { calculator.Calc() // name of my package dot name of the // function I wish to execute in that // package}", "e": 6916, "s": 6663, "text": null }, { "code": null, "e": 7051, "s": 6916, "text": "Save your code and execute the following command on cmd in the directory where the main file is located ———–> “go build file_name.go” " }, { "code": null, "e": 7082, "s": 7051, "text": "For example: go build main.go " }, { "code": null, "e": 7200, "s": 7082, "text": "And now your main file has compiled successfully. To execute it, enter the following command on your cmd: “file_name”" }, { "code": null, "e": 7218, "s": 7200, "text": "For example: main" }, { "code": null, "e": 7341, "s": 7218, "text": "You will notice that the calc function executes exactly as coded. A demo from my package run is shown below for reference." }, { "code": null, "e": 7622, "s": 7341, "text": "This is the calculator package code file and in the terminal section are the commands that need to be executed and the outputs are also shown in the screenshot mentioned above. Also, take note of the directories where I’ve opened the terminal and what commands have been executed." }, { "code": null, "e": 7979, "s": 7622, "text": "This is the main code file where the package is imported and executed. Observe how simple the main file code becomes once you create a package. The package can be reused a million times in any code now. If you make it available on the cloud then anyone on the web can use it. Notice the commands on the terminal and the directory as they’re very important." }, { "code": null, "e": 7995, "s": 7979, "text": "simranarora5sos" }, { "code": null, "e": 8007, "s": 7995, "text": "Go Language" }, { "code": null, "e": 8105, "s": 8007, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8156, "s": 8105, "text": "strings.Replace() Function in Golang With Examples" }, { "code": null, "e": 8203, "s": 8156, "text": "fmt.Sprintf() Function in Golang With Examples" }, { "code": null, "e": 8215, "s": 8203, "text": "Golang Maps" }, { "code": null, "e": 8248, "s": 8215, "text": "How to Split a String in Golang?" }, { "code": null, "e": 8269, "s": 8248, "text": "Interfaces in Golang" }, { "code": null, "e": 8323, "s": 8269, "text": "Different Ways to Find the Type of Variable in Golang" }, { "code": null, "e": 8352, "s": 8323, "text": "How to Parse JSON in Golang?" }, { "code": null, "e": 8384, "s": 8352, "text": "How to Trim a String in Golang?" }, { "code": null, "e": 8433, "s": 8384, "text": "How to convert a string in lower case in Golang?" } ]
Python | Scipy integrate.simps() method
23 Jan, 2020 With the help of scipy.integrate.simps() method, we can get the integration of y(x) using samples along the axis and composite simpson’s rule by using scipy.integrate.simps() method. Syntax : scipy.integrate.simps(y, x)Return : Return the integrated value of y(x) using samples. Example #1 :In this example we can see that by using scipy.integrate.simps() method, we are able to get the integrated value of y(x) using samples and composite simpson’s rule by using this method. # import numpy and scipy.integrateimport numpy as npfrom scipy import integrate x = np.arange(0, 10)y = np.arange(0, 10)# using scipy.integrate.simps() methodgfg = integrate.simps(y, x) print(gfg) Output : 40.5 Example #2 : # import numpy and scipy.integrateimport numpy as npfrom scipy import integrate x = np.arange(0, 10)y = np.sqrt(x)# using scipy.integrate.simps() methodgfg = integrate.simps(y, x) print(gfg) Output : 17.875036119764566 Python-scipy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Jan, 2020" }, { "code": null, "e": 211, "s": 28, "text": "With the help of scipy.integrate.simps() method, we can get the integration of y(x) using samples along the axis and composite simpson’s rule by using scipy.integrate.simps() method." }, { "code": null, "e": 307, "s": 211, "text": "Syntax : scipy.integrate.simps(y, x)Return : Return the integrated value of y(x) using samples." }, { "code": null, "e": 505, "s": 307, "text": "Example #1 :In this example we can see that by using scipy.integrate.simps() method, we are able to get the integrated value of y(x) using samples and composite simpson’s rule by using this method." }, { "code": "# import numpy and scipy.integrateimport numpy as npfrom scipy import integrate x = np.arange(0, 10)y = np.arange(0, 10)# using scipy.integrate.simps() methodgfg = integrate.simps(y, x) print(gfg)", "e": 704, "s": 505, "text": null }, { "code": null, "e": 713, "s": 704, "text": "Output :" }, { "code": null, "e": 718, "s": 713, "text": "40.5" }, { "code": null, "e": 731, "s": 718, "text": "Example #2 :" }, { "code": "# import numpy and scipy.integrateimport numpy as npfrom scipy import integrate x = np.arange(0, 10)y = np.sqrt(x)# using scipy.integrate.simps() methodgfg = integrate.simps(y, x) print(gfg)", "e": 924, "s": 731, "text": null }, { "code": null, "e": 933, "s": 924, "text": "Output :" }, { "code": null, "e": 952, "s": 933, "text": "17.875036119764566" }, { "code": null, "e": 965, "s": 952, "text": "Python-scipy" }, { "code": null, "e": 972, "s": 965, "text": "Python" }, { "code": null, "e": 1070, "s": 972, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1102, "s": 1070, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1129, "s": 1102, "text": "Python Classes and Objects" }, { "code": null, "e": 1150, "s": 1129, "text": "Python OOPs Concepts" }, { "code": null, "e": 1173, "s": 1150, "text": "Introduction To PYTHON" }, { "code": null, "e": 1229, "s": 1173, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1260, "s": 1229, "text": "Python | os.path.join() method" }, { "code": null, "e": 1302, "s": 1260, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1344, "s": 1302, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1383, "s": 1344, "text": "Python | Get unique values from a list" } ]
HTML <input> size Attribute
The size attribute of the <input> element is used to set the width of the input. The more the width would lead to a textbox with more width. You can set the size attribute for the following input types − text, search, email, password, tel and url. Following is the syntax − <input size="size_num"> Above, size_num is the width of the input you need to set in numbers. The default is 20. Let us now see an example to implement the size attribute of the <input> element − Live Demo <!DOCTYPE html> <html> <body> <h2>Register</h2> <form action="" method="get"> Id − <input type="text" name="id" placeholder="Enter UserId here..." size = "25" required><br> Password − <input type="password" name="pwd" placeholder="Enter password here..." required><br> DOB − <input type="date" name="dob" placeholder="Enter date of birth here..."><br> Telephone − <input type="tel" name="tel" placeholder="Enter mobile number here..." required><br> Email − <input type="email" name="email" placeholder="Enter email here..." size = "35"><br><br> <button type="submit" value="Submit">Submit</button> </form> </body> </html> In the above example, we have some fields with a button − <form action="" method="get"> Id − <input type="text" name="id" placeholder="Enter UserId here..." size = "25" required><br> Password − <input type="password" name="pwd" placeholder="Enter password here..." required><br> DOB − <input type="date" name="dob" placeholder="Enter date of birth here..."><br> Telephone − <input type="tel" name="tel" placeholder="Enter mobile number here..." required><br> Email − <input type="email" name="email" placeholder="Enter email here..." size = "35"><br><br> <button type="submit" value="Submit">Submit</button> </form> Now, let’s say we want a bigger textbox i.e. with bigger width. For that, we used the size attribute to set the width in numbers − <input type="text" name="id" placeholder="Enter UserId here..." size = "25" required>
[ { "code": null, "e": 1435, "s": 1187, "text": "The size attribute of the <input> element is used to set the width of the input. The more the width would lead to a textbox with more width. You can set the size attribute for the following input types − text, search, email, password, tel and url." }, { "code": null, "e": 1461, "s": 1435, "text": "Following is the syntax −" }, { "code": null, "e": 1485, "s": 1461, "text": "<input size=\"size_num\">" }, { "code": null, "e": 1574, "s": 1485, "text": "Above, size_num is the width of the input you need to set in numbers. The default is 20." }, { "code": null, "e": 1657, "s": 1574, "text": "Let us now see an example to implement the size attribute of the <input> element −" }, { "code": null, "e": 1668, "s": 1657, "text": " Live Demo" }, { "code": null, "e": 2308, "s": 1668, "text": "<!DOCTYPE html>\n<html>\n<body>\n<h2>Register</h2>\n<form action=\"\" method=\"get\">\n Id − <input type=\"text\" name=\"id\" placeholder=\"Enter UserId here...\" size = \"25\" required><br>\n Password − <input type=\"password\" name=\"pwd\" placeholder=\"Enter password here...\" required><br>\n DOB − <input type=\"date\" name=\"dob\" placeholder=\"Enter date of birth here...\"><br>\n Telephone − <input type=\"tel\" name=\"tel\" placeholder=\"Enter mobile number here...\" required><br>\n Email − <input type=\"email\" name=\"email\" placeholder=\"Enter email here...\" size = \"35\"><br><br>\n <button type=\"submit\" value=\"Submit\">Submit</button>\n</form>\n</body>\n</html>" }, { "code": null, "e": 2366, "s": 2308, "text": "In the above example, we have some fields with a button −" }, { "code": null, "e": 2942, "s": 2366, "text": "<form action=\"\" method=\"get\">\n Id − <input type=\"text\" name=\"id\" placeholder=\"Enter UserId here...\" size = \"25\" required><br>\n Password − <input type=\"password\" name=\"pwd\" placeholder=\"Enter password here...\" required><br>\n DOB − <input type=\"date\" name=\"dob\" placeholder=\"Enter date of birth here...\"><br>\n Telephone − <input type=\"tel\" name=\"tel\" placeholder=\"Enter mobile number here...\" required><br>\n Email − <input type=\"email\" name=\"email\" placeholder=\"Enter email here...\" size = \"35\"><br><br>\n <button type=\"submit\" value=\"Submit\">Submit</button>\n</form>" }, { "code": null, "e": 3073, "s": 2942, "text": "Now, let’s say we want a bigger textbox i.e. with bigger width. For that, we used the size attribute to set the width in numbers −" }, { "code": null, "e": 3159, "s": 3073, "text": "<input type=\"text\" name=\"id\" placeholder=\"Enter UserId here...\" size = \"25\" required>" } ]
Python | How to sort a list of strings
23 May, 2022 Given a list of strings, the task is to sort that list based on given requirement. There are multiple scenarios possible while sorting a list of string, like – Sorting in alphabetical/reverse order. Based on length of string character Sorting the integer values in list of string etc. Let’s discuss various ways to perform this task. Example #1: Using sort() function. Python3 # Python program to sort a list of strings lst = ['gfg', 'is', 'a', 'portal', 'for', 'geeks'] # Using sort() functionlst.sort() print(lst) ['a', 'for', 'geeks', 'gfg', 'is', 'portal'] Example #2: Using sorted() function. Python3 # Python program to sort a list of strings lst = ['gfg', 'is', 'a', 'portal', 'for', 'geeks'] # Using sorted() functionfor ele in sorted(lst): print(ele) a for geeks gfg is portal Example #3: Sort by length of strings Python3 # Python program to sort a list of strings lst = ['Geeksforgeeks', 'is', 'a', 'portal', 'for', 'geeks'] # Using sort() function with key as lenlst.sort(key = len) print(lst) ['a', 'is', 'for', 'geeks', 'portal', 'Geeksforgeeks'] Example #4: Sort string by integer value Python3 # Python program to sort a list of strings lst = ['23', '33', '11', '7', '55'] # Using sort() function with key as intlst.sort(key = int) print(lst) ['7', '11', '23', '33', '55'] Example #5: Sort in descending order Python3 # Python program to sort a list of strings lst = ['gfg', 'is', 'a', 'portal', 'for', 'geeks'] # Using sort() functionlst.sort(reverse = True) print(lst) ['portal', 'is', 'gfg', 'geeks', 'for', 'a'] AshokJaiswal Python list-programs python-list python-string Python Python Programs python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary
[ { "code": null, "e": 28, "s": 0, "text": "\n23 May, 2022" }, { "code": null, "e": 188, "s": 28, "text": "Given a list of strings, the task is to sort that list based on given requirement. There are multiple scenarios possible while sorting a list of string, like –" }, { "code": null, "e": 227, "s": 188, "text": "Sorting in alphabetical/reverse order." }, { "code": null, "e": 263, "s": 227, "text": "Based on length of string character" }, { "code": null, "e": 313, "s": 263, "text": "Sorting the integer values in list of string etc." }, { "code": null, "e": 363, "s": 313, "text": "Let’s discuss various ways to perform this task. " }, { "code": null, "e": 399, "s": 363, "text": "Example #1: Using sort() function. " }, { "code": null, "e": 407, "s": 399, "text": "Python3" }, { "code": "# Python program to sort a list of strings lst = ['gfg', 'is', 'a', 'portal', 'for', 'geeks'] # Using sort() functionlst.sort() print(lst)", "e": 546, "s": 407, "text": null }, { "code": null, "e": 591, "s": 546, "text": "['a', 'for', 'geeks', 'gfg', 'is', 'portal']" }, { "code": null, "e": 631, "s": 591, "text": " Example #2: Using sorted() function. " }, { "code": null, "e": 639, "s": 631, "text": "Python3" }, { "code": "# Python program to sort a list of strings lst = ['gfg', 'is', 'a', 'portal', 'for', 'geeks'] # Using sorted() functionfor ele in sorted(lst): print(ele)", "e": 796, "s": 639, "text": null }, { "code": null, "e": 822, "s": 796, "text": "a\nfor\ngeeks\ngfg\nis\nportal" }, { "code": null, "e": 863, "s": 822, "text": " Example #3: Sort by length of strings " }, { "code": null, "e": 871, "s": 863, "text": "Python3" }, { "code": "# Python program to sort a list of strings lst = ['Geeksforgeeks', 'is', 'a', 'portal', 'for', 'geeks'] # Using sort() function with key as lenlst.sort(key = len) print(lst)", "e": 1045, "s": 871, "text": null }, { "code": null, "e": 1100, "s": 1045, "text": "['a', 'is', 'for', 'geeks', 'portal', 'Geeksforgeeks']" }, { "code": null, "e": 1144, "s": 1100, "text": " Example #4: Sort string by integer value " }, { "code": null, "e": 1152, "s": 1144, "text": "Python3" }, { "code": "# Python program to sort a list of strings lst = ['23', '33', '11', '7', '55'] # Using sort() function with key as intlst.sort(key = int) print(lst)", "e": 1301, "s": 1152, "text": null }, { "code": null, "e": 1331, "s": 1301, "text": "['7', '11', '23', '33', '55']" }, { "code": null, "e": 1369, "s": 1331, "text": "Example #5: Sort in descending order " }, { "code": null, "e": 1377, "s": 1369, "text": "Python3" }, { "code": "# Python program to sort a list of strings lst = ['gfg', 'is', 'a', 'portal', 'for', 'geeks'] # Using sort() functionlst.sort(reverse = True) print(lst)", "e": 1530, "s": 1377, "text": null }, { "code": null, "e": 1575, "s": 1530, "text": "['portal', 'is', 'gfg', 'geeks', 'for', 'a']" }, { "code": null, "e": 1588, "s": 1575, "text": "AshokJaiswal" }, { "code": null, "e": 1609, "s": 1588, "text": "Python list-programs" }, { "code": null, "e": 1621, "s": 1609, "text": "python-list" }, { "code": null, "e": 1635, "s": 1621, "text": "python-string" }, { "code": null, "e": 1642, "s": 1635, "text": "Python" }, { "code": null, "e": 1658, "s": 1642, "text": "Python Programs" }, { "code": null, "e": 1670, "s": 1658, "text": "python-list" }, { "code": null, "e": 1768, "s": 1670, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1810, "s": 1768, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1832, "s": 1810, "text": "Enumerate() in Python" }, { "code": null, "e": 1867, "s": 1832, "text": "Read a file line by line in Python" }, { "code": null, "e": 1893, "s": 1867, "text": "Python String | replace()" }, { "code": null, "e": 1925, "s": 1893, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1968, "s": 1925, "text": "Python program to convert a list to string" }, { "code": null, "e": 1990, "s": 1968, "text": "Defaultdict in Python" }, { "code": null, "e": 2029, "s": 1990, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2067, "s": 2029, "text": "Python | Convert a list to dictionary" } ]
Types of Multiplexing in Data Communications
25 Feb, 2022 What is Multiplexing?Multiplexing is the sharing of a medium or bandwidth. It is the process in which multiple signals coming from multiple sources are combined and transmitted over a single communication/physical line. Types of Multiplexing There are three types of Multiplexing : Frequency Division Multiplexing (FDM)Time-Division Multiplexing (TDM)Wavelength Division Multiplexing (WDM) Frequency Division Multiplexing (FDM) Time-Division Multiplexing (TDM) Wavelength Division Multiplexing (WDM) 1. Frequency Division Multiplexing : Frequency division multiplexing is defined as a type of multiplexing where the bandwidth of a single physical medium is divided into a number of smaller, independent frequency channels. Frequency Division Multiplexing is used in radio and television transmission. In FDM, we can observe a lot of inter-channel cross-talk, due to the fact that in this type of multiplexing the bandwidth is divided into frequency channels. In order to prevent the inter-channel cross talk, unused strips of bandwidth must be placed between each channel. These unused strips between each channel are known as guard bands. 2. Time Division Multiplexing : Time-division multiplexing is defined as a type of multiplexing wherein FDM, instead of sharing a portion of the bandwidth in the form of channels, in TDM, time is shared. Each connection occupies a portion of time in the link. In Time Division Multiplexing, all signals operate with the same frequency (bandwidth) at different times. There are two types of Time Division Multiplexing : Synchronous Time Division MultiplexingStatistical (or Asynchronous) Time Division Multiplexing Synchronous Time Division Multiplexing Statistical (or Asynchronous) Time Division Multiplexing Synchronous TDM : Synchronous TDM is a type of Time Division Multiplexing where the input frame already has a slot in the output frame. Time slots are grouped into frames. One frame consists of one cycle of time slots. Synchronous TDM is not efficient because if the input frame has no data to send, a slot remains empty in the output frame. In synchronous TDM, we need to mention the synchronous bit at the beginning of each frame. Statistical TDM : Statistical TDM is a type of Time Division Multiplexing where the output frame collects data from the input frame till it is full, not leaving an empty slot like in Synchronous TDM. In statistical TDM, we need to include the address of each particular data in the slot that is being sent to the output frame. Statistical TDM is a more efficient type of time-division multiplexing as the channel capacity is fully utilized and improves the bandwidth efficiency. 3. Wavelength Division Multiplexing : Wavelength Division Multiplexing is used on fiber optics to increase the capacity of a single fiber. It is an analog multiplexing technique. Optical signals from the different sources are combined to form a wider band of light with the help of multiplexers. At the receiving end, the demultiplexer separates the signals to transmit them to their respective destinations. prakharsrv17 Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Feb, 2022" }, { "code": null, "e": 249, "s": 28, "text": "What is Multiplexing?Multiplexing is the sharing of a medium or bandwidth. It is the process in which multiple signals coming from multiple sources are combined and transmitted over a single communication/physical line. " }, { "code": null, "e": 311, "s": 249, "text": "Types of Multiplexing There are three types of Multiplexing :" }, { "code": null, "e": 419, "s": 311, "text": "Frequency Division Multiplexing (FDM)Time-Division Multiplexing (TDM)Wavelength Division Multiplexing (WDM)" }, { "code": null, "e": 457, "s": 419, "text": "Frequency Division Multiplexing (FDM)" }, { "code": null, "e": 490, "s": 457, "text": "Time-Division Multiplexing (TDM)" }, { "code": null, "e": 529, "s": 490, "text": "Wavelength Division Multiplexing (WDM)" }, { "code": null, "e": 566, "s": 529, "text": "1. Frequency Division Multiplexing :" }, { "code": null, "e": 753, "s": 566, "text": "Frequency division multiplexing is defined as a type of multiplexing where the bandwidth of a single physical medium is divided into a number of smaller, independent frequency channels. " }, { "code": null, "e": 831, "s": 753, "text": "Frequency Division Multiplexing is used in radio and television transmission." }, { "code": null, "e": 1171, "s": 831, "text": "In FDM, we can observe a lot of inter-channel cross-talk, due to the fact that in this type of multiplexing the bandwidth is divided into frequency channels. In order to prevent the inter-channel cross talk, unused strips of bandwidth must be placed between each channel. These unused strips between each channel are known as guard bands. " }, { "code": null, "e": 1203, "s": 1171, "text": "2. Time Division Multiplexing :" }, { "code": null, "e": 1431, "s": 1203, "text": "Time-division multiplexing is defined as a type of multiplexing wherein FDM, instead of sharing a portion of the bandwidth in the form of channels, in TDM, time is shared. Each connection occupies a portion of time in the link." }, { "code": null, "e": 1538, "s": 1431, "text": "In Time Division Multiplexing, all signals operate with the same frequency (bandwidth) at different times." }, { "code": null, "e": 1590, "s": 1538, "text": "There are two types of Time Division Multiplexing :" }, { "code": null, "e": 1685, "s": 1590, "text": "Synchronous Time Division MultiplexingStatistical (or Asynchronous) Time Division Multiplexing" }, { "code": null, "e": 1724, "s": 1685, "text": "Synchronous Time Division Multiplexing" }, { "code": null, "e": 1781, "s": 1724, "text": "Statistical (or Asynchronous) Time Division Multiplexing" }, { "code": null, "e": 1799, "s": 1781, "text": "Synchronous TDM :" }, { "code": null, "e": 2001, "s": 1799, "text": "Synchronous TDM is a type of Time Division Multiplexing where the input frame already has a slot in the output frame. Time slots are grouped into frames. One frame consists of one cycle of time slots. " }, { "code": null, "e": 2124, "s": 2001, "text": "Synchronous TDM is not efficient because if the input frame has no data to send, a slot remains empty in the output frame." }, { "code": null, "e": 2215, "s": 2124, "text": "In synchronous TDM, we need to mention the synchronous bit at the beginning of each frame." }, { "code": null, "e": 2233, "s": 2215, "text": "Statistical TDM :" }, { "code": null, "e": 2415, "s": 2233, "text": "Statistical TDM is a type of Time Division Multiplexing where the output frame collects data from the input frame till it is full, not leaving an empty slot like in Synchronous TDM." }, { "code": null, "e": 2542, "s": 2415, "text": "In statistical TDM, we need to include the address of each particular data in the slot that is being sent to the output frame." }, { "code": null, "e": 2697, "s": 2544, "text": "Statistical TDM is a more efficient type of time-division multiplexing as the channel capacity is fully utilized and improves the bandwidth efficiency. " }, { "code": null, "e": 2735, "s": 2697, "text": "3. Wavelength Division Multiplexing :" }, { "code": null, "e": 3107, "s": 2735, "text": "Wavelength Division Multiplexing is used on fiber optics to increase the capacity of a single fiber. It is an analog multiplexing technique. Optical signals from the different sources are combined to form a wider band of light with the help of multiplexers. At the receiving end, the demultiplexer separates the signals to transmit them to their respective destinations. " }, { "code": null, "e": 3120, "s": 3107, "text": "prakharsrv17" }, { "code": null, "e": 3138, "s": 3120, "text": "Computer Networks" }, { "code": null, "e": 3156, "s": 3138, "text": "Computer Networks" } ]
Python | Merge list elements
28 Jan, 2019 Sometimes, we require to merge some of the elements as single element in the list. This is usually with the cases with character to string conversion. This type of task is usually required in the development domain to merge the names into one element. Let’s discuss certain ways in which this can be performed. Method #1 : Using join() + List SlicingThe join function can be coupled with list slicing which can perform the task of joining each character in a range picked by the list slicing functionality. # Python3 code to demonstrate # merging list elements# using join() + list slicing # initializing list test_list = ['I', 'L', 'O', 'V', 'E', 'G', 'F', 'G'] # printing original listprint ("The original list is : " + str(test_list)) # using join() + list slicing# merging list elementstest_list[5 : 8] = [''.join(test_list[5 : 8])] # printing result print ("The list after merging elements : " + str(test_list)) The original list is : ['I', 'L', 'O', 'V', 'E', 'G', 'F', 'G'] The list after merging elements : ['I', 'L', 'O', 'V', 'E', 'GFG'] Method #2 : Using reduce() + lambda + list slicingThe task of joining each element in a range is performed by reduce function and lambda. reduce function performs the task for each element in the range which is defined by the lambda function. It works with Python2 only # Python code to demonstrate # merging list elements# using reduce() + lambda + list slicing # initializing list test_list = ['I', 'L', 'O', 'V', 'E', 'G', 'F', 'G'] # printing original listprint ("The original list is : " + str(test_list)) # using reduce() + lambda + list slicing# merging list elementstest_list[5 : 8] = [reduce(lambda i, j: i + j, test_list[5 : 8])] # printing result print ("The list after merging elements : " + str(test_list)) The original list is : ['I', 'L', 'O', 'V', 'E', 'G', 'F', 'G'] The list after merging elements : ['I', 'L', 'O', 'V', 'E', 'GFG'] Python list-programs python-list Python Python Programs python-list 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 ? Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jan, 2019" }, { "code": null, "e": 339, "s": 28, "text": "Sometimes, we require to merge some of the elements as single element in the list. This is usually with the cases with character to string conversion. This type of task is usually required in the development domain to merge the names into one element. Let’s discuss certain ways in which this can be performed." }, { "code": null, "e": 535, "s": 339, "text": "Method #1 : Using join() + List SlicingThe join function can be coupled with list slicing which can perform the task of joining each character in a range picked by the list slicing functionality." }, { "code": "# Python3 code to demonstrate # merging list elements# using join() + list slicing # initializing list test_list = ['I', 'L', 'O', 'V', 'E', 'G', 'F', 'G'] # printing original listprint (\"The original list is : \" + str(test_list)) # using join() + list slicing# merging list elementstest_list[5 : 8] = [''.join(test_list[5 : 8])] # printing result print (\"The list after merging elements : \" + str(test_list))", "e": 951, "s": 535, "text": null }, { "code": null, "e": 1083, "s": 951, "text": "The original list is : ['I', 'L', 'O', 'V', 'E', 'G', 'F', 'G']\nThe list after merging elements : ['I', 'L', 'O', 'V', 'E', 'GFG']\n" }, { "code": null, "e": 1353, "s": 1083, "text": "Method #2 : Using reduce() + lambda + list slicingThe task of joining each element in a range is performed by reduce function and lambda. reduce function performs the task for each element in the range which is defined by the lambda function. It works with Python2 only" }, { "code": "# Python code to demonstrate # merging list elements# using reduce() + lambda + list slicing # initializing list test_list = ['I', 'L', 'O', 'V', 'E', 'G', 'F', 'G'] # printing original listprint (\"The original list is : \" + str(test_list)) # using reduce() + lambda + list slicing# merging list elementstest_list[5 : 8] = [reduce(lambda i, j: i + j, test_list[5 : 8])] # printing result print (\"The list after merging elements : \" + str(test_list))", "e": 1809, "s": 1353, "text": null }, { "code": null, "e": 1941, "s": 1809, "text": "The original list is : ['I', 'L', 'O', 'V', 'E', 'G', 'F', 'G']\nThe list after merging elements : ['I', 'L', 'O', 'V', 'E', 'GFG']\n" }, { "code": null, "e": 1962, "s": 1941, "text": "Python list-programs" }, { "code": null, "e": 1974, "s": 1962, "text": "python-list" }, { "code": null, "e": 1981, "s": 1974, "text": "Python" }, { "code": null, "e": 1997, "s": 1981, "text": "Python Programs" }, { "code": null, "e": 2009, "s": 1997, "text": "python-list" }, { "code": null, "e": 2107, "s": 2009, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2125, "s": 2107, "text": "Python Dictionary" }, { "code": null, "e": 2167, "s": 2125, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2189, "s": 2167, "text": "Enumerate() in Python" }, { "code": null, "e": 2215, "s": 2189, "text": "Python String | replace()" }, { "code": null, "e": 2247, "s": 2215, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2269, "s": 2247, "text": "Defaultdict in Python" }, { "code": null, "e": 2308, "s": 2269, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2346, "s": 2308, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2395, "s": 2346, "text": "Python | Convert string dictionary to dictionary" } ]
HTML - <menu> Tag
The HTML <menu> tag is used for creating a menu list. This tag has been deprecated in HTML and redefined in HTML5. <!DOCTYPE html> <html> <head> <title>HTML menu Tag</title> </head> <body> <menu> <li>ol - ordered list</li> <li>ul - unordered list</li> <li>dir - directory list</li> <li>menu - menu list</li> </menu> </body> </html> This will produce the following result − ol - ordered list ul - unordered list dir - directory list menu - menu list This tag supports all the global attributes described in − HTML Attribute Reference The HTML <menu> tag also supports the following additional attributes − This tag supports all the event attributes described in − HTML Events Reference 19 Lectures 2 hours Anadi Sharma 16 Lectures 1.5 hours Anadi Sharma 18 Lectures 1.5 hours Frahaan Hussain 57 Lectures 5.5 hours DigiFisk (Programming Is Fun) 54 Lectures 6 hours DigiFisk (Programming Is Fun) 45 Lectures 5.5 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 2489, "s": 2374, "text": "The HTML <menu> tag is used for creating a menu list. This tag has been deprecated in HTML and redefined in HTML5." }, { "code": null, "e": 2775, "s": 2489, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML menu Tag</title>\n </head>\n\n <body>\n <menu>\n <li>ol - ordered list</li>\n <li>ul - unordered list</li>\n <li>dir - directory list</li>\n <li>menu - menu list</li>\n </menu>\n </body>\n\n</html>" }, { "code": null, "e": 2816, "s": 2775, "text": "This will produce the following result −" }, { "code": null, "e": 2834, "s": 2816, "text": "ol - ordered list" }, { "code": null, "e": 2854, "s": 2834, "text": "ul - unordered list" }, { "code": null, "e": 2875, "s": 2854, "text": "dir - directory list" }, { "code": null, "e": 2892, "s": 2875, "text": "menu - menu list" }, { "code": null, "e": 2976, "s": 2892, "text": "This tag supports all the global attributes described in − HTML Attribute Reference" }, { "code": null, "e": 3049, "s": 2976, "text": "The HTML <menu> tag also supports the following additional attributes −" }, { "code": null, "e": 3129, "s": 3049, "text": "This tag supports all the event attributes described in − HTML Events Reference" }, { "code": null, "e": 3162, "s": 3129, "text": "\n 19 Lectures \n 2 hours \n" }, { "code": null, "e": 3176, "s": 3162, "text": " Anadi Sharma" }, { "code": null, "e": 3211, "s": 3176, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3225, "s": 3211, "text": " Anadi Sharma" }, { "code": null, "e": 3260, "s": 3225, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3277, "s": 3260, "text": " Frahaan Hussain" }, { "code": null, "e": 3312, "s": 3277, "text": "\n 57 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3343, "s": 3312, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3376, "s": 3343, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 3407, "s": 3376, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3442, "s": 3407, "text": "\n 45 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3473, "s": 3442, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3480, "s": 3473, "text": " Print" }, { "code": null, "e": 3491, "s": 3480, "text": " Add Notes" } ]
How to draw a filled polygon in OpenCV using Java?
The org.opencv.imgproc package of Java OpenCV library contains a class named Imgproc. To draw a filled polygon you need to invoke the fillPoly() method of this class. This method accepts the following parameters − A Mat object representing the image on which the polygon is to be drawn. A Mat object representing the image on which the polygon is to be drawn. A-List object holding the objects of the type MatOfPoint. A-List object holding the objects of the type MatOfPoint. A Scalar object representing the color of the polygon. A Scalar object representing the color of the polygon. An integer representing the line type. An integer representing the line type. import java.util.ArrayList; import java.util.List; import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.core.MatOfPoint; import org.opencv.core.Point; import org.opencv.core.Scalar; import org.opencv.highgui.HighGui; import org.opencv.imgcodecs.Imgcodecs; import org.opencv.imgproc.Imgproc; public class DrawingFilledPolygon { public static void main(String args[]) { //Loading the OpenCV core library System.loadLibrary( Core.NATIVE_LIBRARY_NAME ); //Loading the OpenCV core library System.loadLibrary( Core.NATIVE_LIBRARY_NAME ); //Reading the source image in to a Mat object Mat src = Imgcodecs.imread("D:\\images\\blank.jpg"); //Drawing a polygon List<MatOfPoint>list = new ArrayList<MatOfPoint>(); list.add(new MatOfPoint ( new Point(208, 71), new Point(421, 161), new Point(332, 52), new Point(369, 250), new Point(421, 161), new Point(226, 232), new Point(369, 250), new Point(208, 71), new Point(226, 232), new Point(332, 52))); Scalar color = new Scalar(64, 64, 64); int lineType = Imgproc.LINE_8; Imgproc.fillPoly(src, list, color, lineType); //Saving and displaying the image Imgcodecs.imwrite("arrowed_line.jpg", src); HighGui.imshow("Drawing a polygon", src); HighGui.waitKey(); } } On executing, the above program generates the following window −
[ { "code": null, "e": 1276, "s": 1062, "text": "The org.opencv.imgproc package of Java OpenCV library contains a class named Imgproc. To draw a filled polygon you need to invoke the fillPoly() method of this class. This method accepts the following parameters −" }, { "code": null, "e": 1349, "s": 1276, "text": "A Mat object representing the image on which the polygon is to be drawn." }, { "code": null, "e": 1422, "s": 1349, "text": "A Mat object representing the image on which the polygon is to be drawn." }, { "code": null, "e": 1480, "s": 1422, "text": "A-List object holding the objects of the type MatOfPoint." }, { "code": null, "e": 1538, "s": 1480, "text": "A-List object holding the objects of the type MatOfPoint." }, { "code": null, "e": 1593, "s": 1538, "text": "A Scalar object representing the color of the polygon." }, { "code": null, "e": 1648, "s": 1593, "text": "A Scalar object representing the color of the polygon." }, { "code": null, "e": 1687, "s": 1648, "text": "An integer representing the line type." }, { "code": null, "e": 1726, "s": 1687, "text": "An integer representing the line type." }, { "code": null, "e": 3094, "s": 1726, "text": "import java.util.ArrayList;\nimport java.util.List;\nimport org.opencv.core.Core;\nimport org.opencv.core.Mat;\nimport org.opencv.core.MatOfPoint;\nimport org.opencv.core.Point;\nimport org.opencv.core.Scalar;\nimport org.opencv.highgui.HighGui;\nimport org.opencv.imgcodecs.Imgcodecs;\nimport org.opencv.imgproc.Imgproc;\npublic class DrawingFilledPolygon {\n public static void main(String args[]) {\n //Loading the OpenCV core library\n System.loadLibrary( Core.NATIVE_LIBRARY_NAME );\n //Loading the OpenCV core library\n System.loadLibrary( Core.NATIVE_LIBRARY_NAME );\n //Reading the source image in to a Mat object\n Mat src = Imgcodecs.imread(\"D:\\\\images\\\\blank.jpg\");\n //Drawing a polygon\n List<MatOfPoint>list = new ArrayList<MatOfPoint>();\n list.add(new MatOfPoint (\n new Point(208, 71), new Point(421, 161),\n new Point(332, 52), new Point(369, 250),\n new Point(421, 161), new Point(226, 232),\n new Point(369, 250), new Point(208, 71),\n new Point(226, 232), new Point(332, 52)));\n Scalar color = new Scalar(64, 64, 64);\n int lineType = Imgproc.LINE_8;\n Imgproc.fillPoly(src, list, color, lineType);\n //Saving and displaying the image\n Imgcodecs.imwrite(\"arrowed_line.jpg\", src);\n HighGui.imshow(\"Drawing a polygon\", src);\n HighGui.waitKey();\n }\n}" }, { "code": null, "e": 3159, "s": 3094, "text": "On executing, the above program generates the following window −" } ]
Lexicographical Maximum substring of string - GeeksforGeeks
28 Feb, 2022 Given a string s we have to find the lexicographical maximum substring of a string Examples: Input : s = "ababaa" Output : babaa Explanation : "babaa" is the maximum lexicographic substring formed from this string Input : s = "asdfaa" Output : sdfaa The idea is simple, we traverse through all substrings. For every substring, we compare it with the current result and update the result if needed. Below is the implementation: C++ Java Python3 C# Javascript // CPP program to find the lexicographically// maximum substring.#include <bits/stdc++.h>using namespace std; string LexicographicalMaxString(string str){ // loop to find the max lexicographic // substring in the substring array string mx = ""; for (int i = 0; i < str.length(); ++i) mx = max(mx, str.substr(i)); return mx;} // Driver codeint main(){ string str = "ababaa"; cout << LexicographicalMaxString(str); return 0;} // Java program to find the lexicographically// maximum substring. class GFG { static String LexicographicalMaxString(String str) { // loop to find the max lexicographic // substring in the substring array String mx = ""; for (int i = 0; i < str.length(); ++i) { if (mx.compareTo(str.substring(i)) <= 0) { mx = str.substring(i); } } return mx; } // Driver code public static void main(String[] args) { String str = "ababaa"; System.out.println(LexicographicalMaxString(str)); }}// This code is contributed by 29AjayKumar # Python 3 program to find the# lexicographically maximum substring.def LexicographicalMaxString(str): # loop to find the max lexicographic # substring in the substring array mx = "" for i in range(len(str)): mx = max(mx, str[i:]) return mx # Driver codeif __name__ == '__main__': str = "ababaa" print(LexicographicalMaxString(str)) # This code is contributed by# Sanjit_Prasad // C# program to find the lexicographically// maximum substring. using System;public class GFG { static String LexicographicalMaxString(String str) { // loop to find the max lexicographic // substring in the substring array String mx = ""; for (int i = 0; i < str.Length; ++i) { if (mx.CompareTo(str.Substring(i)) <= 0) { mx = str.Substring(i); } } return mx; } // Driver code public static void Main() { String str = "ababaa"; Console.WriteLine(LexicographicalMaxString(str)); }} // This code is contributed by 29AjayKumar <script> // JavaScript program to find the lexicographically// maximum substring. function LexicographicalMaxString(str) { // loop to find the max lexicographic // substring in the substring array var mx = ""; for (var i = 0; i < str.length; ++i) { if (mx.localeCompare(str.substring(i)) <= 0) { mx = str.substring(i); } } return mx;} // Driver code var str = "ababaa"; document.write(LexicographicalMaxString(str)); // This code is contributed by 29AjayKumar </script> babaa Optimization : We find the largest character and all its indexes. Now we simply traverse through all instances of the largest character to find lexicographically maximum substring. Here we follow the above approach. C++ Java Python3 C# Javascript // C++ program to find the lexicographically// maximum substring.#include <bits/stdc++.h>using namespace std; string LexicographicalMaxString(string str){ char maxchar = 'a'; vector<int> index; // We store all the indexes of maximum // characters we have in the string for (int i = 0; i < str.length(); i++) { if (str[i] >= maxchar) { maxchar = str[i]; index.push_back(i); } } string maxstring = ""; // We form a substring from that maximum // character index till end and check if // its greater that maxstring for (int i = 0; i < index.size(); i++) { if (str.substr(index[i], str.length()) > maxstring) { maxstring = str.substr(index[i], str.length()); } } return maxstring;} // Driver codeint main(){ string str = "acbacbc"; cout << LexicographicalMaxString(str); return 0;} // Java program to find the lexicographically// maximum substring.import java.io.*;import java.util.*;class GFG{ static String LexicographicalMaxString(String str) { char maxchar = 'a'; ArrayList<Integer> index = new ArrayList<Integer>(); // We store all the indexes of maximum // characters we have in the string for (int i = 0; i < str.length(); i++) { if (str.charAt(i) >= maxchar) { maxchar = str.charAt(i); index.add(i); } } String maxstring = ""; // We form a substring from that maximum // character index till end and check if // its greater that maxstring for (int i = 0; i < index.size(); i++) { if (str.substring(index.get(i), str.length()).compareTo( maxstring) > 0) { maxstring = str.substring(index.get(i), str.length()); } } return maxstring; } // Driver code public static void main (String[] args) { String str = "acbacbc"; System.out.println(LexicographicalMaxString(str)); }} // This code is contributed by rag2127. # Python 3 program to find# the lexicographically# maximum substring.def LexicographicalMaxString(st): maxchar = 'a' index = [] # We store all the indexes # of maximum characters we # have in the string for i in range(len(st)): if (st[i] >= maxchar): maxchar = st[i] index.append(i) maxstring = "" # We form a substring from that # maximum character index till # end and check if its greater # that maxstring for i in range(len(index)): if (st[index[i]: len(st)] > maxstring): maxstring = st[index[i]: len(st)] return maxstring # Driver codeif __name__ == "__main__": st = "acbacbc" print(LexicographicalMaxString(st)) # This code is contributed by Chitranayal // C# program to find the lexicographically// maximum substring.using System;using System.Collections.Generic; class GFG{ static string LexicographicalMaxString(string str){ char maxchar = 'a'; List<int> index = new List<int>(); // We store all the indexes of maximum // characters we have in the string for(int i = 0; i < str.Length; i++) { if (str[i] >= maxchar) { maxchar = str[i]; index.Add(i); } } string maxstring = ""; // We form a substring from that maximum // character index till end and check if // its greater that maxstring for(int i = 0; i < index.Count; i++) { if (str.Substring(index[i]).CompareTo(maxstring) > 0) { maxstring = str.Substring(index[i]); } } return maxstring;} // Driver codestatic public void Main(){ string str = "acbacbc"; Console.Write(LexicographicalMaxString(str));}} // This code is contributed by avanitrachhadiya2155 <script>// Javascript program to find the lexicographically// maximum substring. function LexicographicalMaxString(str){ let maxchar = 'a'; let index = []; // We store all the indexes of maximum // characters we have in the string for (let i = 0; i < str.length; i++) { if (str[i] >= maxchar) { maxchar = str[i]; index.push(i); } } let maxstring = ""; // We form a substring from that maximum // character index till end and check if // its greater that maxstring for (let i = 0; i < index.length; i++) { if (str.substring(index[i], str.length) > maxstring) { maxstring = str.substring(index[i], str.length); } } return maxstring;} // Driver codelet str = "acbacbc"; document.write(LexicographicalMaxString(str)); // This code is contributed by ab2127</script> cbc YouTubeGeeksforGeeks500K subscribersLexicographical Maximum substring of string | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:51•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=pMS4P7wxTU8" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> 29AjayKumar Sanjit_Prasad prajmsidc qbert ukasp rag2127 avanitrachhadiya2155 ab2127 varshagumber28 sumitgumber28 cpp-string lexicographic-ordering Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python program to check if a string is palindrome or not Check for Balanced Brackets in an expression (well-formedness) using Stack Different methods to reverse a string in C/C++ KMP Algorithm for Pattern Searching Convert string to char array in C++ Array of Strings in C++ (5 Different Ways to Create) Longest Palindromic Substring | Set 1 Caesar Cipher in Cryptography Reverse words in a given string Check whether two strings are anagram of each other
[ { "code": null, "e": 24829, "s": 24801, "text": "\n28 Feb, 2022" }, { "code": null, "e": 24912, "s": 24829, "text": "Given a string s we have to find the lexicographical maximum substring of a string" }, { "code": null, "e": 24923, "s": 24912, "text": "Examples: " }, { "code": null, "e": 25081, "s": 24923, "text": "Input : s = \"ababaa\"\nOutput : babaa\nExplanation : \"babaa\" is the maximum lexicographic substring formed from this string\n\nInput : s = \"asdfaa\"\nOutput : sdfaa" }, { "code": null, "e": 25229, "s": 25081, "text": "The idea is simple, we traverse through all substrings. For every substring, we compare it with the current result and update the result if needed." }, { "code": null, "e": 25258, "s": 25229, "text": "Below is the implementation:" }, { "code": null, "e": 25262, "s": 25258, "text": "C++" }, { "code": null, "e": 25267, "s": 25262, "text": "Java" }, { "code": null, "e": 25275, "s": 25267, "text": "Python3" }, { "code": null, "e": 25278, "s": 25275, "text": "C#" }, { "code": null, "e": 25289, "s": 25278, "text": "Javascript" }, { "code": "// CPP program to find the lexicographically// maximum substring.#include <bits/stdc++.h>using namespace std; string LexicographicalMaxString(string str){ // loop to find the max lexicographic // substring in the substring array string mx = \"\"; for (int i = 0; i < str.length(); ++i) mx = max(mx, str.substr(i)); return mx;} // Driver codeint main(){ string str = \"ababaa\"; cout << LexicographicalMaxString(str); return 0;}", "e": 25745, "s": 25289, "text": null }, { "code": "// Java program to find the lexicographically// maximum substring. class GFG { static String LexicographicalMaxString(String str) { // loop to find the max lexicographic // substring in the substring array String mx = \"\"; for (int i = 0; i < str.length(); ++i) { if (mx.compareTo(str.substring(i)) <= 0) { mx = str.substring(i); } } return mx; } // Driver code public static void main(String[] args) { String str = \"ababaa\"; System.out.println(LexicographicalMaxString(str)); }}// This code is contributed by 29AjayKumar", "e": 26383, "s": 25745, "text": null }, { "code": "# Python 3 program to find the# lexicographically maximum substring.def LexicographicalMaxString(str): # loop to find the max lexicographic # substring in the substring array mx = \"\" for i in range(len(str)): mx = max(mx, str[i:]) return mx # Driver codeif __name__ == '__main__': str = \"ababaa\" print(LexicographicalMaxString(str)) # This code is contributed by# Sanjit_Prasad", "e": 26799, "s": 26383, "text": null }, { "code": "// C# program to find the lexicographically// maximum substring. using System;public class GFG { static String LexicographicalMaxString(String str) { // loop to find the max lexicographic // substring in the substring array String mx = \"\"; for (int i = 0; i < str.Length; ++i) { if (mx.CompareTo(str.Substring(i)) <= 0) { mx = str.Substring(i); } } return mx; } // Driver code public static void Main() { String str = \"ababaa\"; Console.WriteLine(LexicographicalMaxString(str)); }} // This code is contributed by 29AjayKumar", "e": 27440, "s": 26799, "text": null }, { "code": "<script> // JavaScript program to find the lexicographically// maximum substring. function LexicographicalMaxString(str) { // loop to find the max lexicographic // substring in the substring array var mx = \"\"; for (var i = 0; i < str.length; ++i) { if (mx.localeCompare(str.substring(i)) <= 0) { mx = str.substring(i); } } return mx;} // Driver code var str = \"ababaa\"; document.write(LexicographicalMaxString(str)); // This code is contributed by 29AjayKumar </script>", "e": 27967, "s": 27440, "text": null }, { "code": null, "e": 27973, "s": 27967, "text": "babaa" }, { "code": null, "e": 28156, "s": 27975, "text": "Optimization : We find the largest character and all its indexes. Now we simply traverse through all instances of the largest character to find lexicographically maximum substring." }, { "code": null, "e": 28192, "s": 28156, "text": "Here we follow the above approach. " }, { "code": null, "e": 28196, "s": 28192, "text": "C++" }, { "code": null, "e": 28201, "s": 28196, "text": "Java" }, { "code": null, "e": 28209, "s": 28201, "text": "Python3" }, { "code": null, "e": 28212, "s": 28209, "text": "C#" }, { "code": null, "e": 28223, "s": 28212, "text": "Javascript" }, { "code": "// C++ program to find the lexicographically// maximum substring.#include <bits/stdc++.h>using namespace std; string LexicographicalMaxString(string str){ char maxchar = 'a'; vector<int> index; // We store all the indexes of maximum // characters we have in the string for (int i = 0; i < str.length(); i++) { if (str[i] >= maxchar) { maxchar = str[i]; index.push_back(i); } } string maxstring = \"\"; // We form a substring from that maximum // character index till end and check if // its greater that maxstring for (int i = 0; i < index.size(); i++) { if (str.substr(index[i], str.length()) > maxstring) { maxstring = str.substr(index[i], str.length()); } } return maxstring;} // Driver codeint main(){ string str = \"acbacbc\"; cout << LexicographicalMaxString(str); return 0;}", "e": 29112, "s": 28223, "text": null }, { "code": "// Java program to find the lexicographically// maximum substring.import java.io.*;import java.util.*;class GFG{ static String LexicographicalMaxString(String str) { char maxchar = 'a'; ArrayList<Integer> index = new ArrayList<Integer>(); // We store all the indexes of maximum // characters we have in the string for (int i = 0; i < str.length(); i++) { if (str.charAt(i) >= maxchar) { maxchar = str.charAt(i); index.add(i); } } String maxstring = \"\"; // We form a substring from that maximum // character index till end and check if // its greater that maxstring for (int i = 0; i < index.size(); i++) { if (str.substring(index.get(i), str.length()).compareTo( maxstring) > 0) { maxstring = str.substring(index.get(i), str.length()); } } return maxstring; } // Driver code public static void main (String[] args) { String str = \"acbacbc\"; System.out.println(LexicographicalMaxString(str)); }} // This code is contributed by rag2127.", "e": 30223, "s": 29112, "text": null }, { "code": "# Python 3 program to find# the lexicographically# maximum substring.def LexicographicalMaxString(st): maxchar = 'a' index = [] # We store all the indexes # of maximum characters we # have in the string for i in range(len(st)): if (st[i] >= maxchar): maxchar = st[i] index.append(i) maxstring = \"\" # We form a substring from that # maximum character index till # end and check if its greater # that maxstring for i in range(len(index)): if (st[index[i]: len(st)] > maxstring): maxstring = st[index[i]: len(st)] return maxstring # Driver codeif __name__ == \"__main__\": st = \"acbacbc\" print(LexicographicalMaxString(st)) # This code is contributed by Chitranayal", "e": 31015, "s": 30223, "text": null }, { "code": "// C# program to find the lexicographically// maximum substring.using System;using System.Collections.Generic; class GFG{ static string LexicographicalMaxString(string str){ char maxchar = 'a'; List<int> index = new List<int>(); // We store all the indexes of maximum // characters we have in the string for(int i = 0; i < str.Length; i++) { if (str[i] >= maxchar) { maxchar = str[i]; index.Add(i); } } string maxstring = \"\"; // We form a substring from that maximum // character index till end and check if // its greater that maxstring for(int i = 0; i < index.Count; i++) { if (str.Substring(index[i]).CompareTo(maxstring) > 0) { maxstring = str.Substring(index[i]); } } return maxstring;} // Driver codestatic public void Main(){ string str = \"acbacbc\"; Console.Write(LexicographicalMaxString(str));}} // This code is contributed by avanitrachhadiya2155", "e": 32018, "s": 31015, "text": null }, { "code": "<script>// Javascript program to find the lexicographically// maximum substring. function LexicographicalMaxString(str){ let maxchar = 'a'; let index = []; // We store all the indexes of maximum // characters we have in the string for (let i = 0; i < str.length; i++) { if (str[i] >= maxchar) { maxchar = str[i]; index.push(i); } } let maxstring = \"\"; // We form a substring from that maximum // character index till end and check if // its greater that maxstring for (let i = 0; i < index.length; i++) { if (str.substring(index[i], str.length) > maxstring) { maxstring = str.substring(index[i], str.length); } } return maxstring;} // Driver codelet str = \"acbacbc\"; document.write(LexicographicalMaxString(str)); // This code is contributed by ab2127</script>", "e": 32938, "s": 32018, "text": null }, { "code": null, "e": 32942, "s": 32938, "text": "cbc" }, { "code": null, "e": 33786, "s": 32944, "text": "YouTubeGeeksforGeeks500K subscribersLexicographical Maximum substring of string | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:51•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=pMS4P7wxTU8\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 33798, "s": 33786, "text": "29AjayKumar" }, { "code": null, "e": 33812, "s": 33798, "text": "Sanjit_Prasad" }, { "code": null, "e": 33822, "s": 33812, "text": "prajmsidc" }, { "code": null, "e": 33828, "s": 33822, "text": "qbert" }, { "code": null, "e": 33834, "s": 33828, "text": "ukasp" }, { "code": null, "e": 33842, "s": 33834, "text": "rag2127" }, { "code": null, "e": 33863, "s": 33842, "text": "avanitrachhadiya2155" }, { "code": null, "e": 33870, "s": 33863, "text": "ab2127" }, { "code": null, "e": 33885, "s": 33870, "text": "varshagumber28" }, { "code": null, "e": 33899, "s": 33885, "text": "sumitgumber28" }, { "code": null, "e": 33910, "s": 33899, "text": "cpp-string" }, { "code": null, "e": 33933, "s": 33910, "text": "lexicographic-ordering" }, { "code": null, "e": 33941, "s": 33933, "text": "Strings" }, { "code": null, "e": 33949, "s": 33941, "text": "Strings" }, { "code": null, "e": 34047, "s": 33949, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34056, "s": 34047, "text": "Comments" }, { "code": null, "e": 34069, "s": 34056, "text": "Old Comments" }, { "code": null, "e": 34126, "s": 34069, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 34201, "s": 34126, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" }, { "code": null, "e": 34248, "s": 34201, "text": "Different methods to reverse a string in C/C++" }, { "code": null, "e": 34284, "s": 34248, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 34320, "s": 34284, "text": "Convert string to char array in C++" }, { "code": null, "e": 34373, "s": 34320, "text": "Array of Strings in C++ (5 Different Ways to Create)" }, { "code": null, "e": 34411, "s": 34373, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 34441, "s": 34411, "text": "Caesar Cipher in Cryptography" }, { "code": null, "e": 34473, "s": 34441, "text": "Reverse words in a given string" } ]
VBA - Quick Guide
VBA stands for Visual Basic for Applications an event-driven programming language from Microsoft that is now predominantly used with Microsoft office applications such as MSExcel, MS-Word, and MS-Access. It helps techies to build customized applications and solutions to enhance the capabilities of those applications. The advantage of this facility is that you NEED NOT have visual basic installed on our PC, however, installing Office will implicitly help in achieving the purpose. You can use VBA in all office versions, right from MS-Office 97 to MS-Office 2013 and also with any of the latest versions available. Among VBA, Excel VBA is the most popular. The advantage of using VBA is that you can build very powerful tools in MS Excel using linear programming. You might wonder why to use VBA in Excel as MS-Excel itself provides loads of inbuilt functions. MS-Excel provides only basic inbuilt functions which might not be sufficient to perform complex calculations. Under such circumstances, VBA becomes the most obvious solution. For example, it is very hard to calculate the monthly repayment of a loan using Excel's built-in formulas. Rather, it is easy to program a VBA for such a calculation. In Excel window, press "ALT+F11". A VBA window opens up as shown in the following screenshot. In this chapter, you will learn how to write a simple macro in a step by step manner. Step 1 − First, enable 'Developer' menu in Excel 20XX. To do the same, click File → Options. Step 2 − Click ‘Customize the Ribbon’ tab and check 'Developer'. Click 'OK'. Step 3 − The 'Developer' ribbon appears in the menu bar. Step 4 − Click the 'Visual Basic' button to open the VBA Editor. Step 5 − Start scripting by adding a button. Click Insert → Select the button. Step 6 − Perform a right-click and choose 'properties'. Step 7 − Edit the name and caption as shown in the following screenshot. Step 8 − Now double-click the button and the sub-procedure outline will be displayed as shown in the following screenshot. Step 9 − Start coding by simply adding a message. Private Sub say_helloworld_Click() MsgBox "Hi" End Sub Step 10 − Click the button to execute the sub-procedure. The output of the sub-procedure is shown in the following screenshot. Make sure that you do have design mode turned on. Simply click it to turn it on if it is not on. Note − In further chapters, we will demonstrate using a simple button, as explained from step#1 to 10. Hence , it is important to understand this chapter thoroughly. In this chapter, you will acquaint yourself with the commonly used excel VBA terminologies. These terminologies will be used in further modules, hence understanding each one of these is important. Modules is the area where the code is written. This is a new Workbook, hence there aren't any Modules. To insert a Module, navigate to Insert → Module. Once a module is inserted 'module1' is created. Within the modules, we can write VBA code and the code is written within a Procedure. A Procedure/Sub Procedure is a series of VBA statements instructing what to do. Procedures are a group of statements executed as a whole, which instructs Excel how to perform a specific task. The task performed can be a very simple or a very complicated task. However, it is a good practice to break down complicated procedures into smaller ones. The two main types of Procedures are Sub and Function. A function is a group of reusable code, which can be called anywhere in your program. This eliminates the need of writing the same code over and over again. This helps the programmers to divide a big program into a number of small and manageable functions. Apart from inbuilt Functions, VBA allows to write user-defined functions as well and statements are written between Function and End Function. Sub-procedures work similar to functions. While sub procedures DO NOT Return a value, functions may or may not return a value. Sub procedures CAN be called without call keyword. Sub procedures are always enclosed within Sub and End Sub statements. Comments are used to document the program logic and the user information with which other programmers can seamlessly work on the same code in future. It includes information such as developed by, modified by, and can also include incorporated logic. Comments are ignored by the interpreter while execution. Comments in VBA are denoted by two methods. Any statement that starts with a Single Quote (') is treated as comment. Following is an example. Any statement that starts with a Single Quote (') is treated as comment. Following is an example. ' This Script is invoked after successful login ' Written by : TutorialsPoint ' Return Value : True / False Any statement that starts with the keyword "REM". Following is an example. Any statement that starts with the keyword "REM". Following is an example. REM This Script is written to Validate the Entered Input REM Modified by : Tutorials point/user2 The MsgBox function displays a message box and waits for the user to click a button and then an action is performed based on the button clicked by the user. MsgBox(prompt[,buttons][,title][,helpfile,context]) Prompt − A Required Parameter. A String that is displayed as a message in the dialog box. The maximum length of prompt is approximately 1024 characters. If the message extends to more than a line, then the lines can be separated using a carriage return character (Chr(13)) or a linefeed character (Chr(10)) between each line. Prompt − A Required Parameter. A String that is displayed as a message in the dialog box. The maximum length of prompt is approximately 1024 characters. If the message extends to more than a line, then the lines can be separated using a carriage return character (Chr(13)) or a linefeed character (Chr(10)) between each line. Buttons − An Optional Parameter. A Numeric expression that specifies the type of buttons to display, the icon style to use, the identity of the default button, and the modality of the message box. If left blank, the default value for buttons is 0. Buttons − An Optional Parameter. A Numeric expression that specifies the type of buttons to display, the icon style to use, the identity of the default button, and the modality of the message box. If left blank, the default value for buttons is 0. Title − An Optional Parameter. A String expression displayed in the title bar of the dialog box. If the title is left blank, the application name is placed in the title bar. Title − An Optional Parameter. A String expression displayed in the title bar of the dialog box. If the title is left blank, the application name is placed in the title bar. Helpfile − An Optional Parameter. A String expression that identifies the Help file to use for providing context-sensitive help for the dialog box. Helpfile − An Optional Parameter. A String expression that identifies the Help file to use for providing context-sensitive help for the dialog box. Context − An Optional Parameter. A Numeric expression that identifies the Help context number assigned by the Help author to the appropriate Help topic. If context is provided, helpfile must also be provided. Context − An Optional Parameter. A Numeric expression that identifies the Help context number assigned by the Help author to the appropriate Help topic. If context is provided, helpfile must also be provided. The Buttons parameter can take any of the following values − 0 vbOKOnly - Displays OK button only. 0 vbOKOnly - Displays OK button only. 1 vbOKCancel - Displays OK and Cancel buttons. 1 vbOKCancel - Displays OK and Cancel buttons. 2 vbAbortRetryIgnore - Displays Abort, Retry, and Ignore buttons. 2 vbAbortRetryIgnore - Displays Abort, Retry, and Ignore buttons. 3 vbYesNoCancel - Displays Yes, No, and Cancel buttons. 3 vbYesNoCancel - Displays Yes, No, and Cancel buttons. 4 vbYesNo - Displays Yes and No buttons. 4 vbYesNo - Displays Yes and No buttons. 5 vbRetryCancel - Displays Retry and Cancel buttons. 5 vbRetryCancel - Displays Retry and Cancel buttons. 16 vbCritical - Displays Critical Message icon. 16 vbCritical - Displays Critical Message icon. 32 vbQuestion - Displays Warning Query icon. 32 vbQuestion - Displays Warning Query icon. 48 vbExclamation - Displays Warning Message icon. 48 vbExclamation - Displays Warning Message icon. 64 vbInformation - Displays Information Message icon. 64 vbInformation - Displays Information Message icon. 0 vbDefaultButton1 - First button is default. 0 vbDefaultButton1 - First button is default. 256 vbDefaultButton2 - Second button is default. 256 vbDefaultButton2 - Second button is default. 512 vbDefaultButton3 - Third button is default. 512 vbDefaultButton3 - Third button is default. 768 vbDefaultButton4 - Fourth button is default. 768 vbDefaultButton4 - Fourth button is default. 0 vbApplicationModal Application modal - The current application will not work until the user responds to the message box. 0 vbApplicationModal Application modal - The current application will not work until the user responds to the message box. 4096 vbSystemModal System modal - All applications will not work until the user responds to the message box. 4096 vbSystemModal System modal - All applications will not work until the user responds to the message box. The above values are logically divided into four groups: The first group (0 to 5) indicates the buttons to be displayed in the message box. The second group (16, 32, 48, 64) describes the style of the icon to be displayed, the third group (0, 256, 512, 768) indicates which button must be the default, and the fourth group (0, 4096) determines the modality of the message box. The MsgBox function can return one of the following values which can be used to identify the button the user has clicked in the message box. 1 - vbOK - OK was clicked 2 - vbCancel - Cancel was clicked 3 - vbAbort - Abort was clicked 4 - vbRetry - Retry was clicked 5 - vbIgnore - Ignore was clicked 6 - vbYes - Yes was clicked 7 - vbNo - No was clicked Function MessageBox_Demo() 'Message Box with just prompt message MsgBox("Welcome") 'Message Box with title, yes no and cancel Butttons int a = MsgBox("Do you like blue color?",3,"Choose options") ' Assume that you press No Button msgbox ("The Value of a is " & a) End Function Step 1 − The above Function can be executed either by clicking the "Run" button on VBA Window or by calling the function from Excel Worksheet as shown in the following screenshot. Step 2 − A Simple Message box is displayed with a message "Welcome" and an "OK" Button Step 3 − After Clicking OK, yet another dialog box is displayed with a message along with "yes, no, and cancel" buttons. Step 4 − After clicking the ‘No’ button, the value of that button (7) is stored as an integer and displayed as a message box to the user as shown in the following screenshot. Using this value, it can be understood which button the user has clicked. The InputBox function prompts the users to enter values. After entering the values, if the user clicks the OK button or presses ENTER on the keyboard, the InputBox function will return the text in the text box. If the user clicks the Cancel button, the function will return an empty string (""). InputBox(prompt[,title][,default][,xpos][,ypos][,helpfile,context]) Prompt − A required parameter. A String that is displayed as a message in the dialog box. The maximum length of prompt is approximately 1024 characters. If the message extends to more than a line, then the lines can be separated using a carriage return character (Chr(13)) or a linefeed character (Chr(10)) between each line. Prompt − A required parameter. A String that is displayed as a message in the dialog box. The maximum length of prompt is approximately 1024 characters. If the message extends to more than a line, then the lines can be separated using a carriage return character (Chr(13)) or a linefeed character (Chr(10)) between each line. Title − An optional parameter. A String expression displayed in the title bar of the dialog box. If the title is left blank, the application name is placed in the title bar. Title − An optional parameter. A String expression displayed in the title bar of the dialog box. If the title is left blank, the application name is placed in the title bar. Default − An optional parameter. A default text in the text box that the user would like to be displayed. Default − An optional parameter. A default text in the text box that the user would like to be displayed. XPos − An optional parameter. The position of X axis represents the prompt distance from the left side of the screen horizontally. If left blank, the input box is horizontally centered. XPos − An optional parameter. The position of X axis represents the prompt distance from the left side of the screen horizontally. If left blank, the input box is horizontally centered. YPos − An optional parameter. The position of Y axis represents the prompt distance from the left side of the screen vertically. If left blank, the input box is vertically centered. YPos − An optional parameter. The position of Y axis represents the prompt distance from the left side of the screen vertically. If left blank, the input box is vertically centered. Helpfile − An optional parameter. A String expression that identifies the helpfile to be used to provide context-sensitive Help for the dialog box. Helpfile − An optional parameter. A String expression that identifies the helpfile to be used to provide context-sensitive Help for the dialog box. context − An optional parameter. A Numeric expression that identifies the Help context number assigned by the Help author to the appropriate Help topic. If context is provided, helpfile must also be provided. context − An optional parameter. A Numeric expression that identifies the Help context number assigned by the Help author to the appropriate Help topic. If context is provided, helpfile must also be provided. Let us calculate the area of a rectangle by getting values from the user at run time with the help of two input boxes (one for length and one for width). Function findArea() Dim Length As Double Dim Width As Double Length = InputBox("Enter Length ", "Enter a Number") Width = InputBox("Enter Width", "Enter a Number") findArea = Length * Width End Function Step 1 − To execute the same, call using the function name and press Enter as shown in the following screenshot. Step 2 − Upon execution, the First input box (length) is displayed. Enter a value into the input box. Step 3 − After entering the first value, the second input box (width) is displayed. Step 4 − Upon entering the second number, click the OK button. The area is displayed as shown in the following screenshot. Variable is a named memory location used to hold a value that can be changed during the script execution. Following are the basic rules for naming a variable. You must use a letter as the first character. You must use a letter as the first character. You can't use a space, period (.), exclamation mark (!), or the characters @, &, $, # in the name. You can't use a space, period (.), exclamation mark (!), or the characters @, &, $, # in the name. Name can't exceed 255 characters in length. Name can't exceed 255 characters in length. You cannot use Visual Basic reserved keywords as variable name. You cannot use Visual Basic reserved keywords as variable name. Syntax In VBA, you need to declare the variables before using them. Dim <<variable_name>> As <<variable_type>> There are many VBA data types, which can be divided into two main categories, namely numeric and non-numeric data types. Following table displays the numeric data types and the allowed range of values. -3.402823E+38 to -1.401298E-45 for negative values 1.401298E-45 to 3.402823E+38 for positive values. -1.79769313486232e+308 to -4.94065645841247E-324 for negative values 4.94065645841247E-324 to 1.79769313486232e+308 for positive values. +/- 79,228,162,514,264,337,593,543,950,335 if no decimal is use +/- 7.9228162514264337593543950335 (28 decimal places). Following table displays the non-numeric data types and the allowed range of values. Example Let us create a button and name it as 'Variables_demo' to demonstrate the use of variables. Private Sub say_helloworld_Click() Dim password As String password = "Admin#1" Dim num As Integer num = 1234 Dim BirthDay As Date BirthDay = DateValue("30 / 10 / 2020") MsgBox "Passowrd is " & password & Chr(10) & "Value of num is " & num & Chr(10) & "Value of Birthday is " & BirthDay End Sub Output Upon executing the script, the output will be as shown in the following screenshot. Constant is a named memory location used to hold a value that CANNOT be changed during the script execution. If a user tries to change a Constant value, the script execution ends up with an error. Constants are declared the same way the variables are declared. Following are the rules for naming a constant. You must use a letter as the first character. You must use a letter as the first character. You can't use a space, period (.), exclamation mark (!), or the characters @, &, $, # in the name. You can't use a space, period (.), exclamation mark (!), or the characters @, &, $, # in the name. Name can't exceed 255 characters in length. Name can't exceed 255 characters in length. You cannot use Visual Basic reserved keywords as variable name. You cannot use Visual Basic reserved keywords as variable name. In VBA, we need to assign a value to the declared Constants. An error is thrown, if we try to change the value of the constant. Const <<constant_name>> As <<constant_type>> = <<constant_value>> Let us create a button "Constant_demo" to demonstrate how to work with constants. Private Sub Constant_demo_Click() Const MyInteger As Integer = 42 Const myDate As Date = #2/2/2020# Const myDay As String = "Sunday" MsgBox "Integer is " & MyInteger & Chr(10) & "myDate is " & myDate & Chr(10) & "myDay is " & myDay End Sub Upon executing the script, the output will be displayed as shown in the following screenshot. An Operator can be defined using a simple expression - 4 + 5 is equal to 9. Here, 4 and 5 are called operands and + is called operator. VBA supports following types of operators − Arithmetic Operators Comparison Operators Logical (or Relational) Operators Concatenation Operators Following arithmetic operators are supported by VBA. Assume variable A holds 5 and variable B holds 10, then − Show Examples There are following comparison operators supported by VBA. Assume variable A holds 10 and variable B holds 20, then − Show Examples Following logical operators are supported by VBA. Assume variable A holds 10 and variable B holds 0, then − Show Examples Following Concatenation operators are supported by VBA. Assume variable A holds 5 and variable B holds 10 then − Show Examples Assume variable A = "Microsoft" and variable B = "VBScript", then − Note − Concatenation Operators can be used for both numbers and strings. The output depends on the context, if the variables hold numeric value or string value. Decision making allows the programmers to control the execution flow of a script or one of its sections. The execution is governed by one or more conditional statements. Following is the general form of a typical decision making structure found in most of the programming languages. VBA provides the following types of decision making statements. Click the following links to check their details. An if statement consists of a Boolean expression followed by one or more statements. An if else statement consists of a Boolean expression followed by one or more statements. If the condition is True, the statements under If statements are executed. If the condition is false, the Else part of the script is executed. An if statement followed by one or more ElseIf statements, that consists of Boolean expressions and then followed by an optional else statement, which executes when all the condition become false. An if or elseif statement inside another if or elseif statement(s). A switch statement allows a variable to be tested for equality against a list of values. There may be a situation when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. Programming languages provide various control structures that allow for more complicated execution paths. A loop statement allows us to execute a statement or group of statements multiple times. Following is the general form of a loop statement in VBA. VBA provides the following types of loops to handle looping requirements. Click the following links to check their detail. Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable. This is executed if there is at least one element in the group and reiterated for each element in a group. This tests the condition before executing the loop body. The do..While statements will be executed as long as the condition is True.(i.e.,) The Loop should be repeated till the condition is False. The do..Until statements will be executed as long as the condition is False.(i.e.,) The Loop should be repeated till the condition is True. Loop control statements change execution from its normal sequence. When execution leaves a scope, all the remaining statements in the loop are NOT executed. VBA supports the following control statements. Click the following links to check their detail. Terminates the For loop statement and transfers the execution to the statement immediately following the loop Terminates the Do While statement and transfers the execution to the statement immediately following the loop Strings are a sequence of characters, which can consist of either alphabets, numbers, special characters, or all of them. A variable is said to be a string if it is enclosed within double quotes " ". variablename = "string" str1 = "string" ' Only Alphabets str2 = "132.45" ' Only Numbers str3 = "!@#$;*" ' Only Special Characters Str4 = "Asc23@#" ' Has all the above There are predefined VBA String functions, which help the developers to work with the strings very effectively. Following are String methods that are supported in VBA. Please click on each one of the methods to know in detail. Returns the first occurrence of the specified substring. Search happens from the left to the right. Returns the first occurrence of the specified substring. Search happens from the right to the left. Returns the lower case of the specified string. Returns the upper case of the specified string. Returns a specific number of characters from the left side of the string. Returns a specific number of characters from the right side of the string. Returns a specific number of characters from a string based on the specified parameters. Returns a string after removing the spaces on the left side of the specified string. Returns a string after removing the spaces on the right side of the specified string. Returns a string value after removing both the leading and the trailing blank spaces. Returns the length of the given string. Returns a string after replacing a string with another string. Fills a string with the specified number of spaces. Returns an integer value after comparing the two specified strings. Returns a string with a specified character for specified number of times. Returns a string after reversing the sequence of the characters of the given string. VBScript Date and Time Functions help the developers to convert date and time from one format to another or to express the date or time value in the format that suits a specific condition. A Function, which returns the current system date. A Function, which converts a given input to date. A Function, which returns a date to which a specified time interval has been added. A Function, which returns the difference between two time period. A Function, which returns a specified part of the given input date value. A Function, which returns a valid date for the given year, month, and date. A Function, which formats the date based on the supplied parameters. A Function, which returns a Boolean Value whether or not the supplied parameter is a date. A Function, which returns an integer between 1 and 31 that represents the day of the specified date. A Function, which returns an integer between 1 and 12 that represents the month of the specified date. A Function, which returns an integer that represents the year of the specified date. A Function, which returns the name of the particular month for the specified date. A Function, which returns an integer(1 to 7) that represents the day of the week for the specified day. A Function, which returns the weekday name for the specified day. A Function, which returns the current system date and time. A Function, which returns an integer between 0 and 23 that represents the hour part of the given time. A Function, which returns an integer between 0 and 59 that represents the minutes part of the given time. A Function, which returns an integer between 0 and 59 that represents the seconds part of the given time. A Function, which returns the current system time. A Function, which returns the number of seconds and milliseconds since 12:00 AM. A Function, which returns the time for the specific input of hour, minute and second. A Function, which converts the input string to a time format. We know very well that a variable is a container to store a value. Sometimes, developers are in a position to hold more than one value in a single variable at a time. When a series of values are stored in a single variable, then it is known as an array variable. Arrays are declared the same way a variable has been declared except that the declaration of an array variable uses parenthesis. In the following example, the size of the array is mentioned in the brackets. 'Method 1 : Using Dim Dim arr1() 'Without Size 'Method 2 : Mentioning the Size Dim arr2(5) 'Declared with size of 5 'Method 3 : using 'Array' Parameter Dim arr3 arr3 = Array("apple","Orange","Grapes") Although, the array size is indicated as 5, it can hold 6 values as array index starts from ZERO. Although, the array size is indicated as 5, it can hold 6 values as array index starts from ZERO. Array Index cannot be negative. Array Index cannot be negative. VBScript Arrays can store any type of variable in an array. Hence, an array can store an integer, string, or characters in a single array variable. VBScript Arrays can store any type of variable in an array. Hence, an array can store an integer, string, or characters in a single array variable. The values are assigned to the array by specifying an array index value against each one of the values to be assigned. It can be a string. Add a button and add the following function. Private Sub Constant_demo_Click() Dim arr(5) arr(0) = "1" 'Number as String arr(1) = "VBScript" 'String arr(2) = 100 'Number arr(3) = 2.45 'Decimal Number arr(4) = #10/07/2013# 'Date arr(5) = #12.45 PM# 'Time msgbox("Value stored in Array index 0 : " & arr(0)) msgbox("Value stored in Array index 1 : " & arr(1)) msgbox("Value stored in Array index 2 : " & arr(2)) msgbox("Value stored in Array index 3 : " & arr(3)) msgbox("Value stored in Array index 4 : " & arr(4)) msgbox("Value stored in Array index 5 : " & arr(5)) End Sub When you execute the above function, it produces the following output. Value stored in Array index 0 : 1 Value stored in Array index 1 : VBScript Value stored in Array index 2 : 100 Value stored in Array index 3 : 2.45 Value stored in Array index 4 : 7/10/2013 Value stored in Array index 5 : 12:45:00 PM Arrays are not just limited to a single dimension, however, they can have a maximum of 60 dimensions. Two-dimensional arrays are the most commonly used ones. In the following example, a multi-dimensional array is declared with 3 rows and 4 columns. Private Sub Constant_demo_Click() Dim arr(2,3) as Variant ' Which has 3 rows and 4 columns arr(0,0) = "Apple" arr(0,1) = "Orange" arr(0,2) = "Grapes" arr(0,3) = "pineapple" arr(1,0) = "cucumber" arr(1,1) = "beans" arr(1,2) = "carrot" arr(1,3) = "tomato" arr(2,0) = "potato" arr(2,1) = "sandwitch" arr(2,2) = "coffee" arr(2,3) = "nuts" msgbox("Value in Array index 0,1 : " & arr(0,1)) msgbox("Value in Array index 2,2 : " & arr(2,2)) End Sub When you execute the above function, it produces the following output. Value stored in Array index : 0 , 1 : Orange Value stored in Array index : 2 , 2 : coffee ReDim statement is used to declare dynamic-array variables and allocate or reallocate storage space. ReDim [Preserve] varname(subscripts) [, varname(subscripts)] Preserve − An optional parameter used to preserve the data in an existing array when you change the size of the last dimension. Preserve − An optional parameter used to preserve the data in an existing array when you change the size of the last dimension. Varname − A required parameter, which denotes the name of the variable, which should follow the standard variable naming conventions. Varname − A required parameter, which denotes the name of the variable, which should follow the standard variable naming conventions. Subscripts − A required parameter, which indicates the size of the array. Subscripts − A required parameter, which indicates the size of the array. In the following example, an array has been redefined and then the values preserved when the existing size of the array is changed. Note − Upon resizing an array smaller than it was originally, the data in the eliminated elements will be lost. Private Sub Constant_demo_Click() Dim a() as variant i = 0 redim a(5) a(0) = "XYZ" a(1) = 41.25 a(2) = 22 REDIM PRESERVE a(7) For i = 3 to 7 a(i) = i Next 'to Fetch the output For i = 0 to ubound(a) Msgbox a(i) Next End Sub When you execute the above function, it produces the following output. XYZ 41.25 22 3 4 5 6 7 There are various inbuilt functions within VBScript which help the developers to handle arrays effectively. All the methods that are used in conjunction with arrays are listed below. Please click on the method name to know about it in detail. A Function, which returns an integer that corresponds to the smallest subscript of the given arrays. A Function, which returns an integer that corresponds to the largest subscript of the given arrays. A Function, which returns an array that contains a specified number of values. Split based on a delimiter. A Function, which returns a string that contains a specified number of substrings in an array. This is an exact opposite function of Split Method. A Function, which returns a zero based array that contains a subset of a string array based on a specific filter criteria. A Function, which returns a boolean value that indicates whether or not the input variable is an array. A Function, which recovers the allocated memory for the array variables. A function is a group of reusable code which can be called anywhere in your program. This eliminates the need of writing the same code over and over again. This enables the programmers to divide a big program into a number of small and manageable functions. Apart from inbuilt functions, VBA allows to write user-defined functions as well. In this chapter, you will learn how to write your own functions in VBA. A VBA function can have an optional return statement. This is required if you want to return a value from a function. For example, you can pass two numbers in a function and then you can expect from the function to return their multiplication in your calling program. Note − A function can return multiple values separated by a comma as an array assigned to the function name itself. Before we use a function, we need to define that particular function. The most common way to define a function in VBA is by using the Function keyword, followed by a unique function name and it may or may not carry a list of parameters and a statement with End Function keyword, which indicates the end of the function. Following is the basic syntax. Add a button and add the following function. Function Functionname(parameter-list) statement 1 statement 2 statement 3 ....... statement n End Function Add the following function which returns the area. Note that a value/values can be returned with the function name itself. Function findArea(Length As Double, Optional Width As Variant) If IsMissing(Width) Then findArea = Length * Length Else findArea = Length * Width End If End Function To invoke a function, call the function using the function name as shown in the following screenshot. The output of the area as shown below will be displayed to the user. Sub Procedures are similar to functions, however there are a few differences. Sub procedures DO NOT Return a value while functions may or may not return a value. Sub procedures DO NOT Return a value while functions may or may not return a value. Sub procedures CAN be called without a call keyword. Sub procedures CAN be called without a call keyword. Sub procedures are always enclosed within Sub and End Sub statements. Sub procedures are always enclosed within Sub and End Sub statements. Sub Area(x As Double, y As Double) MsgBox x * y End Sub To invoke a Procedure somewhere in the script, you can make a call from a function. We will not be able to use the same way as that of a function as sub procedure WILL NOT return a value. Function findArea(Length As Double, Width As Variant) area Length, Width ' To Calculate Area 'area' sub proc is called End Function Now you will be able to call the function only but not the sub procedure as shown in the following screenshot. The area is calculated and shown only in the Message box. The result cell displays ZERO as the area value is NOT returned from the function. In short, you cannot make a direct call to a sub procedure from the excel worksheet. VBA, an event-driven programming can be triggered when you change a cell or range of cell values manually. Change event may make things easier, but you can very quickly end a page full of formatting. There are two kinds of events. Worksheet Events Workbook Events Worksheet Events are triggered when there is a change in the worksheet. It is created by performing a right-click on the sheet tab and choosing 'view code', and later pasting the code. The user can select each one of those worksheets and choose "WorkSheet" from the drop down to get the list of all supported Worksheet events. Following are the supported worksheet events that can be added by the user. Private Sub Worksheet_Activate() Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean) Private Sub Worksheet_BeforeRightClick(ByVal Target As Range, Cancel As Boolean) Private Sub Worksheet_Calculate() Private Sub Worksheet_Change(ByVal Target As Range) Private Sub Worksheet_Deactivate() Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink) Private Sub Worksheet_SelectionChange(ByVal Target As Range) Let us say, we just need to display a message before double click. Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean) MsgBox "Before Double Click" End Sub Upon double-clicking on any cell, the message box is displayed to the user as shown in the following screenshot. Workbook events are triggered when there is a change in the workbook on the whole. We can add the code for workbook events by selecting the 'ThisWorkbook' and selecting 'workbook' from the dropdown as shown in the following screenshot. Immediately Workbook_open sub procedure is displayed to the user as seen in the following screenshot. Following are the supported Workbook events that can be added by the user. Private Sub Workbook_AddinUninstall() Private Sub Workbook_BeforeClose(Cancel As Boolean) Private Sub Workbook_BeforePrint(Cancel As Boolean) Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean) Private Sub Workbook_Deactivate() Private Sub Workbook_NewSheet(ByVal Sh As Object) Private Sub Workbook_Open() Private Sub Workbook_SheetActivate(ByVal Sh As Object) Private Sub Workbook_SheetBeforeDoubleClick(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean) Private Sub Workbook_SheetBeforeRightClick(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean) Private Sub Workbook_SheetCalculate(ByVal Sh As Object) Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range) Private Sub Workbook_SheetDeactivate(ByVal Sh As Object) Private Sub Workbook_SheetFollowHyperlink(ByVal Sh As Object, ByVal Target As Hyperlink) Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range) Private Sub Workbook_WindowActivate(ByVal Wn As Window) Private Sub Workbook_WindowDeactivate(ByVal Wn As Window) Private Sub Workbook_WindowResize(ByVal Wn As Window) Let us say, we just need to display a message to the user that a new sheet is created successfully, whenever a new sheet is created. Private Sub Workbook_NewSheet(ByVal Sh As Object) MsgBox "New Sheet Created Successfully" End Sub Upon creating a new excel sheet, a message is displayed to the user as shown in the following screenshot. There are three types of errors in programming: (a) Syntax Errors, (b) Runtime Errors, and (c) Logical Errors. Syntax errors, also called as parsing errors, occur at the interpretation time for VBScript. For example, the following line causes a syntax error because it is missing a closing parenthesis. Function ErrorHanlding_Demo() dim x,y x = "Tutorialspoint" y = Ucase(x End Function Runtime errors, also called exceptions, occur during execution, after interpretation. For example, the following line causes a runtime error because here the syntax is correct but at runtime it is trying to call fnmultiply, which is a non-existing function. Function ErrorHanlding_Demo1() Dim x,y x = 10 y = 20 z = fnadd(x,y) a = fnmultiply(x,y) End Function Function fnadd(x,y) fnadd = x + y End Function Logical errors can be the most difficult type of errors to track down. These errors are not the result of a syntax or runtime error. Instead, they occur when you make a mistake in the logic that drives your script and you do not get the result you expected. You cannot catch those errors, because it depends on your business requirement what type of logic you want to put in your program. For example, dividing a number by zero or a script that is written which enters into infinite loop. Assume if we have a runtime error, then the execution stops by displaying the error message. As a developer, if we want to capture the error, then Error Object is used. In the following example, Err.Number gives the error number and Err.Description gives the error description. Err.Raise 6 ' Raise an overflow error. MsgBox "Error # " & CStr(Err.Number) & " " & Err.Description Err.Clear ' Clear the error. VBA enables an error-handling routine and can also be used to disable an error-handling routine. Without an On Error statement, any run-time error that occurs is fatal: an error message is displayed, and the execution stops abruptly. On Error { GoTo [ line | 0 | -1 ] | Resume Next } GoTo line Enables the error-handling routine that starts at the line specified in the required line argument. The specified line must be in the same procedure as the On Error statement, or a compile-time error will occur. GoTo 0 Disables the enabled error handler in the current procedure and resets it to Nothing. GoTo -1 Disables the enabled exception in the current procedure and resets it to Nothing. Resume Next Specifies that when a run-time error occurs, the control goes to the statement immediately following the statement where the error occurred, and the execution continues from that point. Public Sub OnErrorDemo() On Error GoTo ErrorHandler ' Enable error-handling routine. Dim x, y, z As Integer x = 50 y = 0 z = x / y ' Divide by ZERO Error Raises ErrorHandler: ' Error-handling routine. Select Case Err.Number ' Evaluate error number. Case 10 ' Divide by zero error MsgBox ("You attempted to divide by zero!") Case Else MsgBox "UNKNOWN ERROR - Error# " & Err.Number & " : " & Err.Description End Select Resume Next End Sub When programming using VBA, there are few important objects that a user would be dealing with. Application Objects Workbook Objects Worksheet Objects Range Objects The Application object consists of the following − Application-wide settings and options. Methods that return top-level objects, such as ActiveCell, ActiveSheet, and so on. 'Example 1 : Set xlapp = CreateObject("Excel.Sheet") xlapp.Application.Workbooks.Open "C:\test.xls" 'Example 2 : Application.Windows("test.xls").Activate 'Example 3: Application.ActiveCell.Font.Bold = True The Workbook object is a member of the Workbooks collection and contains all the Workbook objects currently open in Microsoft Excel. 'Ex 1 : To close Workbooks Workbooks.Close 'Ex 2 : To Add an Empty Work Book Workbooks.Add 'Ex 3: To Open a Workbook Workbooks.Open FileName:="Test.xls", ReadOnly:=True 'Ex : 4 - To Activate WorkBooks Workbooks("Test.xls").Worksheets("Sheet1").Activate The Worksheet object is a member of the Worksheets collection and contains all the Worksheet objects in a workbook. 'Ex 1 : To make it Invisible Worksheets(1).Visible = False 'Ex 2 : To protect an WorkSheet Worksheets("Sheet1").Protect password:=strPassword, scenarios:=True Range Objects represent a cell, a row, a column, or a selection of cells containing one or more continuous blocks of cells. 'Ex 1 : To Put a value in the cell A5 Worksheets("Sheet1").Range("A5").Value = "5235" 'Ex 2 : To put a value in range of Cells Worksheets("Sheet1").Range("A1:A4").Value = 5 You can also read Excel File and write the contents of the cell into a Text File using VBA. VBA allows the users to work with text files using two methods − File System Object using Write Command As the name suggests, FSOs help the developers to work with drives, folders, and files. In this section, we will discuss how to use a FSO. Drive Drive is an Object. Contains methods and properties that allow you to gather information about a drive attached to the system. Drives Drives is a Collection. It provides a list of the drives attached to the system, either physically or logically. File File is an Object. It contains methods and properties that allow developers to create, delete, or move a file. Files Files is a Collection. It provides a list of all the files contained within a folder. Folder Folder is an Object. It provides methods and properties that allow the developers to create, delete, or move folders. Folders Folders is a Collection. It provides a list of all the folders within a folder. TextStream TextStream is an Object. It enables the developers to read and write text files. Drive is an object, which provides access to the properties of a particular disk drive or network share. Following properties are supported by Drive object − AvailableSpace DriveLetter DriveType FileSystem FreeSpace IsReady Path RootFolder SerialNumber ShareName TotalSize VolumeName Step 1 − Before proceeding to scripting using FSO, we should enable Microsoft Scripting Runtime. To do the same, navigate to Tools → References as shown in the following screenshot. Step 2 − Add "Microsoft Scripting RunTime" and Click OK. Step 3 − Add Data that you would like to write in a Text File and add a Command Button. Step 4 − Now it is time to Script. Private Sub fn_write_to_text_Click() Dim FilePath As String Dim CellData As String Dim LastCol As Long Dim LastRow As Long Dim fso As FileSystemObject Set fso = New FileSystemObject Dim stream As TextStream LastCol = ActiveSheet.UsedRange.Columns.Count LastRow = ActiveSheet.UsedRange.Rows.Count ' Create a TextStream. Set stream = fso.OpenTextFile("D:\Try\Support.log", ForWriting, True) CellData = "" For i = 1 To LastRow For j = 1 To LastCol CellData = Trim(ActiveCell(i, j).Value) stream.WriteLine "The Value at location (" & i & "," & j & ")" & CellData Next j Next i stream.Close MsgBox ("Job Done") End Sub When executing the script, ensure that you place the cursor in the first cell of the worksheet. The Support.log file is created as shown in the following screenshot under "D:\Try". The Contents of the file are shown in the following screenshot. Unlike FSO, we need NOT add any references, however, we will NOT be able to work with drives, files and folders. We will be able to just add the stream to the text file. Private Sub fn_write_to_text_Click() Dim FilePath As String Dim CellData As String Dim LastCol As Long Dim LastRow As Long LastCol = ActiveSheet.UsedRange.Columns.Count LastRow = ActiveSheet.UsedRange.Rows.Count FilePath = "D:\Try\write.txt" Open FilePath For Output As #2 CellData = "" For i = 1 To LastRow For j = 1 To LastCol CellData = "The Value at location (" & i & "," & j & ")" & Trim(ActiveCell(i, j).Value) Write #2, CellData Next j Next i Close #2 MsgBox ("Job Done") End Sub Upon executing the script, the "write.txt" file is created in the location "D:\Try" as shown in the following screenshot. The contents of the file are shown in the following screenshot. Using VBA, you can generate charts based on certain criteria. Let us take a look at it using an example. Step 1 − Enter the data against which the graph has to be generated. Step 2 − Create 3 buttons - one to generate a bar graph, another to generate a pie chart, and another to generate a column chart. Step 3 − Develop a Macro to generate each one of these type of charts. ' Procedure to Generate Pie Chart Private Sub fn_generate_pie_graph_Click() Dim cht As ChartObject For Each cht In Worksheets(1).ChartObjects cht.Chart.Type = xlPie Next cht End Sub ' Procedure to Generate Bar Graph Private Sub fn_Generate_Bar_Graph_Click() Dim cht As ChartObject For Each cht In Worksheets(1).ChartObjects cht.Chart.Type = xlBar Next cht End Sub ' Procedure to Generate Column Graph Private Sub fn_generate_column_graph_Click() Dim cht As ChartObject For Each cht In Worksheets(1).ChartObjects cht.Chart.Type = xlColumn Next cht End Sub Step 4 − Upon clicking the corresponding button, the chart is created. In the following output, click on generate Pie Chart button. A User Form is a custom-built dialog box that makes a user data entry more controllable and easier to use for the user. In this chapter, you will learn to design a simple form and add data into excel. Step 1 − Navigate to VBA Window by pressing Alt+F11 and Navigate to "Insert" Menu and select "User Form". Upon selecting, the user form is displayed as shown in the following screenshot. Step 2 − Design the forms using the given controls. Step 3 − After adding each control, the controls have to be named. Caption corresponds to what appears on the form and name corresponds to the logical name that will be appearing when you write VBA code for that element. Step 4 − Following are the names against each one of the added controls. Step 5 − Add the code for the form load event by performing a right-click on the form and selecting 'View Code'. Step 6 − Select ‘Userform’ from the objects drop-down and select 'Initialize' method as shown in the following screenshot. Step 7 − Upon Loading the form, ensure that the text boxes are cleared, drop-down boxes are filled and Radio buttons are reset. Private Sub UserForm_Initialize() 'Empty Emp ID Text box and Set the Cursor txtempid.Value = "" txtempid.SetFocus 'Empty all other text box fields txtfirstname.Value = "" txtlastname.Value = "" txtemailid.Value = "" 'Clear All Date of Birth Related Fields cmbdate.Clear cmbmonth.Clear cmbyear.Clear 'Fill Date Drop Down box - Takes 1 to 31 With cmbdate .AddItem "1" .AddItem "2" .AddItem "3" .AddItem "4" .AddItem "5" .AddItem "6" .AddItem "7" .AddItem "8" .AddItem "9" .AddItem "10" .AddItem "11" .AddItem "12" .AddItem "13" .AddItem "14" .AddItem "15" .AddItem "16" .AddItem "17" .AddItem "18" .AddItem "19" .AddItem "20" .AddItem "21" .AddItem "22" .AddItem "23" .AddItem "24" .AddItem "25" .AddItem "26" .AddItem "27" .AddItem "28" .AddItem "29" .AddItem "30" .AddItem "31" End With 'Fill Month Drop Down box - Takes Jan to Dec With cmbmonth .AddItem "JAN" .AddItem "FEB" .AddItem "MAR" .AddItem "APR" .AddItem "MAY" .AddItem "JUN" .AddItem "JUL" .AddItem "AUG" .AddItem "SEP" .AddItem "OCT" .AddItem "NOV" .AddItem "DEC" End With 'Fill Year Drop Down box - Takes 1980 to 2014 With cmbyear .AddItem "1980" .AddItem "1981" .AddItem "1982" .AddItem "1983" .AddItem "1984" .AddItem "1985" .AddItem "1986" .AddItem "1987" .AddItem "1988" .AddItem "1989" .AddItem "1990" .AddItem "1991" .AddItem "1992" .AddItem "1993" .AddItem "1994" .AddItem "1995" .AddItem "1996" .AddItem "1997" .AddItem "1998" .AddItem "1999" .AddItem "2000" .AddItem "2001" .AddItem "2002" .AddItem "2003" .AddItem "2004" .AddItem "2005" .AddItem "2006" .AddItem "2007" .AddItem "2008" .AddItem "2009" .AddItem "2010" .AddItem "2011" .AddItem "2012" .AddItem "2013" .AddItem "2014" End With 'Reset Radio Button. Set it to False when form loads. radioyes.Value = False radiono.Value = False End Sub Step 8 − Now add the code to the Submit button. Upon clicking the submit button, the user should be able to add the values into the worksheet. Private Sub btnsubmit_Click() Dim emptyRow As Long 'Make Sheet1 active Sheet1.Activate 'Determine emptyRow emptyRow = WorksheetFunction.CountA(Range("A:A")) + 1 'Transfer information Cells(emptyRow, 1).Value = txtempid.Value Cells(emptyRow, 2).Value = txtfirstname.Value Cells(emptyRow, 3).Value = txtlastname.Value Cells(emptyRow, 4).Value = cmbdate.Value & "/" & cmbmonth.Value & "/" & cmbyear.Value Cells(emptyRow, 5).Value = txtemailid.Value If radioyes.Value = True Then Cells(emptyRow, 6).Value = "Yes" Else Cells(emptyRow, 6).Value = "No" End If End Sub Step 9 − Add a method to close the form when the user clicks the Cancel button. Private Sub btncancel_Click() Unload Me End Sub Step 10 − Execute the form by clicking the "Run" button. Enter the values into the form and click the 'Submit' button. Automatically the values will flow into the worksheet as shown in the following screenshot. 101 Lectures 6 hours Pavan Lalwani 41 Lectures 3 hours Arnold Higuit 80 Lectures 5.5 hours Prashant Panchal 25 Lectures 2 hours Prashant Panchal 26 Lectures 2 hours Arnold Higuit 92 Lectures 10.5 hours Vijay Kumar Parvatha Reddy Print Add Notes Bookmark this page
[ { "code": null, "e": 2139, "s": 1935, "text": "VBA stands for Visual Basic for Applications an event-driven programming language from Microsoft that is now predominantly used with Microsoft office applications such as MSExcel, MS-Word, and MS-Access." }, { "code": null, "e": 2419, "s": 2139, "text": "It helps techies to build customized applications and solutions to enhance the capabilities of those applications. The advantage of this facility is that you NEED NOT have visual basic installed on our PC, however, installing Office will implicitly help in achieving the purpose." }, { "code": null, "e": 2702, "s": 2419, "text": "You can use VBA in all office versions, right from MS-Office 97 to MS-Office 2013 and also with any of the latest versions available. Among VBA, Excel VBA is the most popular. The advantage of using VBA is that you can build very powerful tools in MS Excel using linear programming." }, { "code": null, "e": 2974, "s": 2702, "text": "You might wonder why to use VBA in Excel as MS-Excel itself provides loads of inbuilt functions. MS-Excel provides only basic inbuilt functions which might not be sufficient to perform complex calculations. Under such circumstances, VBA becomes the most obvious solution." }, { "code": null, "e": 3141, "s": 2974, "text": "For example, it is very hard to calculate the monthly repayment of a loan using Excel's built-in formulas. Rather, it is easy to program a VBA for such a calculation." }, { "code": null, "e": 3235, "s": 3141, "text": "In Excel window, press \"ALT+F11\". A VBA window opens up as shown in the following screenshot." }, { "code": null, "e": 3321, "s": 3235, "text": "In this chapter, you will learn how to write a simple macro in a step by step manner." }, { "code": null, "e": 3414, "s": 3321, "text": "Step 1 − First, enable 'Developer' menu in Excel 20XX. To do the same, click File → Options." }, { "code": null, "e": 3491, "s": 3414, "text": "Step 2 − Click ‘Customize the Ribbon’ tab and check 'Developer'. Click 'OK'." }, { "code": null, "e": 3548, "s": 3491, "text": "Step 3 − The 'Developer' ribbon appears in the menu bar." }, { "code": null, "e": 3613, "s": 3548, "text": "Step 4 − Click the 'Visual Basic' button to open the VBA Editor." }, { "code": null, "e": 3692, "s": 3613, "text": "Step 5 − Start scripting by adding a button. Click Insert → Select the button." }, { "code": null, "e": 3748, "s": 3692, "text": "Step 6 − Perform a right-click and choose 'properties'." }, { "code": null, "e": 3821, "s": 3748, "text": "Step 7 − Edit the name and caption as shown in the following screenshot." }, { "code": null, "e": 3944, "s": 3821, "text": "Step 8 − Now double-click the button and the sub-procedure outline will be displayed as shown in the following screenshot." }, { "code": null, "e": 3994, "s": 3944, "text": "Step 9 − Start coding by simply adding a message." }, { "code": null, "e": 4052, "s": 3994, "text": "Private Sub say_helloworld_Click()\n MsgBox \"Hi\"\nEnd Sub" }, { "code": null, "e": 4276, "s": 4052, "text": "Step 10 − Click the button to execute the sub-procedure. The output of the sub-procedure is shown in the following screenshot. Make sure that you do have design mode turned on. Simply click it to turn it on if it is not on." }, { "code": null, "e": 4442, "s": 4276, "text": "Note − In further chapters, we will demonstrate using a simple button, as explained from step#1 to 10. Hence , it is important to understand this chapter thoroughly." }, { "code": null, "e": 4639, "s": 4442, "text": "In this chapter, you will acquaint yourself with the commonly used excel VBA terminologies. These terminologies will be used in further modules, hence understanding each one of these is important." }, { "code": null, "e": 4742, "s": 4639, "text": "Modules is the area where the code is written. This is a new Workbook, hence there aren't any Modules." }, { "code": null, "e": 4839, "s": 4742, "text": "To insert a Module, navigate to Insert → Module. Once a module is inserted 'module1' is created." }, { "code": null, "e": 5005, "s": 4839, "text": "Within the modules, we can write VBA code and the code is written within a Procedure. A Procedure/Sub Procedure is a series of VBA statements instructing what to do." }, { "code": null, "e": 5272, "s": 5005, "text": "Procedures are a group of statements executed as a whole, which instructs Excel how to perform a specific task. The task performed can be a very simple or a very complicated task. However, it is a good practice to break down complicated procedures into smaller ones." }, { "code": null, "e": 5327, "s": 5272, "text": "The two main types of Procedures are Sub and Function." }, { "code": null, "e": 5584, "s": 5327, "text": "A function is a group of reusable code, which can be called anywhere in your program. This eliminates the need of writing the same code over and over again. This helps the programmers to divide a big program into a number of small and manageable functions." }, { "code": null, "e": 5727, "s": 5584, "text": "Apart from inbuilt Functions, VBA allows to write user-defined functions as well and statements are written between Function and End Function." }, { "code": null, "e": 5975, "s": 5727, "text": "Sub-procedures work similar to functions. While sub procedures DO NOT Return a value, functions may or may not return a value. Sub procedures CAN be called without call keyword. Sub procedures are always enclosed within Sub and End Sub statements." }, { "code": null, "e": 6125, "s": 5975, "text": "Comments are used to document the program logic and the user information with which other programmers can seamlessly work on the same code in future." }, { "code": null, "e": 6282, "s": 6125, "text": "It includes information such as developed by, modified by, and can also include incorporated logic. Comments are ignored by the interpreter while execution." }, { "code": null, "e": 6326, "s": 6282, "text": "Comments in VBA are denoted by two methods." }, { "code": null, "e": 6424, "s": 6326, "text": "Any statement that starts with a Single Quote (') is treated as comment. Following is an example." }, { "code": null, "e": 6522, "s": 6424, "text": "Any statement that starts with a Single Quote (') is treated as comment. Following is an example." }, { "code": null, "e": 6633, "s": 6522, "text": "' This Script is invoked after successful login \n' Written by : TutorialsPoint \n' Return Value : True / False\n" }, { "code": null, "e": 6708, "s": 6633, "text": "Any statement that starts with the keyword \"REM\". Following is an example." }, { "code": null, "e": 6783, "s": 6708, "text": "Any statement that starts with the keyword \"REM\". Following is an example." }, { "code": null, "e": 6883, "s": 6783, "text": "REM This Script is written to Validate the Entered Input \nREM Modified by : Tutorials point/user2\n" }, { "code": null, "e": 7040, "s": 6883, "text": "The MsgBox function displays a message box and waits for the user to click a button and then an action is performed based on the button clicked by the user." }, { "code": null, "e": 7093, "s": 7040, "text": "MsgBox(prompt[,buttons][,title][,helpfile,context])\n" }, { "code": null, "e": 7419, "s": 7093, "text": "Prompt − A Required Parameter. A String that is displayed as a message in the dialog box. The maximum length of prompt is approximately 1024 characters. If the message extends to more than a line, then the lines can be separated using a carriage return character (Chr(13)) or a linefeed character (Chr(10)) between each line." }, { "code": null, "e": 7745, "s": 7419, "text": "Prompt − A Required Parameter. A String that is displayed as a message in the dialog box. The maximum length of prompt is approximately 1024 characters. If the message extends to more than a line, then the lines can be separated using a carriage return character (Chr(13)) or a linefeed character (Chr(10)) between each line." }, { "code": null, "e": 7993, "s": 7745, "text": "Buttons − An Optional Parameter. A Numeric expression that specifies the type of buttons to display, the icon style to use, the identity of the default button, and the modality of the message box. If left blank, the default value for buttons is 0." }, { "code": null, "e": 8241, "s": 7993, "text": "Buttons − An Optional Parameter. A Numeric expression that specifies the type of buttons to display, the icon style to use, the identity of the default button, and the modality of the message box. If left blank, the default value for buttons is 0." }, { "code": null, "e": 8415, "s": 8241, "text": "Title − An Optional Parameter. A String expression displayed in the title bar of the dialog box. If the title is left blank, the application name is placed in the title bar." }, { "code": null, "e": 8589, "s": 8415, "text": "Title − An Optional Parameter. A String expression displayed in the title bar of the dialog box. If the title is left blank, the application name is placed in the title bar." }, { "code": null, "e": 8737, "s": 8589, "text": "Helpfile − An Optional Parameter. A String expression that identifies the Help file to use for providing context-sensitive help for the dialog box." }, { "code": null, "e": 8885, "s": 8737, "text": "Helpfile − An Optional Parameter. A String expression that identifies the Help file to use for providing context-sensitive help for the dialog box." }, { "code": null, "e": 9094, "s": 8885, "text": "Context − An Optional Parameter. A Numeric expression that identifies the Help context number assigned by the Help author to the appropriate Help topic. If context is provided, helpfile must also be provided." }, { "code": null, "e": 9303, "s": 9094, "text": "Context − An Optional Parameter. A Numeric expression that identifies the Help context number assigned by the Help author to the appropriate Help topic. If context is provided, helpfile must also be provided." }, { "code": null, "e": 9364, "s": 9303, "text": "The Buttons parameter can take any of the following values −" }, { "code": null, "e": 9402, "s": 9364, "text": "0 vbOKOnly - Displays OK button only." }, { "code": null, "e": 9440, "s": 9402, "text": "0 vbOKOnly - Displays OK button only." }, { "code": null, "e": 9487, "s": 9440, "text": "1 vbOKCancel - Displays OK and Cancel buttons." }, { "code": null, "e": 9534, "s": 9487, "text": "1 vbOKCancel - Displays OK and Cancel buttons." }, { "code": null, "e": 9600, "s": 9534, "text": "2 vbAbortRetryIgnore - Displays Abort, Retry, and Ignore buttons." }, { "code": null, "e": 9666, "s": 9600, "text": "2 vbAbortRetryIgnore - Displays Abort, Retry, and Ignore buttons." }, { "code": null, "e": 9722, "s": 9666, "text": "3 vbYesNoCancel - Displays Yes, No, and Cancel buttons." }, { "code": null, "e": 9778, "s": 9722, "text": "3 vbYesNoCancel - Displays Yes, No, and Cancel buttons." }, { "code": null, "e": 9819, "s": 9778, "text": "4 vbYesNo - Displays Yes and No buttons." }, { "code": null, "e": 9860, "s": 9819, "text": "4 vbYesNo - Displays Yes and No buttons." }, { "code": null, "e": 9913, "s": 9860, "text": "5 vbRetryCancel - Displays Retry and Cancel buttons." }, { "code": null, "e": 9966, "s": 9913, "text": "5 vbRetryCancel - Displays Retry and Cancel buttons." }, { "code": null, "e": 10014, "s": 9966, "text": "16 vbCritical - Displays Critical Message icon." }, { "code": null, "e": 10062, "s": 10014, "text": "16 vbCritical - Displays Critical Message icon." }, { "code": null, "e": 10107, "s": 10062, "text": "32 vbQuestion - Displays Warning Query icon." }, { "code": null, "e": 10152, "s": 10107, "text": "32 vbQuestion - Displays Warning Query icon." }, { "code": null, "e": 10202, "s": 10152, "text": "48 vbExclamation - Displays Warning Message icon." }, { "code": null, "e": 10252, "s": 10202, "text": "48 vbExclamation - Displays Warning Message icon." }, { "code": null, "e": 10306, "s": 10252, "text": "64 vbInformation - Displays Information Message icon." }, { "code": null, "e": 10360, "s": 10306, "text": "64 vbInformation - Displays Information Message icon." }, { "code": null, "e": 10406, "s": 10360, "text": "0 vbDefaultButton1 - First button is default." }, { "code": null, "e": 10452, "s": 10406, "text": "0 vbDefaultButton1 - First button is default." }, { "code": null, "e": 10501, "s": 10452, "text": "256 vbDefaultButton2 - Second button is default." }, { "code": null, "e": 10550, "s": 10501, "text": "256 vbDefaultButton2 - Second button is default." }, { "code": null, "e": 10598, "s": 10550, "text": "512 vbDefaultButton3 - Third button is default." }, { "code": null, "e": 10646, "s": 10598, "text": "512 vbDefaultButton3 - Third button is default." }, { "code": null, "e": 10695, "s": 10646, "text": "768 vbDefaultButton4 - Fourth button is default." }, { "code": null, "e": 10744, "s": 10695, "text": "768 vbDefaultButton4 - Fourth button is default." }, { "code": null, "e": 10867, "s": 10744, "text": "0 vbApplicationModal Application modal - The current application will not work until the user responds to the message box." }, { "code": null, "e": 10990, "s": 10867, "text": "0 vbApplicationModal Application modal - The current application will not work until the user responds to the message box." }, { "code": null, "e": 11099, "s": 10990, "text": "4096 vbSystemModal System modal - All applications will not work until the user responds to the message box." }, { "code": null, "e": 11208, "s": 11099, "text": "4096 vbSystemModal System modal - All applications will not work until the user responds to the message box." }, { "code": null, "e": 11585, "s": 11208, "text": "The above values are logically divided into four groups: The first group (0 to 5) indicates the buttons to be displayed in the message box. The second group (16, 32, 48, 64) describes the style of the icon to be displayed, the third group (0, 256, 512, 768) indicates which button must be the default, and the fourth group (0, 4096) determines the modality of the message box." }, { "code": null, "e": 11726, "s": 11585, "text": "The MsgBox function can return one of the following values which can be used to identify the button the user has clicked in the message box." }, { "code": null, "e": 11752, "s": 11726, "text": "1 - vbOK - OK was clicked" }, { "code": null, "e": 11786, "s": 11752, "text": "2 - vbCancel - Cancel was clicked" }, { "code": null, "e": 11818, "s": 11786, "text": "3 - vbAbort - Abort was clicked" }, { "code": null, "e": 11850, "s": 11818, "text": "4 - vbRetry - Retry was clicked" }, { "code": null, "e": 11884, "s": 11850, "text": "5 - vbIgnore - Ignore was clicked" }, { "code": null, "e": 11912, "s": 11884, "text": "6 - vbYes - Yes was clicked" }, { "code": null, "e": 11938, "s": 11912, "text": "7 - vbNo - No was clicked" }, { "code": null, "e": 12250, "s": 11938, "text": "Function MessageBox_Demo() \n 'Message Box with just prompt message \n MsgBox(\"Welcome\") \n \n 'Message Box with title, yes no and cancel Butttons \n int a = MsgBox(\"Do you like blue color?\",3,\"Choose options\") \n ' Assume that you press No Button \n msgbox (\"The Value of a is \" & a) \nEnd Function" }, { "code": null, "e": 12430, "s": 12250, "text": "Step 1 − The above Function can be executed either by clicking the \"Run\" button on VBA Window or by calling the function from Excel Worksheet as shown in the following screenshot." }, { "code": null, "e": 12517, "s": 12430, "text": "Step 2 − A Simple Message box is displayed with a message \"Welcome\" and an \"OK\" Button" }, { "code": null, "e": 12638, "s": 12517, "text": "Step 3 − After Clicking OK, yet another dialog box is displayed with a message along with \"yes, no, and cancel\" buttons." }, { "code": null, "e": 12887, "s": 12638, "text": "Step 4 − After clicking the ‘No’ button, the value of that button (7) is stored as an integer and displayed as a message box to the user as shown in the following screenshot. Using this value, it can be understood which button the user has clicked." }, { "code": null, "e": 13183, "s": 12887, "text": "The InputBox function prompts the users to enter values. After entering the values, if the user clicks the OK button or presses ENTER on the keyboard, the InputBox function will return the text in the text box. If the user clicks the Cancel button, the function will return an empty string (\"\")." }, { "code": null, "e": 13252, "s": 13183, "text": "InputBox(prompt[,title][,default][,xpos][,ypos][,helpfile,context])\n" }, { "code": null, "e": 13578, "s": 13252, "text": "Prompt − A required parameter. A String that is displayed as a message in the dialog box. The maximum length of prompt is approximately 1024 characters. If the message extends to more than a line, then the lines can be separated using a carriage return character (Chr(13)) or a linefeed character (Chr(10)) between each line." }, { "code": null, "e": 13904, "s": 13578, "text": "Prompt − A required parameter. A String that is displayed as a message in the dialog box. The maximum length of prompt is approximately 1024 characters. If the message extends to more than a line, then the lines can be separated using a carriage return character (Chr(13)) or a linefeed character (Chr(10)) between each line." }, { "code": null, "e": 14078, "s": 13904, "text": "Title − An optional parameter. A String expression displayed in the title bar of the dialog box. If the title is left blank, the application name is placed in the title bar." }, { "code": null, "e": 14252, "s": 14078, "text": "Title − An optional parameter. A String expression displayed in the title bar of the dialog box. If the title is left blank, the application name is placed in the title bar." }, { "code": null, "e": 14358, "s": 14252, "text": "Default − An optional parameter. A default text in the text box that the user would like to be displayed." }, { "code": null, "e": 14464, "s": 14358, "text": "Default − An optional parameter. A default text in the text box that the user would like to be displayed." }, { "code": null, "e": 14650, "s": 14464, "text": "XPos − An optional parameter. The position of X axis represents the prompt distance from the left side of the screen horizontally. If left blank, the input box is horizontally centered." }, { "code": null, "e": 14836, "s": 14650, "text": "XPos − An optional parameter. The position of X axis represents the prompt distance from the left side of the screen horizontally. If left blank, the input box is horizontally centered." }, { "code": null, "e": 15018, "s": 14836, "text": "YPos − An optional parameter. The position of Y axis represents the prompt distance from the left side of the screen vertically. If left blank, the input box is vertically centered." }, { "code": null, "e": 15200, "s": 15018, "text": "YPos − An optional parameter. The position of Y axis represents the prompt distance from the left side of the screen vertically. If left blank, the input box is vertically centered." }, { "code": null, "e": 15348, "s": 15200, "text": "Helpfile − An optional parameter. A String expression that identifies the helpfile to be used to provide context-sensitive Help for the dialog box." }, { "code": null, "e": 15496, "s": 15348, "text": "Helpfile − An optional parameter. A String expression that identifies the helpfile to be used to provide context-sensitive Help for the dialog box." }, { "code": null, "e": 15705, "s": 15496, "text": "context − An optional parameter. A Numeric expression that identifies the Help context number assigned by the Help author to the appropriate Help topic. If context is provided, helpfile must also be provided." }, { "code": null, "e": 15914, "s": 15705, "text": "context − An optional parameter. A Numeric expression that identifies the Help context number assigned by the Help author to the appropriate Help topic. If context is provided, helpfile must also be provided." }, { "code": null, "e": 16068, "s": 15914, "text": "Let us calculate the area of a rectangle by getting values from the user at run time with the help of two input boxes (one for length and one for width)." }, { "code": null, "e": 16296, "s": 16068, "text": "Function findArea() \n Dim Length As Double \n Dim Width As Double \n \n Length = InputBox(\"Enter Length \", \"Enter a Number\") \n Width = InputBox(\"Enter Width\", \"Enter a Number\") \n findArea = Length * Width \nEnd Function" }, { "code": null, "e": 16409, "s": 16296, "text": "Step 1 − To execute the same, call using the function name and press Enter as shown in the following screenshot." }, { "code": null, "e": 16511, "s": 16409, "text": "Step 2 − Upon execution, the First input box (length) is displayed. Enter a value into the input box." }, { "code": null, "e": 16595, "s": 16511, "text": "Step 3 − After entering the first value, the second input box (width) is displayed." }, { "code": null, "e": 16718, "s": 16595, "text": "Step 4 − Upon entering the second number, click the OK button. The area is displayed as shown in the following screenshot." }, { "code": null, "e": 16877, "s": 16718, "text": "Variable is a named memory location used to hold a value that can be changed during the script execution. Following are the basic rules for naming a variable." }, { "code": null, "e": 16923, "s": 16877, "text": "You must use a letter as the first character." }, { "code": null, "e": 16969, "s": 16923, "text": "You must use a letter as the first character." }, { "code": null, "e": 17068, "s": 16969, "text": "You can't use a space, period (.), exclamation mark (!), or the characters @, &, $, # in the name." }, { "code": null, "e": 17167, "s": 17068, "text": "You can't use a space, period (.), exclamation mark (!), or the characters @, &, $, # in the name." }, { "code": null, "e": 17211, "s": 17167, "text": "Name can't exceed 255 characters in length." }, { "code": null, "e": 17255, "s": 17211, "text": "Name can't exceed 255 characters in length." }, { "code": null, "e": 17319, "s": 17255, "text": "You cannot use Visual Basic reserved keywords as variable name." }, { "code": null, "e": 17383, "s": 17319, "text": "You cannot use Visual Basic reserved keywords as variable name." }, { "code": null, "e": 17390, "s": 17383, "text": "Syntax" }, { "code": null, "e": 17451, "s": 17390, "text": "In VBA, you need to declare the variables before using them." }, { "code": null, "e": 17495, "s": 17451, "text": "Dim <<variable_name>> As <<variable_type>>\n" }, { "code": null, "e": 17616, "s": 17495, "text": "There are many VBA data types, which can be divided into two main categories, namely numeric and non-numeric data types." }, { "code": null, "e": 17697, "s": 17616, "text": "Following table displays the numeric data types and the allowed range of values." }, { "code": null, "e": 17748, "s": 17697, "text": "-3.402823E+38 to -1.401298E-45 for negative values" }, { "code": null, "e": 17798, "s": 17748, "text": "1.401298E-45 to 3.402823E+38 for positive values." }, { "code": null, "e": 17867, "s": 17798, "text": "-1.79769313486232e+308 to -4.94065645841247E-324 for negative values" }, { "code": null, "e": 17935, "s": 17867, "text": "4.94065645841247E-324 to 1.79769313486232e+308 for positive values." }, { "code": null, "e": 17999, "s": 17935, "text": "+/- 79,228,162,514,264,337,593,543,950,335 if no decimal is use" }, { "code": null, "e": 18055, "s": 17999, "text": "+/- 7.9228162514264337593543950335 (28 decimal places)." }, { "code": null, "e": 18140, "s": 18055, "text": "Following table displays the non-numeric data types and the allowed range of values." }, { "code": null, "e": 18148, "s": 18140, "text": "Example" }, { "code": null, "e": 18240, "s": 18148, "text": "Let us create a button and name it as 'Variables_demo' to demonstrate the use of variables." }, { "code": null, "e": 18564, "s": 18240, "text": "Private Sub say_helloworld_Click()\n Dim password As String\n password = \"Admin#1\"\n\n Dim num As Integer\n num = 1234\n\n Dim BirthDay As Date\n BirthDay = DateValue(\"30 / 10 / 2020\")\n\n MsgBox \"Passowrd is \" & password & Chr(10) & \"Value of num is \" &\n num & Chr(10) & \"Value of Birthday is \" & BirthDay\nEnd Sub" }, { "code": null, "e": 18571, "s": 18564, "text": "Output" }, { "code": null, "e": 18655, "s": 18571, "text": "Upon executing the script, the output will be as shown in the following screenshot." }, { "code": null, "e": 18916, "s": 18655, "text": "Constant is a named memory location used to hold a value that CANNOT be changed during the script execution. If a user tries to change a Constant value, the script execution ends up with an error. Constants are declared the same way the variables are declared." }, { "code": null, "e": 18963, "s": 18916, "text": "Following are the rules for naming a constant." }, { "code": null, "e": 19009, "s": 18963, "text": "You must use a letter as the first character." }, { "code": null, "e": 19055, "s": 19009, "text": "You must use a letter as the first character." }, { "code": null, "e": 19154, "s": 19055, "text": "You can't use a space, period (.), exclamation mark (!), or the characters @, &, $, # in the name." }, { "code": null, "e": 19253, "s": 19154, "text": "You can't use a space, period (.), exclamation mark (!), or the characters @, &, $, # in the name." }, { "code": null, "e": 19297, "s": 19253, "text": "Name can't exceed 255 characters in length." }, { "code": null, "e": 19341, "s": 19297, "text": "Name can't exceed 255 characters in length." }, { "code": null, "e": 19405, "s": 19341, "text": "You cannot use Visual Basic reserved keywords as variable name." }, { "code": null, "e": 19469, "s": 19405, "text": "You cannot use Visual Basic reserved keywords as variable name." }, { "code": null, "e": 19597, "s": 19469, "text": "In VBA, we need to assign a value to the declared Constants. An error is thrown, if we try to change the value of the constant." }, { "code": null, "e": 19664, "s": 19597, "text": "Const <<constant_name>> As <<constant_type>> = <<constant_value>>\n" }, { "code": null, "e": 19746, "s": 19664, "text": "Let us create a button \"Constant_demo\" to demonstrate how to work with constants." }, { "code": null, "e": 20015, "s": 19746, "text": "Private Sub Constant_demo_Click() \n Const MyInteger As Integer = 42 \n Const myDate As Date = #2/2/2020# \n Const myDay As String = \"Sunday\" \n \n MsgBox \"Integer is \" & MyInteger & Chr(10) & \"myDate is \" \n & myDate & Chr(10) & \"myDay is \" & myDay \nEnd Sub" }, { "code": null, "e": 20109, "s": 20015, "text": "Upon executing the script, the output will be displayed as shown in the following screenshot." }, { "code": null, "e": 20289, "s": 20109, "text": "An Operator can be defined using a simple expression - 4 + 5 is equal to 9. Here, 4 and 5 are called operands and + is called operator. VBA supports following types of operators −" }, { "code": null, "e": 20310, "s": 20289, "text": "Arithmetic Operators" }, { "code": null, "e": 20331, "s": 20310, "text": "Comparison Operators" }, { "code": null, "e": 20365, "s": 20331, "text": "Logical (or Relational) Operators" }, { "code": null, "e": 20389, "s": 20365, "text": "Concatenation Operators" }, { "code": null, "e": 20442, "s": 20389, "text": "Following arithmetic operators are supported by VBA." }, { "code": null, "e": 20500, "s": 20442, "text": "Assume variable A holds 5 and variable B holds 10, then −" }, { "code": null, "e": 20514, "s": 20500, "text": "Show Examples" }, { "code": null, "e": 20573, "s": 20514, "text": "There are following comparison operators supported by VBA." }, { "code": null, "e": 20632, "s": 20573, "text": "Assume variable A holds 10 and variable B holds 20, then −" }, { "code": null, "e": 20646, "s": 20632, "text": "Show Examples" }, { "code": null, "e": 20696, "s": 20646, "text": "Following logical operators are supported by VBA." }, { "code": null, "e": 20754, "s": 20696, "text": "Assume variable A holds 10 and variable B holds 0, then −" }, { "code": null, "e": 20768, "s": 20754, "text": "Show Examples" }, { "code": null, "e": 20824, "s": 20768, "text": "Following Concatenation operators are supported by VBA." }, { "code": null, "e": 20881, "s": 20824, "text": "Assume variable A holds 5 and variable B holds 10 then −" }, { "code": null, "e": 20895, "s": 20881, "text": "Show Examples" }, { "code": null, "e": 20963, "s": 20895, "text": "Assume variable A = \"Microsoft\" and variable B = \"VBScript\", then −" }, { "code": null, "e": 21124, "s": 20963, "text": "Note − Concatenation Operators can be used for both numbers and strings. The output depends on the context, if the variables hold numeric value or string value." }, { "code": null, "e": 21294, "s": 21124, "text": "Decision making allows the programmers to control the execution flow of a script or one of its sections. The execution is governed by one or more conditional statements." }, { "code": null, "e": 21407, "s": 21294, "text": "Following is the general form of a typical decision making structure found in most of the programming languages." }, { "code": null, "e": 21521, "s": 21407, "text": "VBA provides the following types of decision making statements. Click the following links to check their details." }, { "code": null, "e": 21606, "s": 21521, "text": "An if statement consists of a Boolean expression followed by one or more statements." }, { "code": null, "e": 21839, "s": 21606, "text": "An if else statement consists of a Boolean expression followed by one or more statements. If the condition is True, the statements under If statements are executed. If the condition is false, the Else part of the script is executed." }, { "code": null, "e": 22036, "s": 21839, "text": "An if statement followed by one or more ElseIf statements, that consists of Boolean expressions and then followed by an optional else statement, which executes when all the condition become false." }, { "code": null, "e": 22104, "s": 22036, "text": "An if or elseif statement inside another if or elseif statement(s)." }, { "code": null, "e": 22193, "s": 22104, "text": "A switch statement allows a variable to be tested for equality against a list of values." }, { "code": null, "e": 22422, "s": 22193, "text": "There may be a situation when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on." }, { "code": null, "e": 22528, "s": 22422, "text": "Programming languages provide various control structures that allow for more complicated execution paths." }, { "code": null, "e": 22675, "s": 22528, "text": "A loop statement allows us to execute a statement or group of statements multiple times. Following is the general form of a loop statement in VBA." }, { "code": null, "e": 22798, "s": 22675, "text": "VBA provides the following types of loops to handle looping requirements. Click the following links to check their detail." }, { "code": null, "e": 22904, "s": 22798, "text": "Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable." }, { "code": null, "e": 23011, "s": 22904, "text": "This is executed if there is at least one element in the group and reiterated for each element in a group." }, { "code": null, "e": 23068, "s": 23011, "text": "This tests the condition before executing the loop body." }, { "code": null, "e": 23208, "s": 23068, "text": "The do..While statements will be executed as long as the condition is True.(i.e.,) The Loop should be repeated till the condition is False." }, { "code": null, "e": 23348, "s": 23208, "text": "The do..Until statements will be executed as long as the condition is False.(i.e.,) The Loop should be repeated till the condition is True." }, { "code": null, "e": 23505, "s": 23348, "text": "Loop control statements change execution from its normal sequence. When execution leaves a scope, all the remaining statements in the loop are NOT executed." }, { "code": null, "e": 23601, "s": 23505, "text": "VBA supports the following control statements. Click the following links to check their detail." }, { "code": null, "e": 23711, "s": 23601, "text": "Terminates the For loop statement and transfers the execution to the statement immediately following the loop" }, { "code": null, "e": 23821, "s": 23711, "text": "Terminates the Do While statement and transfers the execution to the statement immediately following the loop" }, { "code": null, "e": 24021, "s": 23821, "text": "Strings are a sequence of characters, which can consist of either alphabets, numbers, special characters, or all of them. A variable is said to be a string if it is enclosed within double quotes \" \"." }, { "code": null, "e": 24046, "s": 24021, "text": "variablename = \"string\"\n" }, { "code": null, "e": 24195, "s": 24046, "text": "str1 = \"string\" ' Only Alphabets\nstr2 = \"132.45\" ' Only Numbers\nstr3 = \"!@#$;*\" ' Only Special Characters\nStr4 = \"Asc23@#\" ' Has all the above" }, { "code": null, "e": 24422, "s": 24195, "text": "There are predefined VBA String functions, which help the developers to work with the strings very effectively. Following are String methods that are supported in VBA. Please click on each one of the methods to know in detail." }, { "code": null, "e": 24522, "s": 24422, "text": "Returns the first occurrence of the specified substring. Search happens from the left to the right." }, { "code": null, "e": 24622, "s": 24522, "text": "Returns the first occurrence of the specified substring. Search happens from the right to the left." }, { "code": null, "e": 24670, "s": 24622, "text": "Returns the lower case of the specified string." }, { "code": null, "e": 24718, "s": 24670, "text": "Returns the upper case of the specified string." }, { "code": null, "e": 24792, "s": 24718, "text": "Returns a specific number of characters from the left side of the string." }, { "code": null, "e": 24867, "s": 24792, "text": "Returns a specific number of characters from the right side of the string." }, { "code": null, "e": 24956, "s": 24867, "text": "Returns a specific number of characters from a string based on the specified parameters." }, { "code": null, "e": 25041, "s": 24956, "text": "Returns a string after removing the spaces on the left side of the specified string." }, { "code": null, "e": 25127, "s": 25041, "text": "Returns a string after removing the spaces on the right side of the specified string." }, { "code": null, "e": 25213, "s": 25127, "text": "Returns a string value after removing both the leading and the trailing blank spaces." }, { "code": null, "e": 25253, "s": 25213, "text": "Returns the length of the given string." }, { "code": null, "e": 25316, "s": 25253, "text": "Returns a string after replacing a string with another string." }, { "code": null, "e": 25368, "s": 25316, "text": "Fills a string with the specified number of spaces." }, { "code": null, "e": 25436, "s": 25368, "text": "Returns an integer value after comparing the two specified strings." }, { "code": null, "e": 25511, "s": 25436, "text": "Returns a string with a specified character for specified number of times." }, { "code": null, "e": 25596, "s": 25511, "text": "Returns a string after reversing the sequence of the characters of the given string." }, { "code": null, "e": 25785, "s": 25596, "text": "VBScript Date and Time Functions help the developers to convert date and time from one format to another or to express the date or time value in the format that suits a specific condition." }, { "code": null, "e": 25836, "s": 25785, "text": "A Function, which returns the current system date." }, { "code": null, "e": 25886, "s": 25836, "text": "A Function, which converts a given input to date." }, { "code": null, "e": 25970, "s": 25886, "text": "A Function, which returns a date to which a specified time interval has been added." }, { "code": null, "e": 26036, "s": 25970, "text": "A Function, which returns the difference between two time period." }, { "code": null, "e": 26110, "s": 26036, "text": "A Function, which returns a specified part of the given input date value." }, { "code": null, "e": 26186, "s": 26110, "text": "A Function, which returns a valid date for the given year, month, and date." }, { "code": null, "e": 26255, "s": 26186, "text": "A Function, which formats the date based on the supplied parameters." }, { "code": null, "e": 26346, "s": 26255, "text": "A Function, which returns a Boolean Value whether or not the supplied parameter is a date." }, { "code": null, "e": 26447, "s": 26346, "text": "A Function, which returns an integer between 1 and 31 that represents the day of the specified date." }, { "code": null, "e": 26550, "s": 26447, "text": "A Function, which returns an integer between 1 and 12 that represents the month of the specified date." }, { "code": null, "e": 26635, "s": 26550, "text": "A Function, which returns an integer that represents the year of the specified date." }, { "code": null, "e": 26718, "s": 26635, "text": "A Function, which returns the name of the particular month for the specified date." }, { "code": null, "e": 26822, "s": 26718, "text": "A Function, which returns an integer(1 to 7) that represents the day of the week for the specified day." }, { "code": null, "e": 26888, "s": 26822, "text": "A Function, which returns the weekday name for the specified day." }, { "code": null, "e": 26948, "s": 26888, "text": "A Function, which returns the current system date and time." }, { "code": null, "e": 27051, "s": 26948, "text": "A Function, which returns an integer between 0 and 23 that represents the hour part of the given time." }, { "code": null, "e": 27157, "s": 27051, "text": "A Function, which returns an integer between 0 and 59 that represents the minutes part of the given time." }, { "code": null, "e": 27263, "s": 27157, "text": "A Function, which returns an integer between 0 and 59 that represents the seconds part of the given time." }, { "code": null, "e": 27314, "s": 27263, "text": "A Function, which returns the current system time." }, { "code": null, "e": 27395, "s": 27314, "text": "A Function, which returns the number of seconds and milliseconds since 12:00 AM." }, { "code": null, "e": 27481, "s": 27395, "text": "A Function, which returns the time for the specific input of hour, minute and second." }, { "code": null, "e": 27543, "s": 27481, "text": "A Function, which converts the input string to a time format." }, { "code": null, "e": 27806, "s": 27543, "text": "We know very well that a variable is a container to store a value. Sometimes, developers are in a position to hold more than one value in a single variable at a time. When a series of values are stored in a single variable, then it is known as an array variable." }, { "code": null, "e": 28013, "s": 27806, "text": "Arrays are declared the same way a variable has been declared except that the declaration of an array variable uses parenthesis. In the following example, the size of the array is mentioned in the brackets." }, { "code": null, "e": 28217, "s": 28013, "text": "'Method 1 : Using Dim\nDim arr1()\t'Without Size\n\n'Method 2 : Mentioning the Size\nDim arr2(5) 'Declared with size of 5\n\n'Method 3 : using 'Array' Parameter\nDim arr3\narr3 = Array(\"apple\",\"Orange\",\"Grapes\")" }, { "code": null, "e": 28315, "s": 28217, "text": "Although, the array size is indicated as 5, it can hold 6 values as array index starts from ZERO." }, { "code": null, "e": 28413, "s": 28315, "text": "Although, the array size is indicated as 5, it can hold 6 values as array index starts from ZERO." }, { "code": null, "e": 28445, "s": 28413, "text": "Array Index cannot be negative." }, { "code": null, "e": 28477, "s": 28445, "text": "Array Index cannot be negative." }, { "code": null, "e": 28625, "s": 28477, "text": "VBScript Arrays can store any type of variable in an array. Hence, an array can store an integer, string, or characters in a single array variable." }, { "code": null, "e": 28773, "s": 28625, "text": "VBScript Arrays can store any type of variable in an array. Hence, an array can store an integer, string, or characters in a single array variable." }, { "code": null, "e": 28912, "s": 28773, "text": "The values are assigned to the array by specifying an array index value against each one of the values to be assigned. It can be a string." }, { "code": null, "e": 28957, "s": 28912, "text": "Add a button and add the following function." }, { "code": null, "e": 29559, "s": 28957, "text": "Private Sub Constant_demo_Click()\n Dim arr(5)\n arr(0) = \"1\" 'Number as String\n arr(1) = \"VBScript\" 'String\n arr(2) = 100 \t\t 'Number\n arr(3) = 2.45 \t\t 'Decimal Number\n arr(4) = #10/07/2013# 'Date\n arr(5) = #12.45 PM# 'Time\n \n msgbox(\"Value stored in Array index 0 : \" & arr(0))\n msgbox(\"Value stored in Array index 1 : \" & arr(1))\n msgbox(\"Value stored in Array index 2 : \" & arr(2))\n msgbox(\"Value stored in Array index 3 : \" & arr(3))\n msgbox(\"Value stored in Array index 4 : \" & arr(4))\n msgbox(\"Value stored in Array index 5 : \" & arr(5))\nEnd Sub" }, { "code": null, "e": 29630, "s": 29559, "text": "When you execute the above function, it produces the following output." }, { "code": null, "e": 29865, "s": 29630, "text": "Value stored in Array index 0 : 1\nValue stored in Array index 1 : VBScript\nValue stored in Array index 2 : 100\nValue stored in Array index 3 : 2.45\nValue stored in Array index 4 : 7/10/2013\nValue stored in Array index 5 : 12:45:00 PM\n" }, { "code": null, "e": 30023, "s": 29865, "text": "Arrays are not just limited to a single dimension, however, they can have a maximum of 60 dimensions. Two-dimensional arrays are the most commonly used ones." }, { "code": null, "e": 30114, "s": 30023, "text": "In the following example, a multi-dimensional array is declared with 3 rows and 4 columns." }, { "code": null, "e": 30721, "s": 30114, "text": "Private Sub Constant_demo_Click()\n Dim arr(2,3) as Variant\t' Which has 3 rows and 4 columns\n arr(0,0) = \"Apple\" \n arr(0,1) = \"Orange\"\n arr(0,2) = \"Grapes\" \n arr(0,3) = \"pineapple\" \n arr(1,0) = \"cucumber\" \n arr(1,1) = \"beans\" \n arr(1,2) = \"carrot\" \n arr(1,3) = \"tomato\" \n arr(2,0) = \"potato\" \n arr(2,1) = \"sandwitch\" \n arr(2,2) = \"coffee\" \n arr(2,3) = \"nuts\" \n \n msgbox(\"Value in Array index 0,1 : \" & arr(0,1))\n msgbox(\"Value in Array index 2,2 : \" & arr(2,2))\nEnd Sub" }, { "code": null, "e": 30792, "s": 30721, "text": "When you execute the above function, it produces the following output." }, { "code": null, "e": 30883, "s": 30792, "text": "Value stored in Array index : 0 , 1 : Orange\nValue stored in Array index : 2 , 2 : coffee\n" }, { "code": null, "e": 30984, "s": 30883, "text": "ReDim statement is used to declare dynamic-array variables and allocate or reallocate storage space." }, { "code": null, "e": 31046, "s": 30984, "text": "ReDim [Preserve] varname(subscripts) [, varname(subscripts)]\n" }, { "code": null, "e": 31174, "s": 31046, "text": "Preserve − An optional parameter used to preserve the data in an existing array when you change the size of the last dimension." }, { "code": null, "e": 31302, "s": 31174, "text": "Preserve − An optional parameter used to preserve the data in an existing array when you change the size of the last dimension." }, { "code": null, "e": 31436, "s": 31302, "text": "Varname − A required parameter, which denotes the name of the variable, which should follow the standard variable naming conventions." }, { "code": null, "e": 31570, "s": 31436, "text": "Varname − A required parameter, which denotes the name of the variable, which should follow the standard variable naming conventions." }, { "code": null, "e": 31644, "s": 31570, "text": "Subscripts − A required parameter, which indicates the size of the array." }, { "code": null, "e": 31718, "s": 31644, "text": "Subscripts − A required parameter, which indicates the size of the array." }, { "code": null, "e": 31850, "s": 31718, "text": "In the following example, an array has been redefined and then the values preserved when the existing size of the array is changed." }, { "code": null, "e": 31962, "s": 31850, "text": "Note − Upon resizing an array smaller than it was originally, the data in the eliminated elements will be lost." }, { "code": null, "e": 32237, "s": 31962, "text": "Private Sub Constant_demo_Click()\n Dim a() as variant\n i = 0\n redim a(5)\n a(0) = \"XYZ\"\n a(1) = 41.25\n a(2) = 22\n \n REDIM PRESERVE a(7)\n For i = 3 to 7\n a(i) = i\n Next\n \n 'to Fetch the output\n For i = 0 to ubound(a)\n Msgbox a(i)\n Next\nEnd Sub" }, { "code": null, "e": 32308, "s": 32237, "text": "When you execute the above function, it produces the following output." }, { "code": null, "e": 32332, "s": 32308, "text": "XYZ\n41.25\n22\n3\n4\n5\n6\n7\n" }, { "code": null, "e": 32575, "s": 32332, "text": "There are various inbuilt functions within VBScript which help the developers to handle arrays effectively. All the methods that are used in conjunction with arrays are listed below. Please click on the method name to know about it in detail." }, { "code": null, "e": 32676, "s": 32575, "text": "A Function, which returns an integer that corresponds to the smallest subscript of the given arrays." }, { "code": null, "e": 32776, "s": 32676, "text": "A Function, which returns an integer that corresponds to the largest subscript of the given arrays." }, { "code": null, "e": 32883, "s": 32776, "text": "A Function, which returns an array that contains a specified number of values. Split based on a delimiter." }, { "code": null, "e": 33030, "s": 32883, "text": "A Function, which returns a string that contains a specified number of substrings in an array. This is an exact opposite function of Split Method." }, { "code": null, "e": 33153, "s": 33030, "text": "A Function, which returns a zero based array that contains a subset of a string array based on a specific filter criteria." }, { "code": null, "e": 33257, "s": 33153, "text": "A Function, which returns a boolean value that indicates whether or not the input variable is an array." }, { "code": null, "e": 33330, "s": 33257, "text": "A Function, which recovers the allocated memory for the array variables." }, { "code": null, "e": 33588, "s": 33330, "text": "A function is a group of reusable code which can be called anywhere in your program. This eliminates the need of writing the same code over and over again. This enables the programmers to divide a big program into a number of small and manageable functions." }, { "code": null, "e": 33742, "s": 33588, "text": "Apart from inbuilt functions, VBA allows to write user-defined functions as well. In this chapter, you will learn how to write your own functions in VBA." }, { "code": null, "e": 33860, "s": 33742, "text": "A VBA function can have an optional return statement. This is required if you want to return a value from a function." }, { "code": null, "e": 34010, "s": 33860, "text": "For example, you can pass two numbers in a function and then you can expect from the function to return their multiplication in your calling program." }, { "code": null, "e": 34126, "s": 34010, "text": "Note − A function can return multiple values separated by a comma as an array assigned to the function name itself." }, { "code": null, "e": 34477, "s": 34126, "text": "Before we use a function, we need to define that particular function. The most common way to define a function in VBA is by using the Function keyword, followed by a unique function name and it may or may not carry a list of parameters and a statement with End Function keyword, which indicates the end of the function. Following is the basic syntax." }, { "code": null, "e": 34522, "s": 34477, "text": "Add a button and add the following function." }, { "code": null, "e": 34645, "s": 34522, "text": "Function Functionname(parameter-list)\n statement 1\n statement 2\n statement 3\n .......\n statement n\nEnd Function\n" }, { "code": null, "e": 34768, "s": 34645, "text": "Add the following function which returns the area. Note that a value/values can be returned with the function name itself." }, { "code": null, "e": 34955, "s": 34768, "text": "Function findArea(Length As Double, Optional Width As Variant)\n If IsMissing(Width) Then\n findArea = Length * Length\n Else\n findArea = Length * Width\n End If\nEnd Function" }, { "code": null, "e": 35058, "s": 34955, "text": "To invoke a function, call the function using the function name as shown in the following screenshot. " }, { "code": null, "e": 35127, "s": 35058, "text": "The output of the area as shown below will be displayed to the user." }, { "code": null, "e": 35205, "s": 35127, "text": "Sub Procedures are similar to functions, however there are a few differences." }, { "code": null, "e": 35289, "s": 35205, "text": "Sub procedures DO NOT Return a value while functions may or may not return a value." }, { "code": null, "e": 35373, "s": 35289, "text": "Sub procedures DO NOT Return a value while functions may or may not return a value." }, { "code": null, "e": 35426, "s": 35373, "text": "Sub procedures CAN be called without a call keyword." }, { "code": null, "e": 35479, "s": 35426, "text": "Sub procedures CAN be called without a call keyword." }, { "code": null, "e": 35549, "s": 35479, "text": "Sub procedures are always enclosed within Sub and End Sub statements." }, { "code": null, "e": 35619, "s": 35549, "text": "Sub procedures are always enclosed within Sub and End Sub statements." }, { "code": null, "e": 35678, "s": 35619, "text": "Sub Area(x As Double, y As Double)\n MsgBox x * y\nEnd Sub" }, { "code": null, "e": 35866, "s": 35678, "text": "To invoke a Procedure somewhere in the script, you can make a call from a function. We will not be able to use the same way as that of a function as sub procedure WILL NOT return a value." }, { "code": null, "e": 36004, "s": 35866, "text": "Function findArea(Length As Double, Width As Variant)\n area Length, Width ' To Calculate Area 'area' sub proc is called\nEnd Function" }, { "code": null, "e": 36115, "s": 36004, "text": "Now you will be able to call the function only but not the sub procedure as shown in the following screenshot." }, { "code": null, "e": 36173, "s": 36115, "text": "The area is calculated and shown only in the Message box." }, { "code": null, "e": 36341, "s": 36173, "text": "The result cell displays ZERO as the area value is NOT returned from the function. In short, you cannot make a direct call to a sub procedure from the excel worksheet." }, { "code": null, "e": 36572, "s": 36341, "text": "VBA, an event-driven programming can be triggered when you change a cell or range of cell values manually. Change event may make things easier, but you can very quickly end a page full of formatting. There are two kinds of events." }, { "code": null, "e": 36589, "s": 36572, "text": "Worksheet Events" }, { "code": null, "e": 36605, "s": 36589, "text": "Workbook Events" }, { "code": null, "e": 36790, "s": 36605, "text": "Worksheet Events are triggered when there is a change in the worksheet. It is created by performing a right-click on the sheet tab and choosing 'view code', and later pasting the code." }, { "code": null, "e": 36932, "s": 36790, "text": "The user can select each one of those worksheets and choose \"WorkSheet\" from the drop down to get the list of all supported Worksheet events." }, { "code": null, "e": 37008, "s": 36932, "text": "Following are the supported worksheet events that can be added by the user." }, { "code": null, "e": 37461, "s": 37008, "text": "Private Sub Worksheet_Activate() \nPrivate Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean) \nPrivate Sub Worksheet_BeforeRightClick(ByVal Target As Range, Cancel As Boolean) \nPrivate Sub Worksheet_Calculate() \nPrivate Sub Worksheet_Change(ByVal Target As Range) \nPrivate Sub Worksheet_Deactivate() \nPrivate Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink) \nPrivate Sub Worksheet_SelectionChange(ByVal Target As Range)" }, { "code": null, "e": 37528, "s": 37461, "text": "Let us say, we just need to display a message before double click." }, { "code": null, "e": 37650, "s": 37528, "text": "Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)\n MsgBox \"Before Double Click\"\nEnd Sub" }, { "code": null, "e": 37763, "s": 37650, "text": "Upon double-clicking on any cell, the message box is displayed to the user as shown in the following screenshot." }, { "code": null, "e": 38101, "s": 37763, "text": "Workbook events are triggered when there is a change in the workbook on the whole. We can add the code for workbook events by selecting the 'ThisWorkbook' and selecting 'workbook' from the dropdown as shown in the following screenshot. Immediately Workbook_open sub procedure is displayed to the user as seen in the following screenshot." }, { "code": null, "e": 38176, "s": 38101, "text": "Following are the supported Workbook events that can be added by the user." }, { "code": null, "e": 39322, "s": 38176, "text": "Private Sub Workbook_AddinUninstall() \nPrivate Sub Workbook_BeforeClose(Cancel As Boolean) \nPrivate Sub Workbook_BeforePrint(Cancel As Boolean) \nPrivate Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean) \nPrivate Sub Workbook_Deactivate() \nPrivate Sub Workbook_NewSheet(ByVal Sh As Object) \nPrivate Sub Workbook_Open() \nPrivate Sub Workbook_SheetActivate(ByVal Sh As Object) \nPrivate Sub Workbook_SheetBeforeDoubleClick(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean) \nPrivate Sub Workbook_SheetBeforeRightClick(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean) \nPrivate Sub Workbook_SheetCalculate(ByVal Sh As Object) \nPrivate Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range) \nPrivate Sub Workbook_SheetDeactivate(ByVal Sh As Object) \nPrivate Sub Workbook_SheetFollowHyperlink(ByVal Sh As Object, ByVal Target As Hyperlink) \nPrivate Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range) \nPrivate Sub Workbook_WindowActivate(ByVal Wn As Window) \nPrivate Sub Workbook_WindowDeactivate(ByVal Wn As Window) \nPrivate Sub Workbook_WindowResize(ByVal Wn As Window)" }, { "code": null, "e": 39455, "s": 39322, "text": "Let us say, we just need to display a message to the user that a new sheet is created successfully, whenever a new sheet is created." }, { "code": null, "e": 39556, "s": 39455, "text": "Private Sub Workbook_NewSheet(ByVal Sh As Object)\n MsgBox \"New Sheet Created Successfully\"\nEnd Sub" }, { "code": null, "e": 39662, "s": 39556, "text": "Upon creating a new excel sheet, a message is displayed to the user as shown in the following screenshot." }, { "code": null, "e": 39773, "s": 39662, "text": "There are three types of errors in programming: (a) Syntax Errors, (b) Runtime Errors, and (c) Logical Errors." }, { "code": null, "e": 39965, "s": 39773, "text": "Syntax errors, also called as parsing errors, occur at the interpretation time for VBScript. For example, the following line causes a syntax error because it is missing a closing parenthesis." }, { "code": null, "e": 40058, "s": 39965, "text": "Function ErrorHanlding_Demo()\n dim x,y\n x = \"Tutorialspoint\"\n y = Ucase(x\nEnd Function" }, { "code": null, "e": 40144, "s": 40058, "text": "Runtime errors, also called exceptions, occur during execution, after interpretation." }, { "code": null, "e": 40316, "s": 40144, "text": "For example, the following line causes a runtime error because here the syntax is correct but at runtime it is trying to call fnmultiply, which is a non-existing function." }, { "code": null, "e": 40483, "s": 40316, "text": "Function ErrorHanlding_Demo1()\n Dim x,y\n x = 10\n y = 20\n z = fnadd(x,y)\n a = fnmultiply(x,y)\nEnd Function\n\nFunction fnadd(x,y)\n fnadd = x + y\nEnd Function" }, { "code": null, "e": 40741, "s": 40483, "text": "Logical errors can be the most difficult type of errors to track down. These errors are not the result of a syntax or runtime error. Instead, they occur when you make a mistake in the logic that drives your script and you do not get the result you expected." }, { "code": null, "e": 40872, "s": 40741, "text": "You cannot catch those errors, because it depends on your business requirement what type of logic you want to put in your program." }, { "code": null, "e": 40972, "s": 40872, "text": "For example, dividing a number by zero or a script that is written which enters into infinite loop." }, { "code": null, "e": 41141, "s": 40972, "text": "Assume if we have a runtime error, then the execution stops by displaying the error message. As a developer, if we want to capture the error, then Error Object is used." }, { "code": null, "e": 41250, "s": 41141, "text": "In the following example, Err.Number gives the error number and Err.Description gives the error description." }, { "code": null, "e": 41383, "s": 41250, "text": "Err.Raise 6 ' Raise an overflow error.\nMsgBox \"Error # \" & CStr(Err.Number) & \" \" & Err.Description\nErr.Clear ' Clear the error." }, { "code": null, "e": 41617, "s": 41383, "text": "VBA enables an error-handling routine and can also be used to disable an error-handling routine. Without an On Error statement, any run-time error that occurs is fatal: an error message is displayed, and the execution stops abruptly." }, { "code": null, "e": 41668, "s": 41617, "text": "On Error { GoTo [ line | 0 | -1 ] | Resume Next }\n" }, { "code": null, "e": 41678, "s": 41668, "text": "GoTo line" }, { "code": null, "e": 41890, "s": 41678, "text": "Enables the error-handling routine that starts at the line specified in the required line argument. The specified line must be in the same procedure as the On Error statement, or a compile-time error will occur." }, { "code": null, "e": 41897, "s": 41890, "text": "GoTo 0" }, { "code": null, "e": 41983, "s": 41897, "text": "Disables the enabled error handler in the current procedure and resets it to Nothing." }, { "code": null, "e": 41991, "s": 41983, "text": "GoTo -1" }, { "code": null, "e": 42073, "s": 41991, "text": "Disables the enabled exception in the current procedure and resets it to Nothing." }, { "code": null, "e": 42085, "s": 42073, "text": "Resume Next" }, { "code": null, "e": 42271, "s": 42085, "text": "Specifies that when a run-time error occurs, the control goes to the statement immediately following the statement where the error occurred, and the execution continues from that point." }, { "code": null, "e": 42780, "s": 42271, "text": "Public Sub OnErrorDemo()\n On Error GoTo ErrorHandler ' Enable error-handling routine.\n Dim x, y, z As Integer\n x = 50\n y = 0\n z = x / y ' Divide by ZERO Error Raises\n \n ErrorHandler: ' Error-handling routine.\n Select Case Err.Number ' Evaluate error number.\n Case 10 ' Divide by zero error\n MsgBox (\"You attempted to divide by zero!\")\n Case Else\n MsgBox \"UNKNOWN ERROR - Error# \" & Err.Number & \" : \" & Err.Description\n End Select\n Resume Next\nEnd Sub" }, { "code": null, "e": 42875, "s": 42780, "text": "When programming using VBA, there are few important objects that a user would be dealing with." }, { "code": null, "e": 42895, "s": 42875, "text": "Application Objects" }, { "code": null, "e": 42912, "s": 42895, "text": "Workbook Objects" }, { "code": null, "e": 42930, "s": 42912, "text": "Worksheet Objects" }, { "code": null, "e": 42944, "s": 42930, "text": "Range Objects" }, { "code": null, "e": 42995, "s": 42944, "text": "The Application object consists of the following −" }, { "code": null, "e": 43034, "s": 42995, "text": "Application-wide settings and options." }, { "code": null, "e": 43117, "s": 43034, "text": "Methods that return top-level objects, such as ActiveCell, ActiveSheet, and so on." }, { "code": null, "e": 43326, "s": 43117, "text": "'Example 1 :\nSet xlapp = CreateObject(\"Excel.Sheet\") \nxlapp.Application.Workbooks.Open \"C:\\test.xls\"\n\n'Example 2 :\nApplication.Windows(\"test.xls\").Activate\n\n'Example 3:\nApplication.ActiveCell.Font.Bold = True" }, { "code": null, "e": 43459, "s": 43326, "text": "The Workbook object is a member of the Workbooks collection and contains all the Workbook objects currently open in Microsoft Excel." }, { "code": null, "e": 43715, "s": 43459, "text": "'Ex 1 : To close Workbooks\nWorkbooks.Close\n\n'Ex 2 : To Add an Empty Work Book\nWorkbooks.Add\n\n'Ex 3: To Open a Workbook\nWorkbooks.Open FileName:=\"Test.xls\", ReadOnly:=True\n\n'Ex : 4 - To Activate WorkBooks\nWorkbooks(\"Test.xls\").Worksheets(\"Sheet1\").Activate" }, { "code": null, "e": 43831, "s": 43715, "text": "The Worksheet object is a member of the Worksheets collection and contains all the Worksheet objects in a workbook." }, { "code": null, "e": 43991, "s": 43831, "text": "'Ex 1 : To make it Invisible\nWorksheets(1).Visible = False\n\n'Ex 2 : To protect an WorkSheet\nWorksheets(\"Sheet1\").Protect password:=strPassword, scenarios:=True" }, { "code": null, "e": 44115, "s": 43991, "text": "Range Objects represent a cell, a row, a column, or a selection of cells containing one or more continuous blocks of cells." }, { "code": null, "e": 44289, "s": 44115, "text": "'Ex 1 : To Put a value in the cell A5\nWorksheets(\"Sheet1\").Range(\"A5\").Value = \"5235\"\n\n'Ex 2 : To put a value in range of Cells\nWorksheets(\"Sheet1\").Range(\"A1:A4\").Value = 5" }, { "code": null, "e": 44446, "s": 44289, "text": "You can also read Excel File and write the contents of the cell into a Text File using VBA. VBA allows the users to work with text files using two methods −" }, { "code": null, "e": 44465, "s": 44446, "text": "File System Object" }, { "code": null, "e": 44485, "s": 44465, "text": "using Write Command" }, { "code": null, "e": 44624, "s": 44485, "text": "As the name suggests, FSOs help the developers to work with drives, folders, and files. In this section, we will discuss how to use a FSO." }, { "code": null, "e": 44630, "s": 44624, "text": "Drive" }, { "code": null, "e": 44757, "s": 44630, "text": "Drive is an Object. Contains methods and properties that allow you to gather information about a drive attached to the system." }, { "code": null, "e": 44764, "s": 44757, "text": "Drives" }, { "code": null, "e": 44877, "s": 44764, "text": "Drives is a Collection. It provides a list of the drives attached to the system, either physically or logically." }, { "code": null, "e": 44882, "s": 44877, "text": "File" }, { "code": null, "e": 44993, "s": 44882, "text": "File is an Object. It contains methods and properties that allow developers to create, delete, or move a file." }, { "code": null, "e": 44999, "s": 44993, "text": "Files" }, { "code": null, "e": 45085, "s": 44999, "text": "Files is a Collection. It provides a list of all the files contained within a folder." }, { "code": null, "e": 45092, "s": 45085, "text": "Folder" }, { "code": null, "e": 45210, "s": 45092, "text": "Folder is an Object. It provides methods and properties that allow the developers to create, delete, or move folders." }, { "code": null, "e": 45218, "s": 45210, "text": "Folders" }, { "code": null, "e": 45298, "s": 45218, "text": "Folders is a Collection. It provides a list of all the folders within a folder." }, { "code": null, "e": 45309, "s": 45298, "text": "TextStream" }, { "code": null, "e": 45390, "s": 45309, "text": "TextStream is an Object. It enables the developers to read and write text files." }, { "code": null, "e": 45548, "s": 45390, "text": "Drive is an object, which provides access to the properties of a particular disk drive or network share. Following properties are supported by Drive object −" }, { "code": null, "e": 45563, "s": 45548, "text": "AvailableSpace" }, { "code": null, "e": 45575, "s": 45563, "text": "DriveLetter" }, { "code": null, "e": 45585, "s": 45575, "text": "DriveType" }, { "code": null, "e": 45596, "s": 45585, "text": "FileSystem" }, { "code": null, "e": 45606, "s": 45596, "text": "FreeSpace" }, { "code": null, "e": 45614, "s": 45606, "text": "IsReady" }, { "code": null, "e": 45619, "s": 45614, "text": "Path" }, { "code": null, "e": 45630, "s": 45619, "text": "RootFolder" }, { "code": null, "e": 45643, "s": 45630, "text": "SerialNumber" }, { "code": null, "e": 45653, "s": 45643, "text": "ShareName" }, { "code": null, "e": 45663, "s": 45653, "text": "TotalSize" }, { "code": null, "e": 45674, "s": 45663, "text": "VolumeName" }, { "code": null, "e": 45856, "s": 45674, "text": "Step 1 − Before proceeding to scripting using FSO, we should enable Microsoft Scripting Runtime. To do the same, navigate to Tools → References as shown in the following screenshot." }, { "code": null, "e": 45913, "s": 45856, "text": "Step 2 − Add \"Microsoft Scripting RunTime\" and Click OK." }, { "code": null, "e": 46001, "s": 45913, "text": "Step 3 − Add Data that you would like to write in a Text File and add a Command Button." }, { "code": null, "e": 46036, "s": 46001, "text": "Step 4 − Now it is time to Script." }, { "code": null, "e": 46748, "s": 46036, "text": "Private Sub fn_write_to_text_Click()\n Dim FilePath As String\n Dim CellData As String\n Dim LastCol As Long\n Dim LastRow As Long\n \n Dim fso As FileSystemObject\n Set fso = New FileSystemObject\n Dim stream As TextStream\n \n LastCol = ActiveSheet.UsedRange.Columns.Count\n LastRow = ActiveSheet.UsedRange.Rows.Count\n \n ' Create a TextStream.\n Set stream = fso.OpenTextFile(\"D:\\Try\\Support.log\", ForWriting, True)\n \n CellData = \"\"\n \n For i = 1 To LastRow\n For j = 1 To LastCol\n CellData = Trim(ActiveCell(i, j).Value)\n stream.WriteLine \"The Value at location (\" & i & \",\" & j & \")\" & CellData\n Next j\n Next i\n \n stream.Close\n MsgBox (\"Job Done\")\nEnd Sub" }, { "code": null, "e": 46929, "s": 46748, "text": "When executing the script, ensure that you place the cursor in the first cell of the worksheet. The Support.log file is created as shown in the following screenshot under \"D:\\Try\"." }, { "code": null, "e": 46993, "s": 46929, "text": "The Contents of the file are shown in the following screenshot." }, { "code": null, "e": 47163, "s": 46993, "text": "Unlike FSO, we need NOT add any references, however, we will NOT be able to work with drives, files and folders. We will be able to just add the stream to the text file." }, { "code": null, "e": 47733, "s": 47163, "text": "Private Sub fn_write_to_text_Click()\n Dim FilePath As String\n Dim CellData As String\n Dim LastCol As Long\n Dim LastRow As Long\n \n LastCol = ActiveSheet.UsedRange.Columns.Count\n LastRow = ActiveSheet.UsedRange.Rows.Count\n \n FilePath = \"D:\\Try\\write.txt\"\n Open FilePath For Output As #2\n \n CellData = \"\"\n For i = 1 To LastRow\n For j = 1 To LastCol\n CellData = \"The Value at location (\" & i & \",\" & j & \")\" & Trim(ActiveCell(i, j).Value)\n Write #2, CellData\n Next j\n Next i\n \n Close #2\n MsgBox (\"Job Done\")\nEnd Sub" }, { "code": null, "e": 47855, "s": 47733, "text": "Upon executing the script, the \"write.txt\" file is created in the location \"D:\\Try\" as shown in the following screenshot." }, { "code": null, "e": 47919, "s": 47855, "text": "The contents of the file are shown in the following screenshot." }, { "code": null, "e": 48024, "s": 47919, "text": "Using VBA, you can generate charts based on certain criteria. Let us take a look at it using an example." }, { "code": null, "e": 48093, "s": 48024, "text": "Step 1 − Enter the data against which the graph has to be generated." }, { "code": null, "e": 48223, "s": 48093, "text": "Step 2 − Create 3 buttons - one to generate a bar graph, another to generate a pie chart, and another to generate a column chart." }, { "code": null, "e": 48294, "s": 48223, "text": "Step 3 − Develop a Macro to generate each one of these type of charts." }, { "code": null, "e": 48896, "s": 48294, "text": "' Procedure to Generate Pie Chart\nPrivate Sub fn_generate_pie_graph_Click()\n Dim cht As ChartObject\n For Each cht In Worksheets(1).ChartObjects\n cht.Chart.Type = xlPie\n Next cht\nEnd Sub\n\n' Procedure to Generate Bar Graph\nPrivate Sub fn_Generate_Bar_Graph_Click()\n Dim cht As ChartObject\n For Each cht In Worksheets(1).ChartObjects\n cht.Chart.Type = xlBar\n Next cht\nEnd Sub\n\n' Procedure to Generate Column Graph\nPrivate Sub fn_generate_column_graph_Click()\n Dim cht As ChartObject\n For Each cht In Worksheets(1).ChartObjects\n cht.Chart.Type = xlColumn\n Next cht\nEnd Sub" }, { "code": null, "e": 49028, "s": 48896, "text": "Step 4 − Upon clicking the corresponding button, the chart is created. In the following output, click on generate Pie Chart button." }, { "code": null, "e": 49229, "s": 49028, "text": "A User Form is a custom-built dialog box that makes a user data entry more controllable and easier to use for the user. In this chapter, you will learn to design a simple form and add data into excel." }, { "code": null, "e": 49416, "s": 49229, "text": "Step 1 − Navigate to VBA Window by pressing Alt+F11 and Navigate to \"Insert\" Menu and select \"User Form\". Upon selecting, the user form is displayed as shown in the following screenshot." }, { "code": null, "e": 49468, "s": 49416, "text": "Step 2 − Design the forms using the given controls." }, { "code": null, "e": 49689, "s": 49468, "text": "Step 3 − After adding each control, the controls have to be named. Caption corresponds to what appears on the form and name corresponds to the logical name that will be appearing when you write VBA code for that element." }, { "code": null, "e": 49762, "s": 49689, "text": "Step 4 − Following are the names against each one of the added controls." }, { "code": null, "e": 49875, "s": 49762, "text": "Step 5 − Add the code for the form load event by performing a right-click on the form and selecting 'View Code'." }, { "code": null, "e": 49998, "s": 49875, "text": "Step 6 − Select ‘Userform’ from the objects drop-down and select 'Initialize' method as shown in the following screenshot." }, { "code": null, "e": 50126, "s": 49998, "text": "Step 7 − Upon Loading the form, ensure that the text boxes are cleared, drop-down boxes are filled and Radio buttons are reset." }, { "code": null, "e": 52459, "s": 50126, "text": "Private Sub UserForm_Initialize()\n 'Empty Emp ID Text box and Set the Cursor \n txtempid.Value = \"\"\n txtempid.SetFocus\n \n 'Empty all other text box fields\n txtfirstname.Value = \"\"\n txtlastname.Value = \"\"\n txtemailid.Value = \"\"\n \n 'Clear All Date of Birth Related Fields\n cmbdate.Clear\n cmbmonth.Clear\n cmbyear.Clear\n \n 'Fill Date Drop Down box - Takes 1 to 31\n With cmbdate\n .AddItem \"1\"\n .AddItem \"2\"\n .AddItem \"3\"\n .AddItem \"4\"\n .AddItem \"5\"\n .AddItem \"6\"\n .AddItem \"7\"\n .AddItem \"8\"\n .AddItem \"9\"\n .AddItem \"10\"\n .AddItem \"11\"\n .AddItem \"12\"\n .AddItem \"13\"\n .AddItem \"14\"\n .AddItem \"15\"\n .AddItem \"16\"\n .AddItem \"17\"\n .AddItem \"18\"\n .AddItem \"19\"\n .AddItem \"20\"\n .AddItem \"21\"\n .AddItem \"22\"\n .AddItem \"23\"\n .AddItem \"24\"\n .AddItem \"25\"\n .AddItem \"26\"\n .AddItem \"27\"\n .AddItem \"28\"\n .AddItem \"29\"\n .AddItem \"30\"\n .AddItem \"31\"\n End With\n \n 'Fill Month Drop Down box - Takes Jan to Dec\n With cmbmonth\n .AddItem \"JAN\"\n .AddItem \"FEB\"\n .AddItem \"MAR\"\n .AddItem \"APR\"\n .AddItem \"MAY\"\n .AddItem \"JUN\"\n .AddItem \"JUL\"\n .AddItem \"AUG\"\n .AddItem \"SEP\"\n .AddItem \"OCT\"\n .AddItem \"NOV\"\n .AddItem \"DEC\"\n End With\n \n 'Fill Year Drop Down box - Takes 1980 to 2014\n With cmbyear\n .AddItem \"1980\"\n .AddItem \"1981\"\n .AddItem \"1982\"\n .AddItem \"1983\"\n .AddItem \"1984\"\n .AddItem \"1985\"\n .AddItem \"1986\"\n .AddItem \"1987\"\n .AddItem \"1988\"\n .AddItem \"1989\"\n .AddItem \"1990\"\n .AddItem \"1991\"\n .AddItem \"1992\"\n .AddItem \"1993\"\n .AddItem \"1994\"\n .AddItem \"1995\"\n .AddItem \"1996\"\n .AddItem \"1997\"\n .AddItem \"1998\"\n .AddItem \"1999\"\n .AddItem \"2000\"\n .AddItem \"2001\"\n .AddItem \"2002\"\n .AddItem \"2003\"\n .AddItem \"2004\"\n .AddItem \"2005\"\n .AddItem \"2006\"\n .AddItem \"2007\"\n .AddItem \"2008\"\n .AddItem \"2009\"\n .AddItem \"2010\"\n .AddItem \"2011\"\n .AddItem \"2012\"\n .AddItem \"2013\"\n .AddItem \"2014\"\n End With\n \n 'Reset Radio Button. Set it to False when form loads.\n radioyes.Value = False\n radiono.Value = False\n\nEnd Sub" }, { "code": null, "e": 52602, "s": 52459, "text": "Step 8 − Now add the code to the Submit button. Upon clicking the submit button, the user should be able to add the values into the worksheet." }, { "code": null, "e": 53229, "s": 52602, "text": "Private Sub btnsubmit_Click()\n Dim emptyRow As Long\n \n 'Make Sheet1 active\n Sheet1.Activate\n \n 'Determine emptyRow\n emptyRow = WorksheetFunction.CountA(Range(\"A:A\")) + 1\n \n 'Transfer information\n Cells(emptyRow, 1).Value = txtempid.Value\n Cells(emptyRow, 2).Value = txtfirstname.Value\n Cells(emptyRow, 3).Value = txtlastname.Value\n Cells(emptyRow, 4).Value = cmbdate.Value & \"/\" & cmbmonth.Value & \"/\" & cmbyear.Value\n Cells(emptyRow, 5).Value = txtemailid.Value\n \n If radioyes.Value = True Then\n Cells(emptyRow, 6).Value = \"Yes\"\n Else\n Cells(emptyRow, 6).Value = \"No\"\n End If\nEnd Sub" }, { "code": null, "e": 53309, "s": 53229, "text": "Step 9 − Add a method to close the form when the user clicks the Cancel button." }, { "code": null, "e": 53360, "s": 53309, "text": "Private Sub btncancel_Click()\n Unload Me\nEnd Sub" }, { "code": null, "e": 53571, "s": 53360, "text": "Step 10 − Execute the form by clicking the \"Run\" button. Enter the values into the form and click the 'Submit' button. Automatically the values will flow into the worksheet as shown in the following screenshot." }, { "code": null, "e": 53605, "s": 53571, "text": "\n 101 Lectures \n 6 hours \n" }, { "code": null, "e": 53620, "s": 53605, "text": " Pavan Lalwani" }, { "code": null, "e": 53653, "s": 53620, "text": "\n 41 Lectures \n 3 hours \n" }, { "code": null, "e": 53668, "s": 53653, "text": " Arnold Higuit" }, { "code": null, "e": 53703, "s": 53668, "text": "\n 80 Lectures \n 5.5 hours \n" }, { "code": null, "e": 53721, "s": 53703, "text": " Prashant Panchal" }, { "code": null, "e": 53754, "s": 53721, "text": "\n 25 Lectures \n 2 hours \n" }, { "code": null, "e": 53772, "s": 53754, "text": " Prashant Panchal" }, { "code": null, "e": 53805, "s": 53772, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 53820, "s": 53805, "text": " Arnold Higuit" }, { "code": null, "e": 53856, "s": 53820, "text": "\n 92 Lectures \n 10.5 hours \n" }, { "code": null, "e": 53884, "s": 53856, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 53891, "s": 53884, "text": " Print" }, { "code": null, "e": 53902, "s": 53891, "text": " Add Notes" } ]
Checking triangular inequality on list of lists in Python
The sum of two sides of a triangle is always greater than the third side. This is called triangle inequality. Python list of lists we will identify those sublists where the triangle inequality holds good. We will first get all the sublists sorted. Then for each sublist we will check if the if the sum of first two elements is greater than the third element. Live Demo Alist = [[3, 8, 3], [9, 8, 6]] # Sorting sublist of list of list for x in Alist: x.sort() # Check for triangular inequality for e in Alist: if e[0] + e[1] > e[2]: print("The sublist showing triangular inequality:",x) Running the above code gives us the following result − The sublist showing triangular inequality: [6, 8, 9] In this method, we also first sort the sublists and then use list comprehension to go through each of the sublists to check which one satisfies the triangle inequality. Alist = [[3, 8, 3], [9, 8, 6]] # Sorting sublist of list of list for x in Alist: x.sort() # Check for triangular inequality if[(x, y, z) for x, y, z in Alist if (x + y) >= z]: print("The sublist showing triangular inequality: \n",x) Running the above code gives us the following result − The sublist showing triangular inequality: [6, 8, 9]
[ { "code": null, "e": 1267, "s": 1062, "text": "The sum of two sides of a triangle is always greater than the third side. This is called triangle inequality. Python list of lists we will identify those sublists where the triangle inequality holds good." }, { "code": null, "e": 1421, "s": 1267, "text": "We will first get all the sublists sorted. Then for each sublist we will check if the if the sum of first two elements is greater than the third element." }, { "code": null, "e": 1432, "s": 1421, "text": " Live Demo" }, { "code": null, "e": 1661, "s": 1432, "text": "Alist = [[3, 8, 3], [9, 8, 6]]\n# Sorting sublist of list of list\nfor x in Alist:\n x.sort()\n# Check for triangular inequality\nfor e in Alist:\n if e[0] + e[1] > e[2]:\n print(\"The sublist showing triangular inequality:\",x)" }, { "code": null, "e": 1716, "s": 1661, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1769, "s": 1716, "text": "The sublist showing triangular inequality:\n[6, 8, 9]" }, { "code": null, "e": 1938, "s": 1769, "text": "In this method, we also first sort the sublists and then use list comprehension to go through each of the sublists to check which one satisfies the triangle inequality." }, { "code": null, "e": 2183, "s": 1938, "text": "Alist = [[3, 8, 3], [9, 8, 6]]\n# Sorting sublist of list of list\nfor x in Alist:\n x.sort()\n# Check for triangular inequality\n if[(x, y, z) for x, y, z in Alist if (x + y) >= z]:\n print(\"The sublist showing triangular inequality: \\n\",x)" }, { "code": null, "e": 2238, "s": 2183, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2291, "s": 2238, "text": "The sublist showing triangular inequality:\n[6, 8, 9]" } ]
How to change the Node.js module wrapper ? - GeeksforGeeks
07 Oct, 2021 Module Wrapper Function: Under the hood, NodeJS does not run our code directly, it wraps the entire code inside a function before execution. This function is termed as Module Wrapper Function. Refer https://nodejs.org/api/modules.html#modules_the_module_wrapper for official documentation. Before a module’s code is executed, NodeJS wraps it with a function wrapper that has the following structure: (function (exports, require, module, __filename, __dirname) { //module code }); Use of Module Wrapper Function in NodeJS: The top-level variables declared with var, const, or let are scoped to the module rather than to the global object.It provides some global-looking variables that are specific to the module, such as:The module and exports object that can be used to export values from the module.The variables like __filename and __dirname, that tells us the module’s absolute filename and its directory path. The top-level variables declared with var, const, or let are scoped to the module rather than to the global object. It provides some global-looking variables that are specific to the module, such as:The module and exports object that can be used to export values from the module.The variables like __filename and __dirname, that tells us the module’s absolute filename and its directory path. The module and exports object that can be used to export values from the module. The variables like __filename and __dirname, that tells us the module’s absolute filename and its directory path. Modifying Module Wrapper Function: Consider that we have two files, main.js and module.js. In main.js we overwrite the Module.wrap function in order to console.log(‘modifedMWF’); every time a module is required. Now if we require module.js, it contains a message to confirm whether our modifications are successful or not. This is the first file which will call second.main.jsmain.jsvar Module = require("module"); (function (moduleWrapCopy) { Module.wrap = function (script) { script = "console.log('modifiedMWF');" + script; return moduleWrapCopy(script); };})(Module.wrap); require("./module.js");This is the second file.module.jsmodule.jsconsole.log("Hello Geeks from module.js!"); This is the first file which will call second.main.jsmain.jsvar Module = require("module"); (function (moduleWrapCopy) { Module.wrap = function (script) { script = "console.log('modifiedMWF');" + script; return moduleWrapCopy(script); };})(Module.wrap); require("./module.js"); main.js var Module = require("module"); (function (moduleWrapCopy) { Module.wrap = function (script) { script = "console.log('modifiedMWF');" + script; return moduleWrapCopy(script); };})(Module.wrap); require("./module.js"); This is the second file.module.jsmodule.jsconsole.log("Hello Geeks from module.js!"); module.js console.log("Hello Geeks from module.js!"); Output: Running main.js, we get the following output that confirms our successful alteration in Module Wrapper Function. node main.js Output window on running main.js NodeJS-Questions Picked Technical Scripter 2020 Node.js Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between promise and async await in Node.js How to use an ES6 import in Node.js? How to read and write Excel file in Node.js ? Express.js res.render() Function Mongoose | findByIdAndUpdate() Function Express.js res.redirect() Function Express.js res.send() Function Node.js fs.readdirSync() Method What are the differences between npm and npx ? Express.js res.sendFile() Function
[ { "code": null, "e": 26511, "s": 26483, "text": "\n07 Oct, 2021" }, { "code": null, "e": 26801, "s": 26511, "text": "Module Wrapper Function: Under the hood, NodeJS does not run our code directly, it wraps the entire code inside a function before execution. This function is termed as Module Wrapper Function. Refer https://nodejs.org/api/modules.html#modules_the_module_wrapper for official documentation." }, { "code": null, "e": 26911, "s": 26801, "text": "Before a module’s code is executed, NodeJS wraps it with a function wrapper that has the following structure:" }, { "code": null, "e": 26994, "s": 26911, "text": "(function (exports, require, module, __filename, __dirname) {\n //module code\n});\n" }, { "code": null, "e": 27036, "s": 26994, "text": "Use of Module Wrapper Function in NodeJS:" }, { "code": null, "e": 27429, "s": 27036, "text": "The top-level variables declared with var, const, or let are scoped to the module rather than to the global object.It provides some global-looking variables that are specific to the module, such as:The module and exports object that can be used to export values from the module.The variables like __filename and __dirname, that tells us the module’s absolute filename and its directory path." }, { "code": null, "e": 27545, "s": 27429, "text": "The top-level variables declared with var, const, or let are scoped to the module rather than to the global object." }, { "code": null, "e": 27823, "s": 27545, "text": "It provides some global-looking variables that are specific to the module, such as:The module and exports object that can be used to export values from the module.The variables like __filename and __dirname, that tells us the module’s absolute filename and its directory path." }, { "code": null, "e": 27904, "s": 27823, "text": "The module and exports object that can be used to export values from the module." }, { "code": null, "e": 28019, "s": 27904, "text": "The variables like __filename and __dirname, that tells us the module’s absolute filename and its directory path." }, { "code": null, "e": 28342, "s": 28019, "text": "Modifying Module Wrapper Function: Consider that we have two files, main.js and module.js. In main.js we overwrite the Module.wrap function in order to console.log(‘modifedMWF’); every time a module is required. Now if we require module.js, it contains a message to confirm whether our modifications are successful or not." }, { "code": null, "e": 28717, "s": 28342, "text": "This is the first file which will call second.main.jsmain.jsvar Module = require(\"module\"); (function (moduleWrapCopy) { Module.wrap = function (script) { script = \"console.log('modifiedMWF');\" + script; return moduleWrapCopy(script); };})(Module.wrap); require(\"./module.js\");This is the second file.module.jsmodule.jsconsole.log(\"Hello Geeks from module.js!\");" }, { "code": null, "e": 29007, "s": 28717, "text": "This is the first file which will call second.main.jsmain.jsvar Module = require(\"module\"); (function (moduleWrapCopy) { Module.wrap = function (script) { script = \"console.log('modifiedMWF');\" + script; return moduleWrapCopy(script); };})(Module.wrap); require(\"./module.js\");" }, { "code": null, "e": 29015, "s": 29007, "text": "main.js" }, { "code": "var Module = require(\"module\"); (function (moduleWrapCopy) { Module.wrap = function (script) { script = \"console.log('modifiedMWF');\" + script; return moduleWrapCopy(script); };})(Module.wrap); require(\"./module.js\");", "e": 29245, "s": 29015, "text": null }, { "code": null, "e": 29331, "s": 29245, "text": "This is the second file.module.jsmodule.jsconsole.log(\"Hello Geeks from module.js!\");" }, { "code": null, "e": 29341, "s": 29331, "text": "module.js" }, { "code": "console.log(\"Hello Geeks from module.js!\");", "e": 29385, "s": 29341, "text": null }, { "code": null, "e": 29506, "s": 29385, "text": "Output: Running main.js, we get the following output that confirms our successful alteration in Module Wrapper Function." }, { "code": null, "e": 29519, "s": 29506, "text": "node main.js" }, { "code": null, "e": 29552, "s": 29519, "text": "Output window on running main.js" }, { "code": null, "e": 29569, "s": 29552, "text": "NodeJS-Questions" }, { "code": null, "e": 29576, "s": 29569, "text": "Picked" }, { "code": null, "e": 29600, "s": 29576, "text": "Technical Scripter 2020" }, { "code": null, "e": 29608, "s": 29600, "text": "Node.js" }, { "code": null, "e": 29706, "s": 29608, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29760, "s": 29706, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 29797, "s": 29760, "text": "How to use an ES6 import in Node.js?" }, { "code": null, "e": 29843, "s": 29797, "text": "How to read and write Excel file in Node.js ?" }, { "code": null, "e": 29876, "s": 29843, "text": "Express.js res.render() Function" }, { "code": null, "e": 29916, "s": 29876, "text": "Mongoose | findByIdAndUpdate() Function" }, { "code": null, "e": 29951, "s": 29916, "text": "Express.js res.redirect() Function" }, { "code": null, "e": 29982, "s": 29951, "text": "Express.js res.send() Function" }, { "code": null, "e": 30014, "s": 29982, "text": "Node.js fs.readdirSync() Method" }, { "code": null, "e": 30061, "s": 30014, "text": "What are the differences between npm and npx ?" } ]
Context Menu in Android with Example - GeeksforGeeks
25 Sep, 2020 In Android, there are three types of menus available to define a set of options and actions in the Android apps. The lists of menus in Android applications are the following: Android options menuAndroid context menuAndroid popup menu Android options menu Android context menu Android popup menu Here in this article let’s discuss the detail of Context Menu. In Android, the context menu is like a floating menu and arises when the user has long pressed or clicks on an item and is beneficial for implementing functions that define the specific content or reference frame effect. The Android context menu is alike to the right-click menu in Windows or Linux. In the Android system, the context menu provides actions that change a specific element or context frame in the user interface and one can provide a context menu for any view. The context menu will not support any object shortcuts and object icons. Note that we are going to implement this project using the Java language. A sample GIF is given below to get an idea about what we are going to do in this article. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Working with the activity_main.xml file Open res -> Layout -> activity_main.xml and write the following code. In this file add only a TextView to display a simple text. XML <?xml version="1.0" encoding="utf-8"?> <!--Relative Layout to display all the details--><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/relLayout" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#fff" android:padding="16dp" tools:context=".MainActivity"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="20dp" android:text="Long press me!" android:textColor="#000" android:textSize="20sp" android:textStyle="bold" /> </RelativeLayout> Step 3: Working with the Mainactivity.java file Open the app -> Java -> Package -> Mainactivity.java file. In this step, add the code to show the ContextMenu. Whenever the app will strat make a long click on a text and display the number of options to select of them for specific purposes. Comments are added inside the code to understand the code in more detail. Java import android.graphics.Color;import android.os.Bundle;import android.view.ContextMenu;import android.view.MenuItem;import android.view.View;import android.widget.RelativeLayout;import android.widget.TextView;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { TextView textView; RelativeLayout relativeLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Link those objects with their respective id's // that we have given in .XML file textView = (TextView) findViewById(R.id.textView); relativeLayout = (RelativeLayout) findViewById(R.id.relLayout); // here you have to register a view for context menu // you can register any view like listview, image view, // textview, button etc registerForContextMenu(textView); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); // you can set menu header with title icon etc menu.setHeaderTitle("Choose a color"); // add menu items menu.add(0, v.getId(), 0, "Yellow"); menu.add(0, v.getId(), 0, "Gray"); menu.add(0, v.getId(), 0, "Cyan"); } // menu item select listener @Override public boolean onContextItemSelected(MenuItem item) { if (item.getTitle() == "Yellow") { relativeLayout.setBackgroundColor(Color.YELLOW); } else if (item.getTitle() == "Gray") { relativeLayout.setBackgroundColor(Color.GRAY); } else if (item.getTitle() == "Cyan") { relativeLayout.setBackgroundColor(Color.CYAN); } return true; }} Now connect the device with a USB cable or in an Emulator and launch the application. The user will see a text. Now long pressing on the text will generate menu options and select one of them to perform specific functionality. android Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Create and Add Data to SQLite Database in Android? Broadcast Receiver in Android With Example Content Providers in Android with Example Android RecyclerView in Kotlin How to View and Locate SQLite Database in Android Studio? For-each loop in Java Arrays.sort() in Java with examples Reverse a string in Java Initialize an ArrayList in Java HashMap in Java with Examples
[ { "code": null, "e": 25154, "s": 25126, "text": "\n25 Sep, 2020" }, { "code": null, "e": 25329, "s": 25154, "text": "In Android, there are three types of menus available to define a set of options and actions in the Android apps. The lists of menus in Android applications are the following:" }, { "code": null, "e": 25388, "s": 25329, "text": "Android options menuAndroid context menuAndroid popup menu" }, { "code": null, "e": 25409, "s": 25388, "text": "Android options menu" }, { "code": null, "e": 25430, "s": 25409, "text": "Android context menu" }, { "code": null, "e": 25449, "s": 25430, "text": "Android popup menu" }, { "code": null, "e": 26225, "s": 25449, "text": "Here in this article let’s discuss the detail of Context Menu. In Android, the context menu is like a floating menu and arises when the user has long pressed or clicks on an item and is beneficial for implementing functions that define the specific content or reference frame effect. The Android context menu is alike to the right-click menu in Windows or Linux. In the Android system, the context menu provides actions that change a specific element or context frame in the user interface and one can provide a context menu for any view. The context menu will not support any object shortcuts and object icons. Note that we are going to implement this project using the Java language. A sample GIF is given below to get an idea about what we are going to do in this article." }, { "code": null, "e": 26254, "s": 26225, "text": "Step 1: Create a New Project" }, { "code": null, "e": 26416, "s": 26254, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 26464, "s": 26416, "text": "Step 2: Working with the activity_main.xml file" }, { "code": null, "e": 26593, "s": 26464, "text": "Open res -> Layout -> activity_main.xml and write the following code. In this file add only a TextView to display a simple text." }, { "code": null, "e": 26597, "s": 26593, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?> <!--Relative Layout to display all the details--><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:id=\"@+id/relLayout\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"#fff\" android:padding=\"16dp\" tools:context=\".MainActivity\"> <TextView android:id=\"@+id/textView\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerHorizontal=\"true\" android:layout_marginTop=\"20dp\" android:text=\"Long press me!\" android:textColor=\"#000\" android:textSize=\"20sp\" android:textStyle=\"bold\" /> </RelativeLayout>", "e": 27385, "s": 26597, "text": null }, { "code": null, "e": 27433, "s": 27385, "text": "Step 3: Working with the Mainactivity.java file" }, { "code": null, "e": 27750, "s": 27433, "text": "Open the app -> Java -> Package -> Mainactivity.java file. In this step, add the code to show the ContextMenu. Whenever the app will strat make a long click on a text and display the number of options to select of them for specific purposes. Comments are added inside the code to understand the code in more detail. " }, { "code": null, "e": 27755, "s": 27750, "text": "Java" }, { "code": "import android.graphics.Color;import android.os.Bundle;import android.view.ContextMenu;import android.view.MenuItem;import android.view.View;import android.widget.RelativeLayout;import android.widget.TextView;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { TextView textView; RelativeLayout relativeLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Link those objects with their respective id's // that we have given in .XML file textView = (TextView) findViewById(R.id.textView); relativeLayout = (RelativeLayout) findViewById(R.id.relLayout); // here you have to register a view for context menu // you can register any view like listview, image view, // textview, button etc registerForContextMenu(textView); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); // you can set menu header with title icon etc menu.setHeaderTitle(\"Choose a color\"); // add menu items menu.add(0, v.getId(), 0, \"Yellow\"); menu.add(0, v.getId(), 0, \"Gray\"); menu.add(0, v.getId(), 0, \"Cyan\"); } // menu item select listener @Override public boolean onContextItemSelected(MenuItem item) { if (item.getTitle() == \"Yellow\") { relativeLayout.setBackgroundColor(Color.YELLOW); } else if (item.getTitle() == \"Gray\") { relativeLayout.setBackgroundColor(Color.GRAY); } else if (item.getTitle() == \"Cyan\") { relativeLayout.setBackgroundColor(Color.CYAN); } return true; }}", "e": 29602, "s": 27755, "text": null }, { "code": null, "e": 29829, "s": 29602, "text": "Now connect the device with a USB cable or in an Emulator and launch the application. The user will see a text. Now long pressing on the text will generate menu options and select one of them to perform specific functionality." }, { "code": null, "e": 29837, "s": 29829, "text": "android" }, { "code": null, "e": 29845, "s": 29837, "text": "Android" }, { "code": null, "e": 29850, "s": 29845, "text": "Java" }, { "code": null, "e": 29855, "s": 29850, "text": "Java" }, { "code": null, "e": 29863, "s": 29855, "text": "Android" }, { "code": null, "e": 29961, "s": 29863, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29970, "s": 29961, "text": "Comments" }, { "code": null, "e": 29983, "s": 29970, "text": "Old Comments" }, { "code": null, "e": 30041, "s": 29983, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 30084, "s": 30041, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 30126, "s": 30084, "text": "Content Providers in Android with Example" }, { "code": null, "e": 30157, "s": 30126, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 30215, "s": 30157, "text": "How to View and Locate SQLite Database in Android Studio?" }, { "code": null, "e": 30237, "s": 30215, "text": "For-each loop in Java" }, { "code": null, "e": 30273, "s": 30237, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 30298, "s": 30273, "text": "Reverse a string in Java" }, { "code": null, "e": 30330, "s": 30298, "text": "Initialize an ArrayList in Java" } ]
RANK() Function in SQL Server - GeeksforGeeks
18 Sep, 2020 The RANK() function is a window function could be used in SQL Server to calculate a rank for each row within a partition of a result set. The same rank is assigned to the rows in a partition which have the same values. The rank of the first row is 1. The ranks may not be consecutive in the RANK() function as it adds the number of repeated rows to the repeated rank to calculate the rank of the next row. Syntax : RANK() OVER ( [PARTITION BY expression, ] ORDER BY expression (ASC | DESC) ); Example – Let us create a table geek_demo that has only column Name : CREATE TABLE geek_demo (Name VARCHAR(10) ); Now, insert some rows into the sales.rank_demo table : INSERT INTO geek_demo (Name) VALUES('A'), ('B'), ('B'), ('C'), ('C'), ('D'), ('E'); Select data from the geek_demo table : SELECT * FROM sales.geek_demo; Let us use RANK() to assign ranks to the rows in the result set of geek_demo table : SELECT Name, RANK () OVER ( ORDER BY Name ) AS Rank_no FROM geek_demo; Output – khushboogoyal499 DBMS-SQL SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments SQL Trigger | Student Database SQL | Views Difference between DDL and DML in DBMS How to Alter Multiple Columns at Once in SQL Server? CTE in SQL SQL Interview Questions How to Update Multiple Columns in Single Update Statement in SQL? Difference between DELETE, DROP and TRUNCATE SQL | GROUP BY MySQL | Group_CONCAT() Function
[ { "code": null, "e": 23993, "s": 23965, "text": "\n18 Sep, 2020" }, { "code": null, "e": 24132, "s": 23993, "text": "The RANK() function is a window function could be used in SQL Server to calculate a rank for each row within a partition of a result set. " }, { "code": null, "e": 24401, "s": 24132, "text": "The same rank is assigned to the rows in a partition which have the same values. The rank of the first row is 1. The ranks may not be consecutive in the RANK() function as it adds the number of repeated rows to the repeated rank to calculate the rank of the next row. " }, { "code": null, "e": 24412, "s": 24401, "text": "Syntax : " }, { "code": null, "e": 24498, "s": 24412, "text": "RANK() OVER (\n [PARTITION BY expression, ]\n ORDER BY expression (ASC | DESC) );\n\n" }, { "code": null, "e": 24569, "s": 24498, "text": "Example – Let us create a table geek_demo that has only column Name : " }, { "code": null, "e": 24617, "s": 24571, "text": "CREATE TABLE geek_demo (Name VARCHAR(10) );\n\n" }, { "code": null, "e": 24702, "s": 24617, "text": "Now, insert some rows into the sales.rank_demo table : INSERT INTO geek_demo (Name) " }, { "code": null, "e": 24761, "s": 24704, "text": "VALUES('A'), ('B'), ('B'), ('C'), ('C'), ('D'), ('E');\n\n" }, { "code": null, "e": 24802, "s": 24761, "text": "Select data from the geek_demo table : " }, { "code": null, "e": 24836, "s": 24802, "text": "SELECT * \nFROM sales.geek_demo; \n" }, { "code": null, "e": 24924, "s": 24838, "text": "Let us use RANK() to assign ranks to the rows in the result set of geek_demo table : " }, { "code": null, "e": 25001, "s": 24926, "text": "SELECT Name, \nRANK () OVER (\nORDER BY Name\n) AS Rank_no \nFROM geek_demo;\n\n" }, { "code": null, "e": 25011, "s": 25001, "text": "Output – " }, { "code": null, "e": 25030, "s": 25013, "text": "khushboogoyal499" }, { "code": null, "e": 25039, "s": 25030, "text": "DBMS-SQL" }, { "code": null, "e": 25050, "s": 25039, "text": "SQL-Server" }, { "code": null, "e": 25054, "s": 25050, "text": "SQL" }, { "code": null, "e": 25058, "s": 25054, "text": "SQL" }, { "code": null, "e": 25156, "s": 25058, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25165, "s": 25156, "text": "Comments" }, { "code": null, "e": 25178, "s": 25165, "text": "Old Comments" }, { "code": null, "e": 25209, "s": 25178, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 25221, "s": 25209, "text": "SQL | Views" }, { "code": null, "e": 25260, "s": 25221, "text": "Difference between DDL and DML in DBMS" }, { "code": null, "e": 25313, "s": 25260, "text": "How to Alter Multiple Columns at Once in SQL Server?" }, { "code": null, "e": 25324, "s": 25313, "text": "CTE in SQL" }, { "code": null, "e": 25348, "s": 25324, "text": "SQL Interview Questions" }, { "code": null, "e": 25414, "s": 25348, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 25459, "s": 25414, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 25474, "s": 25459, "text": "SQL | GROUP BY" } ]
Java Program to Read a Large Text File Line by Line - GeeksforGeeks
13 Sep, 2021 As we are are well verse with this topic let us put more stress in order to figure out minute differences between them. Here we are supposed to read from a file on the local directory where a text file is present say it be ‘gfg.txt’. Let the content inside the file be as shown below: Geeks for Geeks. A computer science portal. Welcome to this portal. Hello Geek !!! Note: Keep a check that prior doing anything first create a file on the system repository to deal with our program\writing a program as we will be accessing the same directory through our programs. Methods: Using Scanner classUsing BufferedReaader class Using Scanner class Using BufferedReaader class Method 1: Using Scanner class Scanner is a class in java.util package used for obtaining the input of the primitive types like int, double, etc. and strings. It is the easiest way to read input in a Java program, though not very efficient if you want an input method for scenarios where time is a constraint like in competitive programming. Scanner class is used to read the large file line by line. A Scanner breaks its input into tokens, which by default matches the whitespace. Example Java // Java Program to Read a Large Text File Line by Line// Using Scanner class // Importing required classesimport java.io.*;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.InputStream;import java.nio.charset.StandardCharsets;import java.util.Scanner; // Main classpublic class GFG { // Main driver method public static void main(String[] args) throws FileNotFoundException { // Declaring and initializing the string with // custom path of a file String path = "C:\\Users\\HP\\Desktop\\gfg.txt"; // Creating an instance of Inputstream InputStream is = new FileInputStream(path); // Try block to check for exceptions try (Scanner sc = new Scanner( is, StandardCharsets.UTF_8.name())) { // It holds true till there is single element // left in the object with usage of hasNext() // method while (sc.hasNextLine()) { // Printing the content of file System.out.println(sc.nextLine()); } } }} Output: Geeks for Geeks. A computer science portal. Welcome to this portal. Hello Geek !!! Method 2: Using BufferedReader class BufferedReader is used to read the file line by line. Basically, BufferedReader() is used for the processing of large files. BufferedReader is very efficient for reading. Note: Specify the size of the BufferReader or keep that size as a Default size of BufferReader. The default size of BufferReader is 8KB. Syntax: BufferedReader in = new BufferedReader(Reader in, int size); Example: Java // Java Program to Read a Large Text File Line by Line// Using BufferedReader class // Importing required classesimport java.io.*;import java.io.BufferedReader;import java.io.FileReader;import java.io.IOException; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Declaring a string and initializing it with // path of file present on the system String path = "C:\\Users\\HP\\Desktop\\gfg.txt"; // Try block to check for exceptions try (BufferedReader br = new BufferedReader(new FileReader(path))) { // Declaring a new string String str; // It holds true till threre is content in file while ((str = br.readLine()) != null) { // Printing the file data System.out.println(br); } } // Catch block to handle the exceptions catch (IOException e) { // Display pop up message if exceptionn occurs System.out.println( "Error while reading a file."); } }} Output: Geeks for Geeks. A computer science portal. Welcome to this portal. Hello Geek !!! anikakapoor sweetyty Java-Files Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Different ways of Reading a text file in Java Exceptions in Java Functional Interfaces in Java Convert a String to Character array in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java?
[ { "code": null, "e": 23972, "s": 23944, "text": "\n13 Sep, 2021" }, { "code": null, "e": 24257, "s": 23972, "text": "As we are are well verse with this topic let us put more stress in order to figure out minute differences between them. Here we are supposed to read from a file on the local directory where a text file is present say it be ‘gfg.txt’. Let the content inside the file be as shown below:" }, { "code": null, "e": 24340, "s": 24257, "text": "Geeks for Geeks.\nA computer science portal.\nWelcome to this portal.\nHello Geek !!!" }, { "code": null, "e": 24538, "s": 24340, "text": "Note: Keep a check that prior doing anything first create a file on the system repository to deal with our program\\writing a program as we will be accessing the same directory through our programs." }, { "code": null, "e": 24547, "s": 24538, "text": "Methods:" }, { "code": null, "e": 24594, "s": 24547, "text": "Using Scanner classUsing BufferedReaader class" }, { "code": null, "e": 24614, "s": 24594, "text": "Using Scanner class" }, { "code": null, "e": 24642, "s": 24614, "text": "Using BufferedReaader class" }, { "code": null, "e": 24672, "s": 24642, "text": "Method 1: Using Scanner class" }, { "code": null, "e": 25125, "s": 24672, "text": "Scanner is a class in java.util package used for obtaining the input of the primitive types like int, double, etc. and strings. It is the easiest way to read input in a Java program, though not very efficient if you want an input method for scenarios where time is a constraint like in competitive programming. Scanner class is used to read the large file line by line. A Scanner breaks its input into tokens, which by default matches the whitespace. " }, { "code": null, "e": 25133, "s": 25125, "text": "Example" }, { "code": null, "e": 25138, "s": 25133, "text": "Java" }, { "code": "// Java Program to Read a Large Text File Line by Line// Using Scanner class // Importing required classesimport java.io.*;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.InputStream;import java.nio.charset.StandardCharsets;import java.util.Scanner; // Main classpublic class GFG { // Main driver method public static void main(String[] args) throws FileNotFoundException { // Declaring and initializing the string with // custom path of a file String path = \"C:\\\\Users\\\\HP\\\\Desktop\\\\gfg.txt\"; // Creating an instance of Inputstream InputStream is = new FileInputStream(path); // Try block to check for exceptions try (Scanner sc = new Scanner( is, StandardCharsets.UTF_8.name())) { // It holds true till there is single element // left in the object with usage of hasNext() // method while (sc.hasNextLine()) { // Printing the content of file System.out.println(sc.nextLine()); } } }}", "e": 26241, "s": 25138, "text": null }, { "code": null, "e": 26250, "s": 26241, "text": "Output: " }, { "code": null, "e": 26333, "s": 26250, "text": "Geeks for Geeks.\nA computer science portal.\nWelcome to this portal.\nHello Geek !!!" }, { "code": null, "e": 26370, "s": 26333, "text": "Method 2: Using BufferedReader class" }, { "code": null, "e": 26542, "s": 26370, "text": "BufferedReader is used to read the file line by line. Basically, BufferedReader() is used for the processing of large files. BufferedReader is very efficient for reading. " }, { "code": null, "e": 26680, "s": 26542, "text": "Note: Specify the size of the BufferReader or keep that size as a Default size of BufferReader. The default size of BufferReader is 8KB. " }, { "code": null, "e": 26688, "s": 26680, "text": "Syntax:" }, { "code": null, "e": 26749, "s": 26688, "text": "BufferedReader in = new BufferedReader(Reader in, int size);" }, { "code": null, "e": 26758, "s": 26749, "text": "Example:" }, { "code": null, "e": 26763, "s": 26758, "text": "Java" }, { "code": "// Java Program to Read a Large Text File Line by Line// Using BufferedReader class // Importing required classesimport java.io.*;import java.io.BufferedReader;import java.io.FileReader;import java.io.IOException; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Declaring a string and initializing it with // path of file present on the system String path = \"C:\\\\Users\\\\HP\\\\Desktop\\\\gfg.txt\"; // Try block to check for exceptions try (BufferedReader br = new BufferedReader(new FileReader(path))) { // Declaring a new string String str; // It holds true till threre is content in file while ((str = br.readLine()) != null) { // Printing the file data System.out.println(br); } } // Catch block to handle the exceptions catch (IOException e) { // Display pop up message if exceptionn occurs System.out.println( \"Error while reading a file.\"); } }}", "e": 27877, "s": 26763, "text": null }, { "code": null, "e": 27886, "s": 27877, "text": "Output: " }, { "code": null, "e": 27969, "s": 27886, "text": "Geeks for Geeks.\nA computer science portal.\nWelcome to this portal.\nHello Geek !!!" }, { "code": null, "e": 27981, "s": 27969, "text": "anikakapoor" }, { "code": null, "e": 27990, "s": 27981, "text": "sweetyty" }, { "code": null, "e": 28001, "s": 27990, "text": "Java-Files" }, { "code": null, "e": 28008, "s": 28001, "text": "Picked" }, { "code": null, "e": 28013, "s": 28008, "text": "Java" }, { "code": null, "e": 28027, "s": 28013, "text": "Java Programs" }, { "code": null, "e": 28032, "s": 28027, "text": "Java" }, { "code": null, "e": 28130, "s": 28032, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28145, "s": 28130, "text": "Stream In Java" }, { "code": null, "e": 28166, "s": 28145, "text": "Constructors in Java" }, { "code": null, "e": 28212, "s": 28166, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 28231, "s": 28212, "text": "Exceptions in Java" }, { "code": null, "e": 28261, "s": 28231, "text": "Functional Interfaces in Java" }, { "code": null, "e": 28305, "s": 28261, "text": "Convert a String to Character array in Java" }, { "code": null, "e": 28331, "s": 28305, "text": "Java Programming Examples" }, { "code": null, "e": 28365, "s": 28331, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 28412, "s": 28365, "text": "Implementing a Linked List in Java using Class" } ]
Delete rows in PySpark dataframe based on multiple conditions - GeeksforGeeks
29 Jun, 2021 In this article, we are going to see how to delete rows in PySpark dataframe based on multiple conditions. Here we are going to use the logical expression to filter the row. Filter() function is used to filter the rows from RDD/DataFrame based on the given condition or SQL expression. Syntax: filter( condition) Parameters: Condition: Logical condition or SQL expression Example 1: Python3 # importing moduleimport pyspark # importing sparksession from pyspark.sql# modulefrom pyspark.sql import SparkSession # spark library importimport pyspark.sql.functions # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of students datadata = [["1", "Amit", " DU"], ["2", "Mohit", "DU"], ["3", "rohith", "BHU"], ["4", "sridevi", "LPU"], ["1", "sravan", "KLMP"], ["5", "gnanesh", "IIT"]] # specify column namescolumns = ['student_ID', 'student_NAME', 'college'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) dataframe = dataframe.filter(dataframe.college != "IIT") dataframe.show() Output: Example 2: Python3 # importing moduleimport pyspark # importing sparksession from pyspark.sql# modulefrom pyspark.sql import SparkSession # spark library importimport pyspark.sql.functions # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of students datadata = [["1", "Amit", " DU"], ["2", "Mohit", "DU"], ["3", "rohith", "BHU"], ["4", "sridevi", "LPU"], ["1", "sravan", "KLMP"], ["5", "gnanesh", "IIT"]] # specify column namescolumns = ['student_ID', 'student_NAME', 'college'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) dataframe = dataframe.filter( ((dataframe.college != "DU") & (dataframe.student_ID != "3"))) dataframe.show() Output: It evaluates a list of conditions and returns a single value. Thus passing the condition and its required values will get the job done. Syntax: When( Condition, Value) Parameters: Condition: Boolean or columns expression. Value: Literal Value Example: Python3 # importing moduleimport pyspark # importing sparksession from pyspark.sql # modulefrom pyspark.sql import SparkSession # spark library importimport pyspark.sql.functions # spark library importfrom pyspark.sql.functions import when # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of students datadata = [["1", "Amit", " DU"], ["2", "Mohit", "DU"], ["3", "rohith", "BHU"], ["4", "sridevi", "LPU"], ["1", "sravan", "KLMP"], ["5", "gnanesh", "IIT"]] # specify column namescolumns = ['student_ID', 'student_NAME', 'college'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) dataframe.withColumn('New_col', when(dataframe.student_ID != '5', "True") .when(dataframe.student_NAME != 'gnanesh', "True") ).filter("New_col == True").drop("New_col").show() Output: Picked Python-Pyspark Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Enumerate() in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists Reading and Writing to text files in Python *args and **kwargs in Python How To Convert Python Dictionary To JSON? sum() function in Python
[ { "code": null, "e": 24476, "s": 24448, "text": "\n29 Jun, 2021" }, { "code": null, "e": 24583, "s": 24476, "text": "In this article, we are going to see how to delete rows in PySpark dataframe based on multiple conditions." }, { "code": null, "e": 24762, "s": 24583, "text": "Here we are going to use the logical expression to filter the row. Filter() function is used to filter the rows from RDD/DataFrame based on the given condition or SQL expression." }, { "code": null, "e": 24789, "s": 24762, "text": "Syntax: filter( condition)" }, { "code": null, "e": 24802, "s": 24789, "text": "Parameters: " }, { "code": null, "e": 24849, "s": 24802, "text": "Condition: Logical condition or SQL expression" }, { "code": null, "e": 24861, "s": 24849, "text": "Example 1: " }, { "code": null, "e": 24869, "s": 24861, "text": "Python3" }, { "code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql# modulefrom pyspark.sql import SparkSession # spark library importimport pyspark.sql.functions # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of students datadata = [[\"1\", \"Amit\", \" DU\"], [\"2\", \"Mohit\", \"DU\"], [\"3\", \"rohith\", \"BHU\"], [\"4\", \"sridevi\", \"LPU\"], [\"1\", \"sravan\", \"KLMP\"], [\"5\", \"gnanesh\", \"IIT\"]] # specify column namescolumns = ['student_ID', 'student_NAME', 'college'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) dataframe = dataframe.filter(dataframe.college != \"IIT\") dataframe.show()", "e": 25608, "s": 24869, "text": null }, { "code": null, "e": 25616, "s": 25608, "text": "Output:" }, { "code": null, "e": 25627, "s": 25616, "text": "Example 2:" }, { "code": null, "e": 25635, "s": 25627, "text": "Python3" }, { "code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql# modulefrom pyspark.sql import SparkSession # spark library importimport pyspark.sql.functions # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of students datadata = [[\"1\", \"Amit\", \" DU\"], [\"2\", \"Mohit\", \"DU\"], [\"3\", \"rohith\", \"BHU\"], [\"4\", \"sridevi\", \"LPU\"], [\"1\", \"sravan\", \"KLMP\"], [\"5\", \"gnanesh\", \"IIT\"]] # specify column namescolumns = ['student_ID', 'student_NAME', 'college'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) dataframe = dataframe.filter( ((dataframe.college != \"DU\") & (dataframe.student_ID != \"3\"))) dataframe.show()", "e": 26417, "s": 25635, "text": null }, { "code": null, "e": 26425, "s": 26417, "text": "Output:" }, { "code": null, "e": 26561, "s": 26425, "text": "It evaluates a list of conditions and returns a single value. Thus passing the condition and its required values will get the job done." }, { "code": null, "e": 26593, "s": 26561, "text": "Syntax: When( Condition, Value)" }, { "code": null, "e": 26605, "s": 26593, "text": "Parameters:" }, { "code": null, "e": 26647, "s": 26605, "text": "Condition: Boolean or columns expression." }, { "code": null, "e": 26668, "s": 26647, "text": "Value: Literal Value" }, { "code": null, "e": 26678, "s": 26668, "text": "Example: " }, { "code": null, "e": 26686, "s": 26678, "text": "Python3" }, { "code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql # modulefrom pyspark.sql import SparkSession # spark library importimport pyspark.sql.functions # spark library importfrom pyspark.sql.functions import when # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of students datadata = [[\"1\", \"Amit\", \" DU\"], [\"2\", \"Mohit\", \"DU\"], [\"3\", \"rohith\", \"BHU\"], [\"4\", \"sridevi\", \"LPU\"], [\"1\", \"sravan\", \"KLMP\"], [\"5\", \"gnanesh\", \"IIT\"]] # specify column namescolumns = ['student_ID', 'student_NAME', 'college'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) dataframe.withColumn('New_col', when(dataframe.student_ID != '5', \"True\") .when(dataframe.student_NAME != 'gnanesh', \"True\") ).filter(\"New_col == True\").drop(\"New_col\").show()", "e": 27649, "s": 26686, "text": null }, { "code": null, "e": 27657, "s": 27649, "text": "Output:" }, { "code": null, "e": 27664, "s": 27657, "text": "Picked" }, { "code": null, "e": 27679, "s": 27664, "text": "Python-Pyspark" }, { "code": null, "e": 27686, "s": 27679, "text": "Python" }, { "code": null, "e": 27784, "s": 27686, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27802, "s": 27784, "text": "Python Dictionary" }, { "code": null, "e": 27824, "s": 27802, "text": "Enumerate() in Python" }, { "code": null, "e": 27856, "s": 27824, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27898, "s": 27856, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27924, "s": 27898, "text": "Python String | replace()" }, { "code": null, "e": 27961, "s": 27924, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 28005, "s": 27961, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 28034, "s": 28005, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28076, "s": 28034, "text": "How To Convert Python Dictionary To JSON?" } ]
Console.ReadLine() Method in C# - GeeksforGeeks
26 Aug, 2021 This method is used to read the next line of characters from the standard input stream. It comes under the Console class(System Namespace). If the standard input device is the keyboard, the ReadLine method blocks until the user presses the Enter key. And if standard input is redirected to a file, then this method reads a line of text from a file. Syntax: public static string ReadLine ();Return Value: It returns the next line of characters of string type from the input stream, or null if no more lines are available. Exceptions: IOException: If an I/O error occurred. OutOfMemoryException: If there is insufficient memory to allocate a buffer for the returned string. ArgumentOutOfRangeException: If the number of characters in the next line of characters is greater than MaxValue. Below program illustrate the use of the above-discussed method:Example 1: Here, take input from the user. Since age is an integer, we typecasted it using Convert.ToInt32() Method. It reads the next line from the input stream. It blocks until Enter key is pressed. Hence it is commonly used to pause the console so that the user can check the output. csharp // C# program to illustrate// the use of Console.ReadLine()using System;using System.IO; class GFG { // Main Method public static void Main() { int age; string name; Console.WriteLine("Enter your name: "); // using the method // typecasting not needed // as ReadLine returns string name = Console.ReadLine(); Console.WriteLine("Enter your age: "); // Converted string to int age = Convert.ToInt32(Console.ReadLine()); if (age >= 18) { Console.WriteLine("Hello " + name + "!" + " You can vote"); } else { Console.WriteLine("Hello " + name + "!" + " Sorry you can't vote"); } }} Output: Example 2: To pause the console csharp // C# program to illustrate// the use of Console.ReadLine()// to pause the consoleusing System;using System.IO; class Geeks { // Main Method public static void Main() { string name; int n; Console.WriteLine("Enter your name: "); // typecasting not needed as // ReadLine returns string name = Console.ReadLine(); Console.WriteLine("Hello " + name + " Welcome to GeeksforGeeks!"); // Pauses the console until // the user presses enter key Console.ReadLine(); }} Output: Explanation: In the above output you can see that the console is paused. The cursor will blink continuously until you press Enter key.Reference: https://docs.microsoft.com/en-us/dotnet/api/system.console.readline?view=netframework-4.7.2 sooda367 CSharp-Console-Class CSharp-method Picked C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Destructors in C# Difference between Ref and Out keywords in C# C# | Delegates C# | String.IndexOf( ) Method | Set - 1 C# | Constructors Extension Method in C# Introduction to .NET Framework C# | Class and Object C# | Abstract Classes C# | Data Types
[ { "code": null, "e": 25006, "s": 24978, "text": "\n26 Aug, 2021" }, { "code": null, "e": 25357, "s": 25006, "text": "This method is used to read the next line of characters from the standard input stream. It comes under the Console class(System Namespace). If the standard input device is the keyboard, the ReadLine method blocks until the user presses the Enter key. And if standard input is redirected to a file, then this method reads a line of text from a file. " }, { "code": null, "e": 25531, "s": 25357, "text": "Syntax: public static string ReadLine ();Return Value: It returns the next line of characters of string type from the input stream, or null if no more lines are available. " }, { "code": null, "e": 25544, "s": 25531, "text": "Exceptions: " }, { "code": null, "e": 25583, "s": 25544, "text": "IOException: If an I/O error occurred." }, { "code": null, "e": 25683, "s": 25583, "text": "OutOfMemoryException: If there is insufficient memory to allocate a buffer for the returned string." }, { "code": null, "e": 25797, "s": 25683, "text": "ArgumentOutOfRangeException: If the number of characters in the next line of characters is greater than MaxValue." }, { "code": null, "e": 26147, "s": 25797, "text": "Below program illustrate the use of the above-discussed method:Example 1: Here, take input from the user. Since age is an integer, we typecasted it using Convert.ToInt32() Method. It reads the next line from the input stream. It blocks until Enter key is pressed. Hence it is commonly used to pause the console so that the user can check the output." }, { "code": null, "e": 26154, "s": 26147, "text": "csharp" }, { "code": "// C# program to illustrate// the use of Console.ReadLine()using System;using System.IO; class GFG { // Main Method public static void Main() { int age; string name; Console.WriteLine(\"Enter your name: \"); // using the method // typecasting not needed // as ReadLine returns string name = Console.ReadLine(); Console.WriteLine(\"Enter your age: \"); // Converted string to int age = Convert.ToInt32(Console.ReadLine()); if (age >= 18) { Console.WriteLine(\"Hello \" + name + \"!\" + \" You can vote\"); } else { Console.WriteLine(\"Hello \" + name + \"!\" + \" Sorry you can't vote\"); } }}", "e": 26950, "s": 26154, "text": null }, { "code": null, "e": 26960, "s": 26950, "text": "Output: " }, { "code": null, "e": 26992, "s": 26960, "text": "Example 2: To pause the console" }, { "code": null, "e": 26999, "s": 26992, "text": "csharp" }, { "code": "// C# program to illustrate// the use of Console.ReadLine()// to pause the consoleusing System;using System.IO; class Geeks { // Main Method public static void Main() { string name; int n; Console.WriteLine(\"Enter your name: \"); // typecasting not needed as // ReadLine returns string name = Console.ReadLine(); Console.WriteLine(\"Hello \" + name + \" Welcome to GeeksforGeeks!\"); // Pauses the console until // the user presses enter key Console.ReadLine(); }}", "e": 27586, "s": 26999, "text": null }, { "code": null, "e": 27596, "s": 27586, "text": "Output: " }, { "code": null, "e": 27742, "s": 27596, "text": "Explanation: In the above output you can see that the console is paused. The cursor will blink continuously until you press Enter key.Reference: " }, { "code": null, "e": 27834, "s": 27742, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.console.readline?view=netframework-4.7.2" }, { "code": null, "e": 27843, "s": 27834, "text": "sooda367" }, { "code": null, "e": 27864, "s": 27843, "text": "CSharp-Console-Class" }, { "code": null, "e": 27878, "s": 27864, "text": "CSharp-method" }, { "code": null, "e": 27885, "s": 27878, "text": "Picked" }, { "code": null, "e": 27888, "s": 27885, "text": "C#" }, { "code": null, "e": 27986, "s": 27888, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28004, "s": 27986, "text": "Destructors in C#" }, { "code": null, "e": 28050, "s": 28004, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 28065, "s": 28050, "text": "C# | Delegates" }, { "code": null, "e": 28105, "s": 28065, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 28123, "s": 28105, "text": "C# | Constructors" }, { "code": null, "e": 28146, "s": 28123, "text": "Extension Method in C#" }, { "code": null, "e": 28177, "s": 28146, "text": "Introduction to .NET Framework" }, { "code": null, "e": 28199, "s": 28177, "text": "C# | Class and Object" }, { "code": null, "e": 28221, "s": 28199, "text": "C# | Abstract Classes" } ]
How to append a second list to an existing list in C#?
Use the AddRange() method to append a second list to an existing list. Here is list one − List < string > list1 = new List < string > (); list1.Add("One"); list1.Add("Two"); Here is list two − List < string > list2 = new List < string > (); list2.Add("Three"); ist2.Add("Four"); Now let us append − list1.AddRange(list2); Let us see the complete code. using System; using System.Collections.Generic; using System.Linq; public class Demo { public static void Main() { List < string > list1 = new List < string > (); list1.Add("One"); list1.Add("Two"); Console.WriteLine("First list..."); foreach(string value in list1) { Console.WriteLine(value); } Console.WriteLine("Second list..."); List < string > list2 = new List < string > (); list2.Add("Three"); list2.Add("Four"); foreach(string value in list2) { Console.WriteLine(value); } Console.WriteLine("After Append..."); list1.AddRange(list2); foreach(string value in list1) { Console.WriteLine(value); } } }
[ { "code": null, "e": 1133, "s": 1062, "text": "Use the AddRange() method to append a second list to an existing list." }, { "code": null, "e": 1152, "s": 1133, "text": "Here is list one −" }, { "code": null, "e": 1237, "s": 1152, "text": "List < string > list1 = new List < string > ();\n\nlist1.Add(\"One\");\nlist1.Add(\"Two\");" }, { "code": null, "e": 1256, "s": 1237, "text": "Here is list two −" }, { "code": null, "e": 1343, "s": 1256, "text": "List < string > list2 = new List < string > ();\n\nlist2.Add(\"Three\");\nist2.Add(\"Four\");" }, { "code": null, "e": 1363, "s": 1343, "text": "Now let us append −" }, { "code": null, "e": 1386, "s": 1363, "text": "list1.AddRange(list2);" }, { "code": null, "e": 1416, "s": 1386, "text": "Let us see the complete code." }, { "code": null, "e": 2157, "s": 1416, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class Demo {\n public static void Main() {\n\n List < string > list1 = new List < string > ();\n list1.Add(\"One\");\n list1.Add(\"Two\");\n Console.WriteLine(\"First list...\");\n foreach(string value in list1) {\n Console.WriteLine(value);\n }\n\n Console.WriteLine(\"Second list...\");\n List < string > list2 = new List < string > ();\n\n list2.Add(\"Three\");\n list2.Add(\"Four\");\n foreach(string value in list2) {\n Console.WriteLine(value);\n }\n\n Console.WriteLine(\"After Append...\");\n list1.AddRange(list2);\n foreach(string value in list1) {\n Console.WriteLine(value);\n }\n }\n}" } ]
Tryit Editor v3.6 - Show Java
class Vehicle // Base class { public string brand = "Ford"; // Vehicle field public void honk() // Vehicle method { Console.WriteLine("Tuut, tuut!"); } } } using System; namespace MyApplication { class Car : Vehicle // Derived class { public string modelName = "Mustang"; // Car field } } using System; namespace MyApplication { class Program { static void Main(string[] args) { // Create a myCar object Car myCar = new Car(); // Call the honk() method (From the Vehicle class) on the myCar object myCar.honk(); // Display the value of the brand field (from the Vehicle class) and the value of the modelName from the Car class Console.WriteLine(myCar.brand + " " + myCar.modelName);
[ { "code": null, "e": 242, "s": 0, "text": "\n class Vehicle // Base class\n {\n public string brand = \"Ford\"; // Vehicle field\n public void honk() // Vehicle method \n {\n Console.WriteLine(\"Tuut, tuut!\");\n }\n }\n}\n\n" }, { "code": null, "e": 390, "s": 242, "text": "using System;\n\nnamespace MyApplication\n{\n class Car : Vehicle // Derived class\n {\n public string modelName = \"Mustang\"; // Car field\n }\n}\n\n" } ]
PySpark - SparkFiles
In Apache Spark, you can upload your files using sc.addFile (sc is your default SparkContext) and get the path on a worker using SparkFiles.get. Thus, SparkFiles resolve the paths to files added through SparkContext.addFile(). SparkFiles contain the following classmethods − get(filename) getrootdirectory() Let us understand them in detail. It specifies the path of the file that is added through SparkContext.addFile(). It specifies the path to the root directory, which contains the file that is added through the SparkContext.addFile(). ----------------------------------------sparkfile.py------------------------------------ from pyspark import SparkContext from pyspark import SparkFiles finddistance = "/home/hadoop/examples_pyspark/finddistance.R" finddistancename = "finddistance.R" sc = SparkContext("local", "SparkFile App") sc.addFile(finddistance) print "Absolute Path -> %s" % SparkFiles.get(finddistancename) ----------------------------------------sparkfile.py------------------------------------ Command − The command is as follows − $SPARK_HOME/bin/spark-submit sparkfiles.py Output − The output for the above command is − Absolute Path -> /tmp/spark-f1170149-af01-4620-9805-f61c85fecee4/userFiles-641dfd0f-240b-4264-a650-4e06e7a57839/finddistance.R Print Add Notes Bookmark this page
[ { "code": null, "e": 2032, "s": 1805, "text": "In Apache Spark, you can upload your files using sc.addFile (sc is your default SparkContext) and get the path on a worker using SparkFiles.get. Thus, SparkFiles resolve the paths to files added through SparkContext.addFile()." }, { "code": null, "e": 2080, "s": 2032, "text": "SparkFiles contain the following classmethods −" }, { "code": null, "e": 2094, "s": 2080, "text": "get(filename)" }, { "code": null, "e": 2113, "s": 2094, "text": "getrootdirectory()" }, { "code": null, "e": 2147, "s": 2113, "text": "Let us understand them in detail." }, { "code": null, "e": 2227, "s": 2147, "text": "It specifies the path of the file that is added through SparkContext.addFile()." }, { "code": null, "e": 2346, "s": 2227, "text": "It specifies the path to the root directory, which contains the file that is added through the SparkContext.addFile()." }, { "code": null, "e": 2819, "s": 2346, "text": "----------------------------------------sparkfile.py------------------------------------\nfrom pyspark import SparkContext\nfrom pyspark import SparkFiles\nfinddistance = \"/home/hadoop/examples_pyspark/finddistance.R\"\nfinddistancename = \"finddistance.R\"\nsc = SparkContext(\"local\", \"SparkFile App\")\nsc.addFile(finddistance)\nprint \"Absolute Path -> %s\" % SparkFiles.get(finddistancename)\n----------------------------------------sparkfile.py------------------------------------\n" }, { "code": null, "e": 2857, "s": 2819, "text": "Command − The command is as follows −" }, { "code": null, "e": 2901, "s": 2857, "text": "$SPARK_HOME/bin/spark-submit sparkfiles.py\n" }, { "code": null, "e": 2948, "s": 2901, "text": "Output − The output for the above command is −" }, { "code": null, "e": 3080, "s": 2948, "text": "Absolute Path -> \n /tmp/spark-f1170149-af01-4620-9805-f61c85fecee4/userFiles-641dfd0f-240b-4264-a650-4e06e7a57839/finddistance.R\n" }, { "code": null, "e": 3087, "s": 3080, "text": " Print" }, { "code": null, "e": 3098, "s": 3087, "text": " Add Notes" } ]
Build a Docker Container with Your Machine Learning Model | by Tina Bu | Towards Data Science
As a data scientist, I don’t have a lot of software engineering experience but I have certainly heard a lot of great comments about containers. I have heard about how lightweight they are compared to traditional VMs, how good they are at ensuring a safe consistent environment for your code, and how my devops effort it saves so you can focus on your code. However, when I tried to Dockerize my own model, I soon realized it is not that intuitive. It is not at all as simple as putting RUN in front of your EC2 bootstrap script. I found that inconsistencies and unpredictable behaviors happen quite a lot and it can be frustrating to learn to debug a new tool. All of these motivated me to create this post with all the code snippets you need to factorize your ML model in Python to a Docker container. I will guide you through installing all the pip packages you need and build your first container image. And in the second part of this post, we will be setting up all the necessary AWS environments and kicking off the container as a Batch job in the third and last part of this series. Disclaimer 1: The model I am talking about here is a batch job on a single instance, NOT a web service with API endpoints, NOT distributed parallel jobs. If you follow this tutorial, the whole process to put your code to a container should not take more than 25 minutes. Disclaimer 2: If this is your first time reading about containers, this post is probably not going to provide the necessary information for understanding how containers work and I would highly recommend you check out some tutorials online before you proceed. an AWS account AWS CLI installed Docker installed, and account setup at DockerHub Python 3 installed To get your code to a container, you need to create a Dockerfile, which tells Docker what you need in your application. A Dockerfile is a text document that contains all the commands a user could call on the command line to assemble an image. (You can build a Docker image from either Dockerfile or docker-compose.yml. If your code can be refactored as a multi-container Docker application, you may want to look into docker compose but now a Dockerfile should suffice.) A Docker image starts with a base image and is built up by read-only layers, with each of them adding some dependencies. In the end, you tell the container how to trigger your model. In the Dockerfile above, I started with the base Python 3.6 stretch image, apt-get updated the system libraries, installed some make and build stuff, checked my python and pip version to make sure they are good, set up my work directory, copied requirements.txt to the container and pip installed all the libraries in it, and finally copied all the other code files to the container, listed all the files to make sure all I need is there and triggered my entrypoint main.py file. This Dockerfile should work for you if your code folder structure is like this. - app-name |-- src |-- main.py |-- other_module.py |-- requirements.txt |-- Dockerfile If your code doesn’t have a main.py or shell script to trigger the model training/inferencing yet, then you may want to refactor your code first. Also remember to freeze the library dependencies into a requirements.txt file with pipreqs path/to/project . I recommend using pipreqs rather than pip freeze because when you run pip freeze > requirements.txt it outputs all the installed packages in that environment whereas pipreqs gives you only the ones actually imported by this project. (Install pipreqs with pip(3) install pipreqs if you don’t have it already) If your code already has an entrypoint, all you need to do is to change the <app- name> to your application’s name and we are ready to build it into an image. There are a lot of best practices to make a Dockerfile smaller and more efficient but most of them are out of the scope for this post. However, a few things you may want to be mindful about are: People say instead of starting with a generic Ubuntu image, use an official base image like Alpine Python instead. Alpine Python is a really small Python Docker image based on Alpine Linux, much smaller than the default docker python images but still has everything needed for the most common python projects. But I have found it extremely difficult to work with especially for installing packages. A Ubuntu base image, on the other hand, will provide more predictable behavior but you need to install all the Python stuff yourself. So I suggest you start with Python 3.6 stretch, which is the official Python image based on Debian 9 (aka stretch). Python stretch comes with the Python environment and pip installed and up to date, all of which you need to figure out how to install if you choose Ubuntu. It’s also very tempting to copy and paste some Dockerfile template posted online especially if this is your first Docker project. But it’s suggested to only install the things you actually need to control the size of the image. If you see a whole bunch of make and build stuff other people installed, try to not include them first and see if your container will work. A smaller image generally means it’s faster to build and deploy. (Another reason you should try my minimalism template above!) Also to keep the image as lean as possible, use .dockerignore which works exactly like .gitignore to ignore files that won’t impact the model. In your Dockerfile, always add your requirements.txt file before copying the source code. That way, when you change your code and re-build the container, Docker will re-use the cached layer up until the installed packages instead of executing the pip install command on every build even if the library dependencies never changed. No one wants to wait a couple of extra minutes just because you added an empty line in your code. If you are interested to learn more about Dockerfile, in appendix I there is a quick summary of a few basic commands we used. Or you can check the Dockerfile documentation here. Now feel free to jump to Step 2 to build a container with the Dockerfile you just created. After you have a Dockerfile ready, it’s time to build a container image. docker build creates an image according to the instructions given in the Dockerfile. All you need to do is to give your image a name (an an optional version tag). $ docker build -t IMAGE_NAME:TAG .$ # or$ docker build -t USERNAME/IMAGE_NAME:TAG . The only difference between the 2 commands is if there is a USERNAME/ before the image name. An image name is made up of slash-separated name components, usually the prefix is the registry hostname. USERNAME/IMAGE_NAME is not a mandatory format for specifying the name of the image in general. But images in Amazon ECR repositories do follow the full REGISTRY/REPOSITORY:TAG naming convention. For example, aws_account_id.dkr.ecr.region.amazonaws.com/my-web-app:latest. A few things are happening in the commands above. First, we told the Docker daemon to fetch the Dockerfile present in the current directory (that’s what the . at the end does). Next, we told the Docker daemon to build the image and give it the specified tag. Tagging has always been very confusing for me. Generally tagging an image is like giving it an alias. It’s the same as assigning an existing image another name to refer to it. It helps with distinguishing versions of your Docker images. It’s not mandatory to specify a tag name. The :latest tag is a default tag when build is run without a specific tag specified. So it’s suggested that you explicitly tag your image after each build if you want to maintain a good version history. $ docker build -t USERNAME/IMAGE_NAME .$ docker tag USERNAME/IMAGE_NAME USERNAME/IMAGE_NAME:1.0$ ...$ docker build -t USERNAME/IMAGE_NAME .$ docker tag USERNAME/IMAGE_NAME USERNAME/IMAGE_NAME:2.0$ ... You can tag an image while building your image with docker build -t USERNAME/IMAGE_NAME:TAG . or explicit tag it like docker tag SOURCE_IMAGE:TAG TARGET_IMAGE:TAG after it was built. Now if you run docker images, you should see an image exists locally whose repository is USERNAME/IMAGE_NAME and tag is TAG . $ docker images I would also recommend you to test your container on your local machine at this point to make sure everything works fine. $ docker run USERNAEM/IMAGE_NAME:TAG Feel free to check appendix II for a quick summary of some basic Docker CLI commands or the official document here. Congratulation! You just baked your model into a container that can be run anywhere Docker is installed. Join me for the second part of this post to configure your AWS environment to meet the prerequisite for scheduling a batch job. FROM starts the Dockerfile. It is a requirement that the Dockerfile must start with the FROM command. Images are created in layers, which means you can use another image as the base image for your own. The FROM command defines your base layer. As arguments, it takes the name of the image. Optionally, you can add the Docker Cloud username of the maintainer and image version, in the format username/imagename:version. RUN is used to build up the image you’re creating. For each RUN command, Docker will run the command then create a new layer of the image. This way you can roll back your image to previous states easily. The syntax for a RUN instruction is to place the full text of the shell command after the RUN(e.g., RUN mkdir /user/local/foo). This will automatically run in a /bin/sh shell. You can define a different shell like this: RUN /bin/bash -c 'mkdir /user/local/foo'. COPY copies local files into the container. CMD defines the commands that will run on the Image at start-up. Unlike a RUN, this does not create a new layer for the Image, but simply runs the command. There can only be one CMD per a Dockerfile/Image. If you need to run multiple commands, the best way to do that is to have the CMD run a script. CMD requires that you tell it where to run the command, unlike RUN. EXPOSE creates a hint for users of an image which ports provide services. It is included in the information which can be retrieved via docker inspect <container-id>. Note: The EXPOSE command does not actually make any ports accessible to the host! Instead, this requires publishing ports by means of the -p flag when using docker run. PUSH pushes your image to a private or cloud registry. Some basic Docker CLI commands include: docker build builds an image from a Dockerfile docker images displays all Docker images on the machine docker run starts a container and runs commands in it docker run options: -p specify ports in host and Docker container -it opens an interactive console -d starts the container in daemon mode (runs in the background) -e sets environment variables docker ps displays all running containers docker rmi removes one or more images docker rm removes one or more containers docker kill kills one or more running containers docker tag tags an image with an alias which can be referenced later docker login logs in to your Docker registry I am a machine learning engineer and I write about productivity and self-development besides tech tutorials. I visited Yellowstone on 4th of July thus the cover image.
[ { "code": null, "e": 528, "s": 171, "text": "As a data scientist, I don’t have a lot of software engineering experience but I have certainly heard a lot of great comments about containers. I have heard about how lightweight they are compared to traditional VMs, how good they are at ensuring a safe consistent environment for your code, and how my devops effort it saves so you can focus on your code." }, { "code": null, "e": 832, "s": 528, "text": "However, when I tried to Dockerize my own model, I soon realized it is not that intuitive. It is not at all as simple as putting RUN in front of your EC2 bootstrap script. I found that inconsistencies and unpredictable behaviors happen quite a lot and it can be frustrating to learn to debug a new tool." }, { "code": null, "e": 1260, "s": 832, "text": "All of these motivated me to create this post with all the code snippets you need to factorize your ML model in Python to a Docker container. I will guide you through installing all the pip packages you need and build your first container image. And in the second part of this post, we will be setting up all the necessary AWS environments and kicking off the container as a Batch job in the third and last part of this series." }, { "code": null, "e": 1531, "s": 1260, "text": "Disclaimer 1: The model I am talking about here is a batch job on a single instance, NOT a web service with API endpoints, NOT distributed parallel jobs. If you follow this tutorial, the whole process to put your code to a container should not take more than 25 minutes." }, { "code": null, "e": 1790, "s": 1531, "text": "Disclaimer 2: If this is your first time reading about containers, this post is probably not going to provide the necessary information for understanding how containers work and I would highly recommend you check out some tutorials online before you proceed." }, { "code": null, "e": 1805, "s": 1790, "text": "an AWS account" }, { "code": null, "e": 1823, "s": 1805, "text": "AWS CLI installed" }, { "code": null, "e": 1872, "s": 1823, "text": "Docker installed, and account setup at DockerHub" }, { "code": null, "e": 1891, "s": 1872, "text": "Python 3 installed" }, { "code": null, "e": 2011, "s": 1891, "text": "To get your code to a container, you need to create a Dockerfile, which tells Docker what you need in your application." }, { "code": null, "e": 2134, "s": 2011, "text": "A Dockerfile is a text document that contains all the commands a user could call on the command line to assemble an image." }, { "code": null, "e": 2361, "s": 2134, "text": "(You can build a Docker image from either Dockerfile or docker-compose.yml. If your code can be refactored as a multi-container Docker application, you may want to look into docker compose but now a Dockerfile should suffice.)" }, { "code": null, "e": 2544, "s": 2361, "text": "A Docker image starts with a base image and is built up by read-only layers, with each of them adding some dependencies. In the end, you tell the container how to trigger your model." }, { "code": null, "e": 3024, "s": 2544, "text": "In the Dockerfile above, I started with the base Python 3.6 stretch image, apt-get updated the system libraries, installed some make and build stuff, checked my python and pip version to make sure they are good, set up my work directory, copied requirements.txt to the container and pip installed all the libraries in it, and finally copied all the other code files to the container, listed all the files to make sure all I need is there and triggered my entrypoint main.py file." }, { "code": null, "e": 3104, "s": 3024, "text": "This Dockerfile should work for you if your code folder structure is like this." }, { "code": null, "e": 3221, "s": 3104, "text": "- app-name |-- src |-- main.py |-- other_module.py |-- requirements.txt |-- Dockerfile" }, { "code": null, "e": 3784, "s": 3221, "text": "If your code doesn’t have a main.py or shell script to trigger the model training/inferencing yet, then you may want to refactor your code first. Also remember to freeze the library dependencies into a requirements.txt file with pipreqs path/to/project . I recommend using pipreqs rather than pip freeze because when you run pip freeze > requirements.txt it outputs all the installed packages in that environment whereas pipreqs gives you only the ones actually imported by this project. (Install pipreqs with pip(3) install pipreqs if you don’t have it already)" }, { "code": null, "e": 3943, "s": 3784, "text": "If your code already has an entrypoint, all you need to do is to change the <app- name> to your application’s name and we are ready to build it into an image." }, { "code": null, "e": 4138, "s": 3943, "text": "There are a lot of best practices to make a Dockerfile smaller and more efficient but most of them are out of the scope for this post. However, a few things you may want to be mindful about are:" }, { "code": null, "e": 4537, "s": 4138, "text": "People say instead of starting with a generic Ubuntu image, use an official base image like Alpine Python instead. Alpine Python is a really small Python Docker image based on Alpine Linux, much smaller than the default docker python images but still has everything needed for the most common python projects. But I have found it extremely difficult to work with especially for installing packages." }, { "code": null, "e": 4671, "s": 4537, "text": "A Ubuntu base image, on the other hand, will provide more predictable behavior but you need to install all the Python stuff yourself." }, { "code": null, "e": 4943, "s": 4671, "text": "So I suggest you start with Python 3.6 stretch, which is the official Python image based on Debian 9 (aka stretch). Python stretch comes with the Python environment and pip installed and up to date, all of which you need to figure out how to install if you choose Ubuntu." }, { "code": null, "e": 5438, "s": 4943, "text": "It’s also very tempting to copy and paste some Dockerfile template posted online especially if this is your first Docker project. But it’s suggested to only install the things you actually need to control the size of the image. If you see a whole bunch of make and build stuff other people installed, try to not include them first and see if your container will work. A smaller image generally means it’s faster to build and deploy. (Another reason you should try my minimalism template above!)" }, { "code": null, "e": 5581, "s": 5438, "text": "Also to keep the image as lean as possible, use .dockerignore which works exactly like .gitignore to ignore files that won’t impact the model." }, { "code": null, "e": 6009, "s": 5581, "text": "In your Dockerfile, always add your requirements.txt file before copying the source code. That way, when you change your code and re-build the container, Docker will re-use the cached layer up until the installed packages instead of executing the pip install command on every build even if the library dependencies never changed. No one wants to wait a couple of extra minutes just because you added an empty line in your code." }, { "code": null, "e": 6187, "s": 6009, "text": "If you are interested to learn more about Dockerfile, in appendix I there is a quick summary of a few basic commands we used. Or you can check the Dockerfile documentation here." }, { "code": null, "e": 6278, "s": 6187, "text": "Now feel free to jump to Step 2 to build a container with the Dockerfile you just created." }, { "code": null, "e": 6514, "s": 6278, "text": "After you have a Dockerfile ready, it’s time to build a container image. docker build creates an image according to the instructions given in the Dockerfile. All you need to do is to give your image a name (an an optional version tag)." }, { "code": null, "e": 6598, "s": 6514, "text": "$ docker build -t IMAGE_NAME:TAG .$ # or$ docker build -t USERNAME/IMAGE_NAME:TAG ." }, { "code": null, "e": 7068, "s": 6598, "text": "The only difference between the 2 commands is if there is a USERNAME/ before the image name. An image name is made up of slash-separated name components, usually the prefix is the registry hostname. USERNAME/IMAGE_NAME is not a mandatory format for specifying the name of the image in general. But images in Amazon ECR repositories do follow the full REGISTRY/REPOSITORY:TAG naming convention. For example, aws_account_id.dkr.ecr.region.amazonaws.com/my-web-app:latest." }, { "code": null, "e": 7118, "s": 7068, "text": "A few things are happening in the commands above." }, { "code": null, "e": 7245, "s": 7118, "text": "First, we told the Docker daemon to fetch the Dockerfile present in the current directory (that’s what the . at the end does)." }, { "code": null, "e": 7564, "s": 7245, "text": "Next, we told the Docker daemon to build the image and give it the specified tag. Tagging has always been very confusing for me. Generally tagging an image is like giving it an alias. It’s the same as assigning an existing image another name to refer to it. It helps with distinguishing versions of your Docker images." }, { "code": null, "e": 7809, "s": 7564, "text": "It’s not mandatory to specify a tag name. The :latest tag is a default tag when build is run without a specific tag specified. So it’s suggested that you explicitly tag your image after each build if you want to maintain a good version history." }, { "code": null, "e": 8010, "s": 7809, "text": "$ docker build -t USERNAME/IMAGE_NAME .$ docker tag USERNAME/IMAGE_NAME USERNAME/IMAGE_NAME:1.0$ ...$ docker build -t USERNAME/IMAGE_NAME .$ docker tag USERNAME/IMAGE_NAME USERNAME/IMAGE_NAME:2.0$ ..." }, { "code": null, "e": 8193, "s": 8010, "text": "You can tag an image while building your image with docker build -t USERNAME/IMAGE_NAME:TAG . or explicit tag it like docker tag SOURCE_IMAGE:TAG TARGET_IMAGE:TAG after it was built." }, { "code": null, "e": 8319, "s": 8193, "text": "Now if you run docker images, you should see an image exists locally whose repository is USERNAME/IMAGE_NAME and tag is TAG ." }, { "code": null, "e": 8335, "s": 8319, "text": "$ docker images" }, { "code": null, "e": 8457, "s": 8335, "text": "I would also recommend you to test your container on your local machine at this point to make sure everything works fine." }, { "code": null, "e": 8494, "s": 8457, "text": "$ docker run USERNAEM/IMAGE_NAME:TAG" }, { "code": null, "e": 8610, "s": 8494, "text": "Feel free to check appendix II for a quick summary of some basic Docker CLI commands or the official document here." }, { "code": null, "e": 8843, "s": 8610, "text": "Congratulation! You just baked your model into a container that can be run anywhere Docker is installed. Join me for the second part of this post to configure your AWS environment to meet the prerequisite for scheduling a batch job." }, { "code": null, "e": 9262, "s": 8843, "text": "FROM starts the Dockerfile. It is a requirement that the Dockerfile must start with the FROM command. Images are created in layers, which means you can use another image as the base image for your own. The FROM command defines your base layer. As arguments, it takes the name of the image. Optionally, you can add the Docker Cloud username of the maintainer and image version, in the format username/imagename:version." }, { "code": null, "e": 9728, "s": 9262, "text": "RUN is used to build up the image you’re creating. For each RUN command, Docker will run the command then create a new layer of the image. This way you can roll back your image to previous states easily. The syntax for a RUN instruction is to place the full text of the shell command after the RUN(e.g., RUN mkdir /user/local/foo). This will automatically run in a /bin/sh shell. You can define a different shell like this: RUN /bin/bash -c 'mkdir /user/local/foo'." }, { "code": null, "e": 9772, "s": 9728, "text": "COPY copies local files into the container." }, { "code": null, "e": 10141, "s": 9772, "text": "CMD defines the commands that will run on the Image at start-up. Unlike a RUN, this does not create a new layer for the Image, but simply runs the command. There can only be one CMD per a Dockerfile/Image. If you need to run multiple commands, the best way to do that is to have the CMD run a script. CMD requires that you tell it where to run the command, unlike RUN." }, { "code": null, "e": 10307, "s": 10141, "text": "EXPOSE creates a hint for users of an image which ports provide services. It is included in the information which can be retrieved via docker inspect <container-id>." }, { "code": null, "e": 10476, "s": 10307, "text": "Note: The EXPOSE command does not actually make any ports accessible to the host! Instead, this requires publishing ports by means of the -p flag when using docker run." }, { "code": null, "e": 10531, "s": 10476, "text": "PUSH pushes your image to a private or cloud registry." }, { "code": null, "e": 10571, "s": 10531, "text": "Some basic Docker CLI commands include:" }, { "code": null, "e": 10618, "s": 10571, "text": "docker build builds an image from a Dockerfile" }, { "code": null, "e": 10674, "s": 10618, "text": "docker images displays all Docker images on the machine" }, { "code": null, "e": 10728, "s": 10674, "text": "docker run starts a container and runs commands in it" }, { "code": null, "e": 10748, "s": 10728, "text": "docker run options:" }, { "code": null, "e": 10794, "s": 10748, "text": "-p specify ports in host and Docker container" }, { "code": null, "e": 10827, "s": 10794, "text": "-it opens an interactive console" }, { "code": null, "e": 10891, "s": 10827, "text": "-d starts the container in daemon mode (runs in the background)" }, { "code": null, "e": 10921, "s": 10891, "text": "-e sets environment variables" }, { "code": null, "e": 10963, "s": 10921, "text": "docker ps displays all running containers" }, { "code": null, "e": 11001, "s": 10963, "text": "docker rmi removes one or more images" }, { "code": null, "e": 11042, "s": 11001, "text": "docker rm removes one or more containers" }, { "code": null, "e": 11091, "s": 11042, "text": "docker kill kills one or more running containers" }, { "code": null, "e": 11160, "s": 11091, "text": "docker tag tags an image with an alias which can be referenced later" }, { "code": null, "e": 11205, "s": 11160, "text": "docker login logs in to your Docker registry" } ]
How do you dynamically add Python modules to a package while your programming is running?
To dynamically import Python modules, you can use the importlib package's import_module(moduleName) function. You need to have moduleName as a string. For example, >>> from importlib import import_module >>> moduleName = "os" >>> globals()[moduleName] = import_module(moduleName) If you want to dynamically import a list of modules, you can even call this from a for loop. For example, >>> import importlib >>> modnames = ["os", "sys", "math"] >>> for lib in modnames: ... globals()[lib] = importlib.import_module(lib) The globals() call returns a dict. We can set the lib key for each library as the object returned to us on import of a module. If you've imported a package and now want to dynamically import one of its module, you can still use the same function and get the expected result. The module you want to import should have its full name and not just the module name. For example, >>> import importlib >>> pack = 'datetime' >>> mod = 'date' >>> globals()[pack] = importlib.import_module(pack) >>> globals()[pack + '.' + mod] = importlib.import_module(pack + '.' + mod)
[ { "code": null, "e": 1226, "s": 1062, "text": "To dynamically import Python modules, you can use the importlib package's import_module(moduleName) function. You need to have moduleName as a string. For example," }, { "code": null, "e": 1342, "s": 1226, "text": ">>> from importlib import import_module\n>>> moduleName = \"os\"\n>>> globals()[moduleName] = import_module(moduleName)" }, { "code": null, "e": 1448, "s": 1342, "text": "If you want to dynamically import a list of modules, you can even call this from a for loop. For example," }, { "code": null, "e": 1585, "s": 1448, "text": ">>> import importlib\n>>> modnames = [\"os\", \"sys\", \"math\"]\n>>> for lib in modnames:\n... globals()[lib] = importlib.import_module(lib)" }, { "code": null, "e": 1712, "s": 1585, "text": "The globals() call returns a dict. We can set the lib key for each library as the object returned to us on import of a module." }, { "code": null, "e": 1959, "s": 1712, "text": "If you've imported a package and now want to dynamically import one of its module, you can still use the same function and get the expected result. The module you want to import should have its full name and not just the module name. For example," }, { "code": null, "e": 2147, "s": 1959, "text": ">>> import importlib\n>>> pack = 'datetime'\n>>> mod = 'date'\n>>> globals()[pack] = importlib.import_module(pack)\n>>> globals()[pack + '.' + mod] = importlib.import_module(pack + '.' + mod)" } ]
Linear Algebra for Machine Learning: Solve a System of Linear Equations | by Khuyen Tran | Towards Data Science
Let’s start with the common plot in data science: Scatter plot The plot above represents the correlation between the diameter and the height of the tree. Each dot is a sample of a tree. Our task is to find the best fit line to predict the height provided the diameter. How can we do that? That is when Linear Algebra is needed. Linear regression is an example of linear systems of equations. Linear Algebra is about working on linear systems of equations. Rather than working with scalars, we start working with matrices and vectors. Linear Algebra is the key to understanding the calculus and statistics you need in machine learning. If you can understand machine learning methods at the level of vectors and matrices, you will improve your intuition for how and when they work. The better linear algebra will lift your game across the board. And what is the best way to understand linear algebra? Implement it. There are 2 methods to solve a system of linear equations: direct methods and iterative methods. In this article, we will use the direct methods, in particular, Gauss-method. Since most often time we work with data with many features (or variables). We will make our system of linear equations more general by working with a 3-dimensional data instead. Let’s generate an example for the plot above: where the coefficients of x_0, x_1, and x_2 and the corresponding values 8, 4, 5 are the samples of points in the plot. The equations can be split into matrices A, x, and b where A and b are the matrices of known constants, x is the vector of unknown variables. A = np.array([[2, 1, 5], [4, 4, -4], [1, 3, 1]])b= np.array([8,4,5]) Concatenate matrix A and b to get n = A.shape[0] C=np.c_[A,b.reshape(-1,1)] Now we are ready to tackle our problems with 2 steps: Apply Gaussian Elimination to reduce the matrix above to triangular matrix Apply Gaussian Elimination to reduce the matrix above to triangular matrix which could be represented by the equation: 2. Apply backward substitution to obtain the result Let’s start with the first step To obtain this matrix: the idea is simple: We start with the pivot value in the first row and first column: row =0, column = 0 Find the maximum absolute value of the column of the pivot. If all the values in that column are 0, we stop. Else, we exchange E_0 and E_1 Next, apply equivalent transformations to convert all the entries below the pivot to 0 by: Find the ratio between element j,i and pivot i,i (.i.e, 2/4 = 1/2).Multiply all the elements in E0 with 1/2. Subtract all the elements in row 1 by 1/2 E0 (i.e, 2-(4*1/2)=2–2 =0) Find the ratio between element j,i and pivot i,i (.i.e, 2/4 = 1/2). Multiply all the elements in E0 with 1/2. Subtract all the elements in row 1 by 1/2 E0 (i.e, 2-(4*1/2)=2–2 =0) #rowfor j in range(i+1, n): c = C[j,i]/C[i,i] C[j,:] = C[j,:] - c*C[i,:] After each column is simplified, we proceed to the next column to the right. Repeat the procedure: Pivot: row = 1, column = 1. Maximum absolute value: 2 in row 2. Then, permute E_1 and E_2 Applying the equivalent transformation to get all the entries below the pivot converted to 0 Put everything together Nice! Now we have a system of equations: Once we get here, this system of equation is incredibly easy to solve using backsubstitution From Gaussian Elimination, we obtain a triangular matrix The idea is to solve the system of equations above by solving from the bottom up. Use the value obtained from the last equation to find the other values Start with row 3. Divided 8 by 8 to get the value of x_3. X[n-1] = T[n-1,n]/T[n-1,n-1] Now in the second row, we have: x_2 could be solved easily by Repeat with x1 Thus, in general, backsubstution can be represented as: Awesome! We obtain a solution as we predict. To make sure this is correct when working with a larger matrix, we can use the built-in function in NumPy >>> np.linalg.solve(A,b)array([1., 1., 1.]) What we get is a vector of solutions where each element corresponding to x_0, x_1, x_2 Congratulation on getting this far! I hope this article helps you understand what is linear algebra and one of the mechanisms of solving a system of linear equations. I try to make this article understandable as much as possible. But I understand that this could be challenging if you are not familiar with linear algebra. That is okay! One step at a time. The more you are exposed to linear algebra, the more you will understand it. You could play and experiment with the codes above in my Github. I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter. Star this repo if you want to check out the codes for all of the articles I have written. Follow me on Medium to stay informed with my latest data science articles like these:
[ { "code": null, "e": 235, "s": 172, "text": "Let’s start with the common plot in data science: Scatter plot" }, { "code": null, "e": 441, "s": 235, "text": "The plot above represents the correlation between the diameter and the height of the tree. Each dot is a sample of a tree. Our task is to find the best fit line to predict the height provided the diameter." }, { "code": null, "e": 500, "s": 441, "text": "How can we do that? That is when Linear Algebra is needed." }, { "code": null, "e": 706, "s": 500, "text": "Linear regression is an example of linear systems of equations. Linear Algebra is about working on linear systems of equations. Rather than working with scalars, we start working with matrices and vectors." }, { "code": null, "e": 1016, "s": 706, "text": "Linear Algebra is the key to understanding the calculus and statistics you need in machine learning. If you can understand machine learning methods at the level of vectors and matrices, you will improve your intuition for how and when they work. The better linear algebra will lift your game across the board." }, { "code": null, "e": 1260, "s": 1016, "text": "And what is the best way to understand linear algebra? Implement it. There are 2 methods to solve a system of linear equations: direct methods and iterative methods. In this article, we will use the direct methods, in particular, Gauss-method." }, { "code": null, "e": 1438, "s": 1260, "text": "Since most often time we work with data with many features (or variables). We will make our system of linear equations more general by working with a 3-dimensional data instead." }, { "code": null, "e": 1484, "s": 1438, "text": "Let’s generate an example for the plot above:" }, { "code": null, "e": 1657, "s": 1484, "text": "where the coefficients of x_0, x_1, and x_2 and the corresponding values 8, 4, 5 are the samples of points in the plot. The equations can be split into matrices A, x, and b" }, { "code": null, "e": 1746, "s": 1657, "text": "where A and b are the matrices of known constants, x is the vector of unknown variables." }, { "code": null, "e": 1837, "s": 1746, "text": "A = np.array([[2, 1, 5], [4, 4, -4], [1, 3, 1]])b= np.array([8,4,5])" }, { "code": null, "e": 1871, "s": 1837, "text": "Concatenate matrix A and b to get" }, { "code": null, "e": 1916, "s": 1871, "text": "n = A.shape[0] C=np.c_[A,b.reshape(-1,1)]" }, { "code": null, "e": 1970, "s": 1916, "text": "Now we are ready to tackle our problems with 2 steps:" }, { "code": null, "e": 2045, "s": 1970, "text": "Apply Gaussian Elimination to reduce the matrix above to triangular matrix" }, { "code": null, "e": 2120, "s": 2045, "text": "Apply Gaussian Elimination to reduce the matrix above to triangular matrix" }, { "code": null, "e": 2164, "s": 2120, "text": "which could be represented by the equation:" }, { "code": null, "e": 2216, "s": 2164, "text": "2. Apply backward substitution to obtain the result" }, { "code": null, "e": 2248, "s": 2216, "text": "Let’s start with the first step" }, { "code": null, "e": 2271, "s": 2248, "text": "To obtain this matrix:" }, { "code": null, "e": 2291, "s": 2271, "text": "the idea is simple:" }, { "code": null, "e": 2375, "s": 2291, "text": "We start with the pivot value in the first row and first column: row =0, column = 0" }, { "code": null, "e": 2484, "s": 2375, "text": "Find the maximum absolute value of the column of the pivot. If all the values in that column are 0, we stop." }, { "code": null, "e": 2514, "s": 2484, "text": "Else, we exchange E_0 and E_1" }, { "code": null, "e": 2605, "s": 2514, "text": "Next, apply equivalent transformations to convert all the entries below the pivot to 0 by:" }, { "code": null, "e": 2783, "s": 2605, "text": "Find the ratio between element j,i and pivot i,i (.i.e, 2/4 = 1/2).Multiply all the elements in E0 with 1/2. Subtract all the elements in row 1 by 1/2 E0 (i.e, 2-(4*1/2)=2–2 =0)" }, { "code": null, "e": 2851, "s": 2783, "text": "Find the ratio between element j,i and pivot i,i (.i.e, 2/4 = 1/2)." }, { "code": null, "e": 2962, "s": 2851, "text": "Multiply all the elements in E0 with 1/2. Subtract all the elements in row 1 by 1/2 E0 (i.e, 2-(4*1/2)=2–2 =0)" }, { "code": null, "e": 3053, "s": 2962, "text": "#rowfor j in range(i+1, n): c = C[j,i]/C[i,i] C[j,:] = C[j,:] - c*C[i,:]" }, { "code": null, "e": 3130, "s": 3053, "text": "After each column is simplified, we proceed to the next column to the right." }, { "code": null, "e": 3152, "s": 3130, "text": "Repeat the procedure:" }, { "code": null, "e": 3242, "s": 3152, "text": "Pivot: row = 1, column = 1. Maximum absolute value: 2 in row 2. Then, permute E_1 and E_2" }, { "code": null, "e": 3335, "s": 3242, "text": "Applying the equivalent transformation to get all the entries below the pivot converted to 0" }, { "code": null, "e": 3359, "s": 3335, "text": "Put everything together" }, { "code": null, "e": 3400, "s": 3359, "text": "Nice! Now we have a system of equations:" }, { "code": null, "e": 3493, "s": 3400, "text": "Once we get here, this system of equation is incredibly easy to solve using backsubstitution" }, { "code": null, "e": 3550, "s": 3493, "text": "From Gaussian Elimination, we obtain a triangular matrix" }, { "code": null, "e": 3703, "s": 3550, "text": "The idea is to solve the system of equations above by solving from the bottom up. Use the value obtained from the last equation to find the other values" }, { "code": null, "e": 3761, "s": 3703, "text": "Start with row 3. Divided 8 by 8 to get the value of x_3." }, { "code": null, "e": 3790, "s": 3761, "text": "X[n-1] = T[n-1,n]/T[n-1,n-1]" }, { "code": null, "e": 3822, "s": 3790, "text": "Now in the second row, we have:" }, { "code": null, "e": 3852, "s": 3822, "text": "x_2 could be solved easily by" }, { "code": null, "e": 3867, "s": 3852, "text": "Repeat with x1" }, { "code": null, "e": 3923, "s": 3867, "text": "Thus, in general, backsubstution can be represented as:" }, { "code": null, "e": 4074, "s": 3923, "text": "Awesome! We obtain a solution as we predict. To make sure this is correct when working with a larger matrix, we can use the built-in function in NumPy" }, { "code": null, "e": 4118, "s": 4074, "text": ">>> np.linalg.solve(A,b)array([1., 1., 1.])" }, { "code": null, "e": 4205, "s": 4118, "text": "What we get is a vector of solutions where each element corresponding to x_0, x_1, x_2" }, { "code": null, "e": 4639, "s": 4205, "text": "Congratulation on getting this far! I hope this article helps you understand what is linear algebra and one of the mechanisms of solving a system of linear equations. I try to make this article understandable as much as possible. But I understand that this could be challenging if you are not familiar with linear algebra. That is okay! One step at a time. The more you are exposed to linear algebra, the more you will understand it." }, { "code": null, "e": 4704, "s": 4639, "text": "You could play and experiment with the codes above in my Github." }, { "code": null, "e": 4864, "s": 4704, "text": "I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter." } ]
How to create a "section counter" with CSS?
To create a section counter with CSS, the code is as follows − Live Demo <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/fontawesome.min.css"> <style> * { box-sizing: border-box; } body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif } .section { float: left; width: 25%; padding: 0 5px; } .sectionContainer {margin: 0 -5px;} .sectionContainer:after { content: ""; display: table; clear: both; } @media screen and (max-width: 600px) { .section { width: 100%; display: block; margin-bottom: 10px; } } .sectionCard { box-shadow: 0 4px 8px 0 rgb(127, 16, 172); padding: 16px; text-align: center; background-color: rgb(127, 16, 172); color: rgb(255, 255, 255); } .fa {font-size:50px;} </style> </head> <body> <h1>Responsive Section Counter Example</h1> <br> <div class="sectionContainer"> <div class="section"> <div class="sectionCard"> <p><i class="fa fa-mobile" aria-hidden="true"></i></p> <h3>100000+</h3> <p>Downloads</p> </div> </div> <div class="section"> <div class="sectionCard"> <p><i class="fa fa-globe" aria-hidden="true"></i></p> <h3>5000+</h3> <p>Outlets over the globe</p> </div> </div> <div class="section"> <div class="sectionCard"> <p><i class="fa fa-bar-chart" aria-hidden="true"></i> </p> <h3>Top Performer</h3> <p>In past 5 years</p> </div> </div> <div class="section"> <div class="sectionCard"> <p><i class="fa fa-handshake-o" aria-hidden="true"></i></p> <h3>3000+</h3> <p>Partners</p> </div> </div> </div> </body> </html> The above code will produce the following output − On resizing the screen −
[ { "code": null, "e": 1125, "s": 1062, "text": "To create a section counter with CSS, the code is as follows −" }, { "code": null, "e": 1136, "s": 1125, "text": " Live Demo" }, { "code": null, "e": 2819, "s": 1136, "text": "<!DOCTYPE html>\n<html>\n<head>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/fontawesome.min.css\">\n<style>\n * {\n box-sizing: border-box;\n }\n body {\n font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif\n }\n .section {\n float: left;\n width: 25%;\n padding: 0 5px;\n }\n .sectionContainer {margin: 0 -5px;}\n .sectionContainer:after {\n content: \"\";\n display: table;\n clear: both;\n }\n @media screen and (max-width: 600px) {\n .section {\n width: 100%;\n display: block;\n margin-bottom: 10px;\n }\n }\n .sectionCard {\n box-shadow: 0 4px 8px 0 rgb(127, 16, 172);\n padding: 16px;\n text-align: center;\n background-color: rgb(127, 16, 172);\n color: rgb(255, 255, 255);\n }\n .fa {font-size:50px;}\n</style>\n</head>\n<body>\n<h1>Responsive Section Counter Example</h1>\n<br>\n<div class=\"sectionContainer\">\n<div class=\"section\">\n<div class=\"sectionCard\">\n<p><i class=\"fa fa-mobile\" aria-hidden=\"true\"></i></p>\n<h3>100000+</h3>\n<p>Downloads</p>\n</div>\n</div>\n<div class=\"section\">\n<div class=\"sectionCard\">\n<p><i class=\"fa fa-globe\" aria-hidden=\"true\"></i></p>\n<h3>5000+</h3>\n<p>Outlets over the globe</p>\n</div>\n</div>\n<div class=\"section\">\n<div class=\"sectionCard\">\n<p><i class=\"fa fa-bar-chart\" aria-hidden=\"true\"></i> </p>\n<h3>Top Performer</h3>\n<p>In past 5 years</p>\n</div>\n</div>\n<div class=\"section\">\n<div class=\"sectionCard\">\n<p><i class=\"fa fa-handshake-o\" aria-hidden=\"true\"></i></p>\n<h3>3000+</h3>\n<p>Partners</p>\n</div>\n</div>\n</div>\n</body>\n</html>" }, { "code": null, "e": 2870, "s": 2819, "text": "The above code will produce the following output −" }, { "code": null, "e": 2895, "s": 2870, "text": "On resizing the screen −" } ]
PL/SQL - GOTO Statement
A GOTO statement in PL/SQL programming language provides an unconditional jump from the GOTO to a labeled statement in the same subprogram. NOTE − The use of GOTO statement is not recommended in any programming language because it makes it difficult to trace the control flow of a program, making the program hard to understand and hard to modify. Any program that uses a GOTO can be rewritten so that it doesn't need the GOTO. The syntax for a GOTO statement in PL/SQL is as follows − GOTO label; .. .. << label >> statement; DECLARE a number(2) := 10; BEGIN <<loopstart>> -- while loop execution WHILE a < 20 LOOP dbms_output.put_line ('value of a: ' || a); a := a + 1; IF a = 15 THEN a := a + 1; GOTO loopstart; END IF; END LOOP; END; / When the above code is executed at the SQL prompt, it produces the following result − value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 16 value of a: 17 value of a: 18 value of a: 19 PL/SQL procedure successfully completed. GOTO Statement in PL/SQL imposes the following restrictions − A GOTO statement cannot branch into an IF statement, CASE statement, LOOP statement or sub-block. A GOTO statement cannot branch into an IF statement, CASE statement, LOOP statement or sub-block. A GOTO statement cannot branch from one IF statement clause to another or from one CASE statement WHEN clause to another. A GOTO statement cannot branch from one IF statement clause to another or from one CASE statement WHEN clause to another. A GOTO statement cannot branch from an outer block into a sub-block (i.e., an inner BEGIN-END block). A GOTO statement cannot branch from an outer block into a sub-block (i.e., an inner BEGIN-END block). A GOTO statement cannot branch out of a subprogram. To end a subprogram early, either use the RETURN statement or have GOTO branch to a place right before the end of the subprogram. A GOTO statement cannot branch out of a subprogram. To end a subprogram early, either use the RETURN statement or have GOTO branch to a place right before the end of the subprogram. A GOTO statement cannot branch from an exception handler back into the current BEGIN-END block. However, a GOTO statement can branch from an exception handler into an enclosing block. A GOTO statement cannot branch from an exception handler back into the current BEGIN-END block. However, a GOTO statement can branch from an exception handler into an enclosing block. Print Add Notes Bookmark this page
[ { "code": null, "e": 2205, "s": 2065, "text": "A GOTO statement in PL/SQL programming language provides an unconditional jump from the GOTO to a labeled statement in the same subprogram." }, { "code": null, "e": 2493, "s": 2205, "text": "NOTE − The use of GOTO statement is not recommended in any programming language because it makes it difficult to trace the control flow of a program, making the program hard to understand and hard to modify. Any program that uses a GOTO can be rewritten so that it doesn't need the GOTO." }, { "code": null, "e": 2551, "s": 2493, "text": "The syntax for a GOTO statement in PL/SQL is as follows −" }, { "code": null, "e": 2593, "s": 2551, "text": "GOTO label;\n..\n..\n<< label >>\nstatement;\n" }, { "code": null, "e": 2874, "s": 2593, "text": "DECLARE \n a number(2) := 10; \nBEGIN \n <<loopstart>> \n -- while loop execution \n WHILE a < 20 LOOP\n dbms_output.put_line ('value of a: ' || a); \n a := a + 1; \n IF a = 15 THEN \n a := a + 1; \n GOTO loopstart; \n END IF; \n END LOOP; \nEND; \n/" }, { "code": null, "e": 2960, "s": 2874, "text": "When the above code is executed at the SQL prompt, it produces the following result −" }, { "code": null, "e": 3148, "s": 2960, "text": "value of a: 10 \nvalue of a: 11 \nvalue of a: 12 \nvalue of a: 13 \nvalue of a: 14 \nvalue of a: 16 \nvalue of a: 17 \nvalue of a: 18 \nvalue of a: 19 \n\nPL/SQL procedure successfully completed.\n" }, { "code": null, "e": 3210, "s": 3148, "text": "GOTO Statement in PL/SQL imposes the following restrictions −" }, { "code": null, "e": 3308, "s": 3210, "text": "A GOTO statement cannot branch into an IF statement, CASE statement, LOOP statement or sub-block." }, { "code": null, "e": 3406, "s": 3308, "text": "A GOTO statement cannot branch into an IF statement, CASE statement, LOOP statement or sub-block." }, { "code": null, "e": 3528, "s": 3406, "text": "A GOTO statement cannot branch from one IF statement clause to another or from one CASE statement WHEN clause to another." }, { "code": null, "e": 3650, "s": 3528, "text": "A GOTO statement cannot branch from one IF statement clause to another or from one CASE statement WHEN clause to another." }, { "code": null, "e": 3752, "s": 3650, "text": "A GOTO statement cannot branch from an outer block into a sub-block (i.e., an inner BEGIN-END block)." }, { "code": null, "e": 3854, "s": 3752, "text": "A GOTO statement cannot branch from an outer block into a sub-block (i.e., an inner BEGIN-END block)." }, { "code": null, "e": 4036, "s": 3854, "text": "A GOTO statement cannot branch out of a subprogram. To end a subprogram early, either use the RETURN statement or have GOTO branch to a place right before the end of the subprogram." }, { "code": null, "e": 4218, "s": 4036, "text": "A GOTO statement cannot branch out of a subprogram. To end a subprogram early, either use the RETURN statement or have GOTO branch to a place right before the end of the subprogram." }, { "code": null, "e": 4402, "s": 4218, "text": "A GOTO statement cannot branch from an exception handler back into the current BEGIN-END block. However, a GOTO statement can branch from an exception handler into an enclosing block." }, { "code": null, "e": 4586, "s": 4402, "text": "A GOTO statement cannot branch from an exception handler back into the current BEGIN-END block. However, a GOTO statement can branch from an exception handler into an enclosing block." }, { "code": null, "e": 4593, "s": 4586, "text": " Print" }, { "code": null, "e": 4604, "s": 4593, "text": " Add Notes" } ]
Amazon Interview Experience - GeeksforGeeks
01 Sep, 2021 I have applied to Amazon via LinkedIn. Finally, I got a mail stating that I can give my online test on Hacker-rank platform. Round 1: It is an online round on hacker-rank. Two coding questions were asked. We need to write time complexity and space complexity as well. Optimizing Alexa SuggestionsIn this question 1 list is given with x and y coordinates and an integer X is given. We need to find X restaurants near the customer from location (0,0).Example 1 : location:[[1,2],[3,4],[1,-1]], X=2 O/P: [[1,-1],[1,2]]Device Application PairsIn this question device capacity, foregroundAppList and backgroundAppList is given. We need to find the foreground and background pair which optimally utilizes the device capacity. List has set of pair where first integer represents id and second integer represents amount of memory required.Example 1 : capacity = 7, foregroundAppList:[[1,2],[2,4],[3,6]], backgroundAppList:[[1,2]] O/P:[[2,1]] Example 2 : capacity = 10, foregroundAppList:[[1,3],[2,5],[3,7],[4,10]], backgroundAppList:[[1,2],[2,3],[3,4],[4,5]] O/P:[[2,4],[3,2]] Optimizing Alexa SuggestionsIn this question 1 list is given with x and y coordinates and an integer X is given. We need to find X restaurants near the customer from location (0,0).Example 1 : location:[[1,2],[3,4],[1,-1]], X=2 O/P: [[1,-1],[1,2]] In this question 1 list is given with x and y coordinates and an integer X is given. We need to find X restaurants near the customer from location (0,0). Example 1 : location:[[1,2],[3,4],[1,-1]], X=2 O/P: [[1,-1],[1,2]] Device Application PairsIn this question device capacity, foregroundAppList and backgroundAppList is given. We need to find the foreground and background pair which optimally utilizes the device capacity. List has set of pair where first integer represents id and second integer represents amount of memory required.Example 1 : capacity = 7, foregroundAppList:[[1,2],[2,4],[3,6]], backgroundAppList:[[1,2]] O/P:[[2,1]] Example 2 : capacity = 10, foregroundAppList:[[1,3],[2,5],[3,7],[4,10]], backgroundAppList:[[1,2],[2,3],[3,4],[4,5]] O/P:[[2,4],[3,2]] In this question device capacity, foregroundAppList and backgroundAppList is given. We need to find the foreground and background pair which optimally utilizes the device capacity. List has set of pair where first integer represents id and second integer represents amount of memory required. Example 1 : capacity = 7, foregroundAppList:[[1,2],[2,4],[3,6]], backgroundAppList:[[1,2]] O/P:[[2,1]] Example 2 : capacity = 10, foregroundAppList:[[1,3],[2,5],[3,7],[4,10]], backgroundAppList:[[1,2],[2,3],[3,4],[4,5]] O/P:[[2,4],[3,2]] After 15-20 days I got call from HR for amazon Chime Interview. There will be 3 rounds on that day only. The rounds were held in next week. Round 2: It is taken by Manager. There is discussion on project, leadership principles and Java concepts. Incident when you deep dive, etc Process and threads How google.com works when we type it in URL. Multiprocessing, multitasking, multithreading, etc Round 3: It is taken by SDE-1. Two codes were asked. I was able to solve both. https://www.geeksforgeeks.org/iterative-letter-combinations-of-a-phone-number/https://www.geeksforgeeks.org/minimum-steps-reach-target-knight/ https://www.geeksforgeeks.org/iterative-letter-combinations-of-a-phone-number/ https://www.geeksforgeeks.org/minimum-steps-reach-target-knight/ Round 4: It was taken by SDE-2. Two codes were asked. I was able to solve both. A question similar to: https://practice.geeksforgeeks.org/problems/kth-largest-element-in-a-stream2220/1https://www.geeksforgeeks.org/unique-paths-in-a-grid-with-obstacles/A question based on dp to find ways to move from one cell to another. A question similar to: https://practice.geeksforgeeks.org/problems/kth-largest-element-in-a-stream2220/1 https://www.geeksforgeeks.org/unique-paths-in-a-grid-with-obstacles/ A question based on dp to find ways to move from one cell to another. After 3 weeks I got reply that I will have bar raiser round after 1 week. Amazon Marketing Interview Experiences Amazon Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Amazon Interview Experience Amazon Interview Experience for SDE-1 (On-Campus) Microsoft Interview Experience for Internship (Via Engage) Directi Interview | Set 7 (Programming Questions) Zoho Interview | Set 3 (Off-Campus) Amazon Interview Experience for SDE-1 Amazon Interview Experience for SDE-1 (Off-Campus) Difference between ANN, CNN and RNN Amazon Interview Experience (Off-Campus) 2022 Amazon Interview Experience for SDE-1(Off-Campus)
[ { "code": null, "e": 25210, "s": 25182, "text": "\n01 Sep, 2021" }, { "code": null, "e": 25335, "s": 25210, "text": "I have applied to Amazon via LinkedIn. Finally, I got a mail stating that I can give my online test on Hacker-rank platform." }, { "code": null, "e": 25478, "s": 25335, "text": "Round 1: It is an online round on hacker-rank. Two coding questions were asked. We need to write time complexity and space complexity as well." }, { "code": null, "e": 26292, "s": 25478, "text": "Optimizing Alexa SuggestionsIn this question 1 list is given with x and y coordinates and an integer X is given. We need to find X restaurants near the customer from location (0,0).Example 1 : \nlocation:[[1,2],[3,4],[1,-1]],\nX=2 \nO/P: [[1,-1],[1,2]]Device Application PairsIn this question device capacity, foregroundAppList and backgroundAppList is given. We need to find the foreground and background pair which optimally utilizes the device capacity. List has set of pair where first integer represents id and second integer represents amount of memory required.Example 1 :\ncapacity = 7, \nforegroundAppList:[[1,2],[2,4],[3,6]], \nbackgroundAppList:[[1,2]] \nO/P:[[2,1]]\nExample 2 : \ncapacity = 10, \nforegroundAppList:[[1,3],[2,5],[3,7],[4,10]], \nbackgroundAppList:[[1,2],[2,3],[3,4],[4,5]] \nO/P:[[2,4],[3,2]]" }, { "code": null, "e": 26542, "s": 26292, "text": "Optimizing Alexa SuggestionsIn this question 1 list is given with x and y coordinates and an integer X is given. We need to find X restaurants near the customer from location (0,0).Example 1 : \nlocation:[[1,2],[3,4],[1,-1]],\nX=2 \nO/P: [[1,-1],[1,2]]" }, { "code": null, "e": 26696, "s": 26542, "text": "In this question 1 list is given with x and y coordinates and an integer X is given. We need to find X restaurants near the customer from location (0,0)." }, { "code": null, "e": 26765, "s": 26696, "text": "Example 1 : \nlocation:[[1,2],[3,4],[1,-1]],\nX=2 \nO/P: [[1,-1],[1,2]]" }, { "code": null, "e": 27330, "s": 26765, "text": "Device Application PairsIn this question device capacity, foregroundAppList and backgroundAppList is given. We need to find the foreground and background pair which optimally utilizes the device capacity. List has set of pair where first integer represents id and second integer represents amount of memory required.Example 1 :\ncapacity = 7, \nforegroundAppList:[[1,2],[2,4],[3,6]], \nbackgroundAppList:[[1,2]] \nO/P:[[2,1]]\nExample 2 : \ncapacity = 10, \nforegroundAppList:[[1,3],[2,5],[3,7],[4,10]], \nbackgroundAppList:[[1,2],[2,3],[3,4],[4,5]] \nO/P:[[2,4],[3,2]]" }, { "code": null, "e": 27623, "s": 27330, "text": "In this question device capacity, foregroundAppList and backgroundAppList is given. We need to find the foreground and background pair which optimally utilizes the device capacity. List has set of pair where first integer represents id and second integer represents amount of memory required." }, { "code": null, "e": 27872, "s": 27623, "text": "Example 1 :\ncapacity = 7, \nforegroundAppList:[[1,2],[2,4],[3,6]], \nbackgroundAppList:[[1,2]] \nO/P:[[2,1]]\nExample 2 : \ncapacity = 10, \nforegroundAppList:[[1,3],[2,5],[3,7],[4,10]], \nbackgroundAppList:[[1,2],[2,3],[3,4],[4,5]] \nO/P:[[2,4],[3,2]]" }, { "code": null, "e": 28012, "s": 27872, "text": "After 15-20 days I got call from HR for amazon Chime Interview. There will be 3 rounds on that day only. The rounds were held in next week." }, { "code": null, "e": 28046, "s": 28012, "text": "Round 2: It is taken by Manager. " }, { "code": null, "e": 28119, "s": 28046, "text": "There is discussion on project, leadership principles and Java concepts." }, { "code": null, "e": 28152, "s": 28119, "text": "Incident when you deep dive, etc" }, { "code": null, "e": 28172, "s": 28152, "text": "Process and threads" }, { "code": null, "e": 28217, "s": 28172, "text": "How google.com works when we type it in URL." }, { "code": null, "e": 28268, "s": 28217, "text": "Multiprocessing, multitasking, multithreading, etc" }, { "code": null, "e": 28347, "s": 28268, "text": "Round 3: It is taken by SDE-1. Two codes were asked. I was able to solve both." }, { "code": null, "e": 28490, "s": 28347, "text": "https://www.geeksforgeeks.org/iterative-letter-combinations-of-a-phone-number/https://www.geeksforgeeks.org/minimum-steps-reach-target-knight/" }, { "code": null, "e": 28569, "s": 28490, "text": "https://www.geeksforgeeks.org/iterative-letter-combinations-of-a-phone-number/" }, { "code": null, "e": 28634, "s": 28569, "text": "https://www.geeksforgeeks.org/minimum-steps-reach-target-knight/" }, { "code": null, "e": 28714, "s": 28634, "text": "Round 4: It was taken by SDE-2. Two codes were asked. I was able to solve both." }, { "code": null, "e": 28956, "s": 28714, "text": "A question similar to: https://practice.geeksforgeeks.org/problems/kth-largest-element-in-a-stream2220/1https://www.geeksforgeeks.org/unique-paths-in-a-grid-with-obstacles/A question based on dp to find ways to move from one cell to another." }, { "code": null, "e": 29061, "s": 28956, "text": "A question similar to: https://practice.geeksforgeeks.org/problems/kth-largest-element-in-a-stream2220/1" }, { "code": null, "e": 29130, "s": 29061, "text": "https://www.geeksforgeeks.org/unique-paths-in-a-grid-with-obstacles/" }, { "code": null, "e": 29200, "s": 29130, "text": "A question based on dp to find ways to move from one cell to another." }, { "code": null, "e": 29274, "s": 29200, "text": "After 3 weeks I got reply that I will have bar raiser round after 1 week." }, { "code": null, "e": 29281, "s": 29274, "text": "Amazon" }, { "code": null, "e": 29291, "s": 29281, "text": "Marketing" }, { "code": null, "e": 29313, "s": 29291, "text": "Interview Experiences" }, { "code": null, "e": 29320, "s": 29313, "text": "Amazon" }, { "code": null, "e": 29418, "s": 29320, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29446, "s": 29418, "text": "Amazon Interview Experience" }, { "code": null, "e": 29496, "s": 29446, "text": "Amazon Interview Experience for SDE-1 (On-Campus)" }, { "code": null, "e": 29555, "s": 29496, "text": "Microsoft Interview Experience for Internship (Via Engage)" }, { "code": null, "e": 29605, "s": 29555, "text": "Directi Interview | Set 7 (Programming Questions)" }, { "code": null, "e": 29641, "s": 29605, "text": "Zoho Interview | Set 3 (Off-Campus)" }, { "code": null, "e": 29679, "s": 29641, "text": "Amazon Interview Experience for SDE-1" }, { "code": null, "e": 29730, "s": 29679, "text": "Amazon Interview Experience for SDE-1 (Off-Campus)" }, { "code": null, "e": 29766, "s": 29730, "text": "Difference between ANN, CNN and RNN" }, { "code": null, "e": 29812, "s": 29766, "text": "Amazon Interview Experience (Off-Campus) 2022" } ]
C# If ... Else
C# supports the usual logical conditions from mathematics: Less than: a < b Less than or equal to: a <= b Greater than: a > b Greater than or equal to: a >= b Equal to a == b Not Equal to: a != b You can use these conditions to perform different actions for different decisions. C# has the following conditional statements: Use if to specify a block of code to be executed, if a specified condition is true Use else to specify a block of code to be executed, if the same condition is false Use else if to specify a new condition to test, if the first condition is false Use switch to specify many alternative blocks of code to be executed Use the if statement to specify a block of C# code to be executed if a condition is True. if (condition) { // block of code to be executed if the condition is True } Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error. In the example below, we test two values to find out if 20 is greater than 18. If the condition is True, print some text: if (20 > 18) { Console.WriteLine("20 is greater than 18"); } Try it Yourself » We can also test variables: int x = 20; int y = 18; if (x > y) { Console.WriteLine("x is greater than y"); } Try it Yourself » In the example above we use two variables, x and y, to test whether x is greater than y (using the > operator). As x is 20, and y is 18, and we know that 20 is greater than 18, we print to the screen that "x is greater than y". Use the else statement to specify a block of code to be executed if the condition is False. if (condition) { // block of code to be executed if the condition is True } else { // block of code to be executed if the condition is False } int time = 20; if (time < 18) { Console.WriteLine("Good day."); } else { Console.WriteLine("Good evening."); } // Outputs "Good evening." Try it Yourself » In the example above, time (20) is greater than 18, so the condition is False. Because of this, we move on to the else condition and print to the screen "Good evening". If the time was less than 18, the program would print "Good day". Use the else if statement to specify a new condition if the first condition is False. if (condition1) { // block of code to be executed if condition1 is True } else if (condition2) { // block of code to be executed if the condition1 is false and condition2 is True } else { // block of code to be executed if the condition1 is false and condition2 is False } int time = 22; if (time < 10) { Console.WriteLine("Good morning."); } else if (time < 20) { Console.WriteLine("Good day."); } else { Console.WriteLine("Good evening."); } // Outputs "Good evening." Try it Yourself » In the example above, time (22) is greater than 10, so the first condition is False. The next condition, in the else if statement, is also False, so we move on to the else condition since condition1 and condition2 is both False - and print to the screen "Good evening". However, if the time was 14, our program would print "Good day." There is also a short-hand if else, which is known as the ternary operator because it consists of three operands. It can be used to replace multiple lines of code with a single line. It is often used to replace simple if else statements: variable = (condition) ? expressionTrue : expressionFalse; Instead of writing: int time = 20; if (time < 18) { Console.WriteLine("Good day."); } else { Console.WriteLine("Good evening."); } Try it Yourself » You can simply write: int time = 20; string result = (time < 18) ? "Good day." : "Good evening."; Console.WriteLine(result); Try it Yourself » Print "Hello World" if x is greater than y. int x = 50; int y = 10; (x y) { Console.WriteLine("Hello World"); } Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 59, "s": 0, "text": "C# supports the usual logical conditions from mathematics:" }, { "code": null, "e": 76, "s": 59, "text": "Less than: a < b" }, { "code": null, "e": 106, "s": 76, "text": "Less than or equal to: a <= b" }, { "code": null, "e": 126, "s": 106, "text": "Greater than: a > b" }, { "code": null, "e": 159, "s": 126, "text": "Greater than or equal to: a >= b" }, { "code": null, "e": 175, "s": 159, "text": "Equal to a == b" }, { "code": null, "e": 196, "s": 175, "text": "Not Equal to: a != b" }, { "code": null, "e": 279, "s": 196, "text": "You can use these conditions to perform different actions for different decisions." }, { "code": null, "e": 324, "s": 279, "text": "C# has the following conditional statements:" }, { "code": null, "e": 407, "s": 324, "text": "Use if to specify a block of code to be executed, if a specified condition is true" }, { "code": null, "e": 490, "s": 407, "text": "Use else to specify a block of code to be executed, if the same condition is false" }, { "code": null, "e": 570, "s": 490, "text": "Use else if to specify a new condition to test, if the first condition is false" }, { "code": null, "e": 639, "s": 570, "text": "Use switch to specify many alternative blocks of code to be executed" }, { "code": null, "e": 730, "s": 639, "text": "Use the if statement to specify a block of C# code to be executed if a condition is \nTrue." }, { "code": null, "e": 810, "s": 730, "text": "if (condition) \n{\n // block of code to be executed if the condition is True\n}\n" }, { "code": null, "e": 901, "s": 810, "text": "Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error." }, { "code": null, "e": 1024, "s": 901, "text": "In the example below, we test two values to find out if 20 is greater than \n18. If the condition is True, print some text:" }, { "code": null, "e": 1089, "s": 1024, "text": "if (20 > 18) \n{\n Console.WriteLine(\"20 is greater than 18\");\n}\n" }, { "code": null, "e": 1109, "s": 1089, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 1137, "s": 1109, "text": "We can also test variables:" }, { "code": null, "e": 1222, "s": 1137, "text": "int x = 20;\nint y = 18;\nif (x > y) \n{\n Console.WriteLine(\"x is greater than y\");\n}\n" }, { "code": null, "e": 1242, "s": 1222, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 1472, "s": 1242, "text": "In the example above we use two variables, x and y, \nto test whether x is greater than y \n(using the > operator). As x is 20, and y is 18, and we know that 20 is greater than 18, we print to the screen that \"x is greater than y\"." }, { "code": null, "e": 1565, "s": 1472, "text": "Use the else statement to specify a block of code to be executed if the condition is \nFalse." }, { "code": null, "e": 1715, "s": 1565, "text": "if (condition)\n{\n // block of code to be executed if the condition is True\n} \nelse \n{\n // block of code to be executed if the condition is False\n}\n" }, { "code": null, "e": 1863, "s": 1715, "text": "int time = 20;\nif (time < 18) \n{\n Console.WriteLine(\"Good day.\");\n} \nelse \n{\n Console.WriteLine(\"Good evening.\");\n}\n// Outputs \"Good evening.\"\n \n" }, { "code": null, "e": 1883, "s": 1863, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 2121, "s": 1883, "text": "In the example above, time (20) is greater than 18, so the condition is \nFalse. \nBecause of this, we move on to the else condition and print to the screen \"Good \nevening\". If the time was less than 18, the program would print \"Good day\"." }, { "code": null, "e": 2208, "s": 2121, "text": "Use the else if statement to specify a new condition if the first condition is \nFalse." }, { "code": null, "e": 2491, "s": 2208, "text": "if (condition1)\n{\n // block of code to be executed if condition1 is True\n} \nelse if (condition2) \n{\n // block of code to be executed if the condition1 is false and condition2 is True\n} \nelse\n{\n // block of code to be executed if the condition1 is false and condition2 is False\n}\n" }, { "code": null, "e": 2703, "s": 2491, "text": "int time = 22;\nif (time < 10) \n{\n Console.WriteLine(\"Good morning.\");\n} \nelse if (time < 20) \n{\n Console.WriteLine(\"Good day.\");\n} \nelse \n{\n Console.WriteLine(\"Good evening.\");\n}\n// Outputs \"Good evening.\"\n \n" }, { "code": null, "e": 2723, "s": 2703, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 2999, "s": 2723, "text": "In the example above, time (22) is greater than 10, so the first condition is \nFalse. The next condition, in the \nelse if statement, is also \nFalse, so we move on to the else\ncondition since condition1 and condition2 is both \nFalse - and print to the screen \"Good \nevening\"." }, { "code": null, "e": 3064, "s": 2999, "text": "However, if the time was 14, our program would print \"Good day.\"" }, { "code": null, "e": 3305, "s": 3064, "text": "There is also a short-hand if else, which is known as the ternary \noperator because it consists of three operands. It can be used to \nreplace multiple lines of code with a single line. It is often used to replace \nsimple if else statements:" }, { "code": null, "e": 3366, "s": 3305, "text": "variable = (condition) ? expressionTrue : expressionFalse;\n" }, { "code": null, "e": 3386, "s": 3366, "text": "Instead of writing:" }, { "code": null, "e": 3505, "s": 3386, "text": "int time = 20;\nif (time < 18) \n{\n Console.WriteLine(\"Good day.\");\n} \nelse \n{\n Console.WriteLine(\"Good evening.\");\n}\n" }, { "code": null, "e": 3525, "s": 3505, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 3547, "s": 3525, "text": "You can simply write:" }, { "code": null, "e": 3651, "s": 3547, "text": "int time = 20;\nstring result = (time < 18) ? \"Good day.\" : \"Good evening.\";\nConsole.WriteLine(result);\n" }, { "code": null, "e": 3671, "s": 3651, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 3715, "s": 3671, "text": "Print \"Hello World\" if x is greater than y." }, { "code": null, "e": 3789, "s": 3715, "text": "int x = 50;\nint y = 10;\n (x y) \n{\n Console.WriteLine(\"Hello World\");\n}\n" }, { "code": null, "e": 3808, "s": 3789, "text": "Start the Exercise" }, { "code": null, "e": 3841, "s": 3808, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 3883, "s": 3841, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 3990, "s": 3883, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 4009, "s": 3990, "text": "[email protected]" } ]
Calculate average of numbers in a column MySQL query?
Calculate the average of numbers in a column with the help of MySQL aggregate function AVG(). The syntax is as follows − select avg(yourColumnName) as anyVariableName from yourTableName; To understand the above concept, let us create a table. The following is the query to create a table. mysql> create table AverageCalculateDemo −> ( −> SubjectMarks int −> ); Query OK, 0 rows affected (0.67 sec) The following is the query to insert some records into the table − mysql> insert into AverageCalculateDemo values(70); Query OK, 1 row affected (0.14 sec) mysql> insert into AverageCalculateDemo values(80); Query OK, 1 row affected (0.19 sec) mysql> insert into AverageCalculateDemo values(65); Query OK, 1 row affected (0.13 sec) mysql> insert into AverageCalculateDemo values(55); Query OK, 1 row affected (0.13 sec) mysql> insert into AverageCalculateDemo values(60); Query OK, 1 row affected (0.23 sec) Display all values with the help of a select statement. The query is as follows to display all records − mysql> select *from AverageCalculateDemo; The following is the output − +--------------+ | SubjectMarks | +--------------+ | 70 | | 80 | | 65 | | 55 | | 60 | +--------------+ 5 rows in set (0.00 sec) Here is the query that calculates the average of the column in MySQL − mysql> select avg(SubjectMarks) as AverageOf4Numbers from AverageCalculateDemo; The following is the output that displays the average − +-------------------+ | AverageOf4Numbers | +-------------------+ | 66.0000 | +-------------------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1156, "s": 1062, "text": "Calculate the average of numbers in a column with the help of MySQL aggregate function AVG()." }, { "code": null, "e": 1183, "s": 1156, "text": "The syntax is as follows −" }, { "code": null, "e": 1249, "s": 1183, "text": "select avg(yourColumnName) as anyVariableName from yourTableName;" }, { "code": null, "e": 1351, "s": 1249, "text": "To understand the above concept, let us create a table. The following is the query to create a table." }, { "code": null, "e": 1472, "s": 1351, "text": "mysql> create table AverageCalculateDemo\n −> (\n −> SubjectMarks int\n −> );\nQuery OK, 0 rows affected (0.67 sec)" }, { "code": null, "e": 1539, "s": 1472, "text": "The following is the query to insert some records into the table −" }, { "code": null, "e": 1983, "s": 1539, "text": "mysql> insert into AverageCalculateDemo values(70);\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into AverageCalculateDemo values(80);\nQuery OK, 1 row affected (0.19 sec)\n\nmysql> insert into AverageCalculateDemo values(65);\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> insert into AverageCalculateDemo values(55);\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> insert into AverageCalculateDemo values(60);\nQuery OK, 1 row affected (0.23 sec)" }, { "code": null, "e": 2088, "s": 1983, "text": "Display all values with the help of a select statement. The query is as follows to display all records −" }, { "code": null, "e": 2130, "s": 2088, "text": "mysql> select *from AverageCalculateDemo;" }, { "code": null, "e": 2160, "s": 2130, "text": "The following is the output −" }, { "code": null, "e": 2338, "s": 2160, "text": "+--------------+\n| SubjectMarks |\n+--------------+\n| 70 |\n| 80 |\n| 65 |\n| 55 |\n| 60 |\n+--------------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 2409, "s": 2338, "text": "Here is the query that calculates the average of the column in MySQL −" }, { "code": null, "e": 2489, "s": 2409, "text": "mysql> select avg(SubjectMarks) as AverageOf4Numbers from AverageCalculateDemo;" }, { "code": null, "e": 2545, "s": 2489, "text": "The following is the output that displays the average −" }, { "code": null, "e": 2679, "s": 2545, "text": "+-------------------+\n| AverageOf4Numbers |\n+-------------------+\n| 66.0000 |\n+-------------------+\n1 row in set (0.00 sec)" } ]
Blowfish Algorithm with Examples - GeeksforGeeks
30 Sep, 2021 Blowfish is an encryption technique designed by Bruce Schneier in 1993 as an alternative to DES Encryption Technique. It is significantly faster than DES and provides a good encryption rate with no effective cryptanalysis technique found to date. It is one of the first, secure block cyphers not subject to any patents and hence freely available for anyone to use. blockSize: 64-bitskeySize: 32-bits to 448-bits variable sizenumber of subkeys: 18 [P-array]number of rounds: 16number of substitution boxes: 4 [each having 512 entries of 32-bits each] blockSize: 64-bits keySize: 32-bits to 448-bits variable size number of subkeys: 18 [P-array] number of rounds: 16 number of substitution boxes: 4 [each having 512 entries of 32-bits each] Blowfish Encryption Algorithm The entire encryption process can be elaborated as: Lets see each step one by one: Step1: Generation of subkeys: 18 subkeys{P[0]...P[17]} are needed in both encryption as well as decryption process and the same subkeys are used for both the processes. These 18 subkeys are stored in a P-array with each array element being a 32-bit entry. It is initialized with the digits of pi(?). The hexadecimal representation of each of the subkeys is given by: P[0] = "243f6a88" P[1] = "85a308d3" . . . P[17] = "8979fb1b" Now each of the subkey is changed with respect to the input key as: P[0] = P[0] xor 1st 32-bits of input key P[1] = P[1] xor 2nd 32-bits of input key . . . P[i] = P[i] xor (i+1)th 32-bits of input key (roll over to 1st 32-bits depending on the key length) . . . P[17] = P[17] xor 18th 32-bits of input key (roll over to 1st 32-bits depending on key length) The resultant P-array holds 18 subkeys that is used during the entire encryption process Step2: initialise Substitution Boxes: 4 Substitution boxes(S-boxes) are needed{S[0]...S[4]} in both encryption aswell as decryption process with each S-box having 256 entries{S[i][0]...S[i][255], 0&lei&le4} where each entry is 32-bit. It is initialized with the digits of pi(?) after initializing the P-array. You may find the s-boxes in here! Step3: Encryption: The encryption function consists of two parts: a. Rounds: The encryption consists of 16 rounds with each round(Ri) taking inputs the plainText(P.T.) from previous round and corresponding subkey(Pi). The description of each round is as follows: The description of the function ” F ” is as follows: Here the function “add” is addition modulo 2^32. b. Post-processing: The output after the 16 rounds is processed as follows: Below is a Java Program to demonstrate Blowfish encryption: Java // Java Program to demonstrate Blowfish encryption import java.util.*; public class Main { // Substitution boxes each string is a 32 bit hexadecimal value. String S[][] = { { "d1310ba6", "98dfb5ac", "2ffd72db", "d01adfb7", "b8e1afed", "6a267e96", "ba7c9045", "f12c7f99", "24a19947", "b3916cf7", "0801f2e2", "858efc16", "636920d8", "71574e69", "a458fea3", "f4933d7e", "0d95748f", "728eb658", "718bcd58", "82154aee", "7b54a41d", "c25a59b5", "9c30d539", "2af26013", "c5d1b023", "286085f0", "ca417918", "b8db38ef", "8e79dcb0", "603a180e", "6c9e0e8b", "b01e8a3e", "d71577c1", "bd314b27", "78af2fda", "55605c60", "e65525f3", "aa55ab94", "57489862", "63e81440", "55ca396a", "2aab10b6", "b4cc5c34", "1141e8ce", "a15486af", "7c72e993", "b3ee1411", "636fbc2a", "2ba9c55d", "741831f6", "ce5c3e16", "9b87931e", "afd6ba33", "6c24cf5c", "7a325381", "28958677", "3b8f4898", "6b4bb9af", "c4bfe81b", "66282193", "61d809cc", "fb21a991", "487cac60", "5dec8032", "ef845d5d", "e98575b1", "dc262302", "eb651b88", "23893e81", "d396acc5", "0f6d6ff3", "83f44239", "2e0b4482", "a4842004", "69c8f04a", "9e1f9b5e", "21c66842", "f6e96c9a", "670c9c61", "abd388f0", "6a51a0d2", "d8542f68", "960fa728", "ab5133a3", "6eef0b6c", "137a3be4", "ba3bf050", "7efb2a98", "a1f1651d", "39af0176", "66ca593e", "82430e88", "8cee8619", "456f9fb4", "7d84a5c3", "3b8b5ebe", "e06f75d8", "85c12073", "401a449f", "56c16aa6", "4ed3aa62", "363f7706", "1bfedf72", "429b023d", "37d0d724", "d00a1248", "db0fead3", "49f1c09b", "075372c9", "80991b7b", "25d479d8", "f6e8def7", "e3fe501a", "b6794c3b", "976ce0bd", "04c006ba", "c1a94fb6", "409f60c4", "5e5c9ec2", "196a2463", "68fb6faf", "3e6c53b5", "1339b2eb", "3b52ec6f", "6dfc511f", "9b30952c", "cc814544", "af5ebd09", "bee3d004", "de334afd", "660f2807", "192e4bb3", "c0cba857", "45c8740f", "d20b5f39", "b9d3fbdb", "5579c0bd", "1a60320a", "d6a100c6", "402c7279", "679f25fe", "fb1fa3cc", "8ea5e9f8", "db3222f8", "3c7516df", "fd616b15", "2f501ec8", "ad0552ab", "323db5fa", "fd238760", "53317b48", "3e00df82", "9e5c57bb", "ca6f8ca0", "1a87562e", "df1769db", "d542a8f6", "287effc3", "ac6732c6", "8c4f5573", "695b27b0", "bbca58c8", "e1ffa35d", "b8f011a0", "10fa3d98", "fd2183b8", "4afcb56c", "2dd1d35b", "9a53e479", "b6f84565", "d28e49bc", "4bfb9790", "e1ddf2da", "a4cb7e33", "62fb1341", "cee4c6e8", "ef20cada", "36774c01", "d07e9efe", "2bf11fb4", "95dbda4d", "ae909198", "eaad8e71", "6b93d5a0", "d08ed1d0", "afc725e0", "8e3c5b2f", "8e7594b7", "8ff6e2fb", "f2122b64", "8888b812", "900df01c", "4fad5ea0", "688fc31c", "d1cff191", "b3a8c1ad", "2f2f2218", "be0e1777", "ea752dfe", "8b021fa1", "e5a0cc0f", "b56f74e8", "18acf3d6", "ce89e299", "b4a84fe0", "fd13e0b7", "7cc43b81", "d2ada8d9", "165fa266", "80957705", "93cc7314", "211a1477", "e6ad2065", "77b5fa86", "c75442f5", "fb9d35cf", "ebcdaf0c", "7b3e89a0", "d6411bd3", "ae1e7e49", "00250e2d", "2071b35e", "226800bb", "57b8e0af", "2464369b", "f009b91e", "5563911d", "59dfa6aa", "78c14389", "d95a537f", "207d5ba2", "02e5b9c5", "83260376", "6295cfa9", "11c81968", "4e734a41", "b3472dca", "7b14a94a", "1b510052", "9a532915", "d60f573f", "bc9bc6e4", "2b60a476", "81e67400", "08ba6fb5", "571be91f", "f296ec6b", "2a0dd915", "b6636521", "e7b9f9b6", "ff34052e", "c5855664", "53b02d5d", "a99f8fa1", "08ba4799", "6e85076a" }, { "4b7a70e9", "b5b32944", "db75092e", "c4192623", "ad6ea6b0", "49a7df7d", "9cee60b8", "8fedb266", "ecaa8c71", "699a17ff", "5664526c", "c2b19ee1", "193602a5", "75094c29", "a0591340", "e4183a3e", "3f54989a", "5b429d65", "6b8fe4d6", "99f73fd6", "a1d29c07", "efe830f5", "4d2d38e6", "f0255dc1", "4cdd2086", "8470eb26", "6382e9c6", "021ecc5e", "09686b3f", "3ebaefc9", "3c971814", "6b6a70a1", "687f3584", "52a0e286", "b79c5305", "aa500737", "3e07841c", "7fdeae5c", "8e7d44ec", "5716f2b8", "b03ada37", "f0500c0d", "f01c1f04", "0200b3ff", "ae0cf51a", "3cb574b2", "25837a58", "dc0921bd", "d19113f9", "7ca92ff6", "94324773", "22f54701", "3ae5e581", "37c2dadc", "c8b57634", "9af3dda7", "a9446146", "0fd0030e", "ecc8c73e", "a4751e41", "e238cd99", "3bea0e2f", "3280bba1", "183eb331", "4e548b38", "4f6db908", "6f420d03", "f60a04bf", "2cb81290", "24977c79", "5679b072", "bcaf89af", "de9a771f", "d9930810", "b38bae12", "dccf3f2e", "5512721f", "2e6b7124", "501adde6", "9f84cd87", "7a584718", "7408da17", "bc9f9abc", "e94b7d8c", "ec7aec3a", "db851dfa", "63094366", "c464c3d2", "ef1c1847", "3215d908", "dd433b37", "24c2ba16", "12a14d43", "2a65c451", "50940002", "133ae4dd", "71dff89e", "10314e55", "81ac77d6", "5f11199b", "043556f1", "d7a3c76b", "3c11183b", "5924a509", "f28fe6ed", "97f1fbfa", "9ebabf2c", "1e153c6e", "86e34570", "eae96fb1", "860e5e0a", "5a3e2ab3", "771fe71c", "4e3d06fa", "2965dcb9", "99e71d0f", "803e89d6", "5266c825", "2e4cc978", "9c10b36a", "c6150eba", "94e2ea78", "a5fc3c53", "1e0a2df4", "f2f74ea7", "361d2b3d", "1939260f", "19c27960", "5223a708", "f71312b6", "ebadfe6e", "eac31f66", "e3bc4595", "a67bc883", "b17f37d1", "018cff28", "c332ddef", "be6c5aa5", "65582185", "68ab9802", "eecea50f", "db2f953b", "2aef7dad", "5b6e2f84", "1521b628", "29076170", "ecdd4775", "619f1510", "13cca830", "eb61bd96", "0334fe1e", "aa0363cf", "b5735c90", "4c70a239", "d59e9e0b", "cbaade14", "eecc86bc", "60622ca7", "9cab5cab", "b2f3846e", "648b1eaf", "19bdf0ca", "a02369b9", "655abb50", "40685a32", "3c2ab4b3", "319ee9d5", "c021b8f7", "9b540b19", "875fa099", "95f7997e", "623d7da8", "f837889a", "97e32d77", "11ed935f", "16681281", "0e358829", "c7e61fd6", "96dedfa1", "7858ba99", "57f584a5", "1b227263", "9b83c3ff", "1ac24696", "cdb30aeb", "532e3054", "8fd948e4", "6dbc3128", "58ebf2ef", "34c6ffea", "fe28ed61", "ee7c3c73", "5d4a14d9", "e864b7e3", "42105d14", "203e13e0", "45eee2b6", "a3aaabea", "db6c4f15", "facb4fd0", "c742f442", "ef6abbb5", "654f3b1d", "41cd2105", "d81e799e", "86854dc7", "e44b476a", "3d816250", "cf62a1f2", "5b8d2646", "fc8883a0", "c1c7b6a3", "7f1524c3", "69cb7492", "47848a0b", "5692b285", "095bbf00", "ad19489d", "1462b174", "23820e00", "58428d2a", "0c55f5ea", "1dadf43e", "233f7061", "3372f092", "8d937e41", "d65fecf1", "6c223bdb", "7cde3759", "cbee7460", "4085f2a7", "ce77326e", "a6078084", "19f8509e", "e8efd855", "61d99735", "a969a7aa", "c50c06c2", "5a04abfc", "800bcadc", "9e447a2e", "c3453484", "fdd56705", "0e1e9ec9", "db73dbd3", "105588cd", "675fda79", "e3674340", "c5c43465", "713e38d8", "3d28f89e", "f16dff20", "153e21e7", "8fb03d4a", "e6e39f2b", "db83adf7" }, { "e93d5a68", "948140f7", "f64c261c", "94692934", "411520f7", "7602d4f7", "bcf46b2e", "d4a20068", "d4082471", "3320f46a", "43b7d4b7", "500061af", "1e39f62e", "97244546", "14214f74", "bf8b8840", "4d95fc1d", "96b591af", "70f4ddd3", "66a02f45", "bfbc09ec", "03bd9785", "7fac6dd0", "31cb8504", "96eb27b3", "55fd3941", "da2547e6", "abca0a9a", "28507825", "530429f4", "0a2c86da", "e9b66dfb", "68dc1462", "d7486900", "680ec0a4", "27a18dee", "4f3ffea2", "e887ad8c", "b58ce006", "7af4d6b6", "aace1e7c", "d3375fec", "ce78a399", "406b2a42", "20fe9e35", "d9f385b9", "ee39d7ab", "3b124e8b", "1dc9faf7", "4b6d1856", "26a36631", "eae397b2", "3a6efa74", "dd5b4332", "6841e7f7", "ca7820fb", "fb0af54e", "d8feb397", "454056ac", "ba489527", "55533a3a", "20838d87", "fe6ba9b7", "d096954b", "55a867bc", "a1159a58", "cca92963", "99e1db33", "a62a4a56", "3f3125f9", "5ef47e1c", "9029317c", "fdf8e802", "04272f70", "80bb155c", "05282ce3", "95c11548", "e4c66d22", "48c1133f", "c70f86dc", "07f9c9ee", "41041f0f", "404779a4", "5d886e17", "325f51eb", "d59bc0d1", "f2bcc18f", "41113564", "257b7834", "602a9c60", "dff8e8a3", "1f636c1b", "0e12b4c2", "02e1329e", "af664fd1", "cad18115", "6b2395e0", "333e92e1", "3b240b62", "eebeb922", "85b2a20e", "e6ba0d99", "de720c8c", "2da2f728", "d0127845", "95b794fd", "647d0862", "e7ccf5f0", "5449a36f", "877d48fa", "c39dfd27", "f33e8d1e", "0a476341", "992eff74", "3a6f6eab", "f4f8fd37", "a812dc60", "a1ebddf8", "991be14c", "db6e6b0d", "c67b5510", "6d672c37", "2765d43b", "dcd0e804", "f1290dc7", "cc00ffa3", "b5390f92", "690fed0b", "667b9ffb", "cedb7d9c", "a091cf0b", "d9155ea3", "bb132f88", "515bad24", "7b9479bf", "763bd6eb", "37392eb3", "cc115979", "8026e297", "f42e312d", "6842ada7", "c66a2b3b", "12754ccc", "782ef11c", "6a124237", "b79251e7", "06a1bbe6", "4bfb6350", "1a6b1018", "11caedfa", "3d25bdd8", "e2e1c3c9", "44421659", "0a121386", "d90cec6e", "d5abea2a", "64af674e", "da86a85f", "bebfe988", "64e4c3fe", "9dbc8057", "f0f7c086", "60787bf8", "6003604d", "d1fd8346", "f6381fb0", "7745ae04", "d736fccc", "83426b33", "f01eab71", "b0804187", "3c005e5f", "77a057be", "bde8ae24", "55464299", "bf582e61", "4e58f48f", "f2ddfda2", "f474ef38", "8789bdc2", "5366f9c3", "c8b38e74", "b475f255", "46fcd9b9", "7aeb2661", "8b1ddf84", "846a0e79", "915f95e2", "466e598e", "20b45770", "8cd55591", "c902de4c", "b90bace1", "bb8205d0", "11a86248", "7574a99e", "b77f19b6", "e0a9dc09", "662d09a1", "c4324633", "e85a1f02", "09f0be8c", "4a99a025", "1d6efe10", "1ab93d1d", "0ba5a4df", "a186f20f", "2868f169", "dcb7da83", "573906fe", "a1e2ce9b", "4fcd7f52", "50115e01", "a70683fa", "a002b5c4", "0de6d027", "9af88c27", "773f8641", "c3604c06", "61a806b5", "f0177a28", "c0f586e0", "006058aa", "30dc7d62", "11e69ed7", "2338ea63", "53c2dd94", "c2c21634", "bbcbee56", "90bcb6de", "ebfc7da1", "ce591d76", "6f05e409", "4b7c0188", "39720a3d", "7c927c24", "86e3725f", "724d9db9", "1ac15bb4", "d39eb8fc", "ed545578", "08fca5b5", "d83d7cd3", "4dad0fc4", "1e50ef5e", "b161e6f8", "a28514d9", "6c51133c", "6fd5c7e7", "56e14ec4", "362abfce", "ddc6c837", "d79a3234", "92638212", "670efa8e", "406000e0" }, { "3a39ce37", "d3faf5cf", "abc27737", "5ac52d1b", "5cb0679e", "4fa33742", "d3822740", "99bc9bbe", "d5118e9d", "bf0f7315", "d62d1c7e", "c700c47b", "b78c1b6b", "21a19045", "b26eb1be", "6a366eb4", "5748ab2f", "bc946e79", "c6a376d2", "6549c2c8", "530ff8ee", "468dde7d", "d5730a1d", "4cd04dc6", "2939bbdb", "a9ba4650", "ac9526e8", "be5ee304", "a1fad5f0", "6a2d519a", "63ef8ce2", "9a86ee22", "c089c2b8", "43242ef6", "a51e03aa", "9cf2d0a4", "83c061ba", "9be96a4d", "8fe51550", "ba645bd6", "2826a2f9", "a73a3ae1", "4ba99586", "ef5562e9", "c72fefd3", "f752f7da", "3f046f69", "77fa0a59", "80e4a915", "87b08601", "9b09e6ad", "3b3ee593", "e990fd5a", "9e34d797", "2cf0b7d9", "022b8b51", "96d5ac3a", "017da67d", "d1cf3ed6", "7c7d2d28", "1f9f25cf", "adf2b89b", "5ad6b472", "5a88f54c", "e029ac71", "e019a5e6", "47b0acfd", "ed93fa9b", "e8d3c48d", "283b57cc", "f8d56629", "79132e28", "785f0191", "ed756055", "f7960e44", "e3d35e8c", "15056dd4", "88f46dba", "03a16125", "0564f0bd", "c3eb9e15", "3c9057a2", "97271aec", "a93a072a", "1b3f6d9b", "1e6321f5", "f59c66fb", "26dcf319", "7533d928", "b155fdf5", "03563482", "8aba3cbb", "28517711", "c20ad9f8", "abcc5167", "ccad925f", "4de81751", "3830dc8e", "379d5862", "9320f991", "ea7a90c2", "fb3e7bce", "5121ce64", "774fbe32", "a8b6e37e", "c3293d46", "48de5369", "6413e680", "a2ae0810", "dd6db224", "69852dfd", "09072166", "b39a460a", "6445c0dd", "586cdecf", "1c20c8ae", "5bbef7dd", "1b588d40", "ccd2017f", "6bb4e3bb", "dda26a7e", "3a59ff45", "3e350a44", "bcb4cdd5", "72eacea8", "fa6484bb", "8d6612ae", "bf3c6f47", "d29be463", "542f5d9e", "aec2771b", "f64e6370", "740e0d8d", "e75b1357", "f8721671", "af537d5d", "4040cb08", "4eb4e2cc", "34d2466a", "0115af84", "e1b00428", "95983a1d", "06b89fb4", "ce6ea048", "6f3f3b82", "3520ab82", "011a1d4b", "277227f8", "611560b1", "e7933fdc", "bb3a792b", "344525bd", "a08839e1", "51ce794b", "2f32c9b7", "a01fbac9", "e01cc87e", "bcc7d1f6", "cf0111c3", "a1e8aac7", "1a908749", "d44fbd9a", "d0dadecb", "d50ada38", "0339c32a", "c6913667", "8df9317c", "e0b12b4f", "f79e59b7", "43f5bb3a", "f2d519ff", "27d9459c", "bf97222c", "15e6fc2a", "0f91fc71", "9b941525", "fae59361", "ceb69ceb", "c2a86459", "12baa8d1", "b6c1075e", "e3056a0c", "10d25065", "cb03a442", "e0ec6e0e", "1698db3b", "4c98a0be", "3278e964", "9f1f9532", "e0d392df", "d3a0342b", "8971f21e", "1b0a7441", "4ba3348c", "c5be7120", "c37632d8", "df359f8d", "9b992f2e", "e60b6f47", "0fe3f11d", "e54cda54", "1edad891", "ce6279cf", "cd3e7e6f", "1618b166", "fd2c1d05", "848fd2c5", "f6fb2299", "f523f357", "a6327623", "93a83531", "56cccd02", "acf08162", "5a75ebb5", "6e163697", "88d273cc", "de966292", "81b949d0", "4c50901b", "71c65614", "e6c6c7bd", "327a140a", "45e1d006", "c3f27b9a", "c9aa53fd", "62a80f00", "bb25bfe2", "35bdd2f6", "71126905", "b2040222", "b6cbcf7c", "cd769c2b", "53113ec0", "1640e3d3", "38abbd60", "2547adf0", "ba38209c", "f746ce76", "77afa1c5", "20756060", "85cbfe4e", "8ae88dd8", "7aaaf9b0", "4cf9aa7e", "1948c25c", "02fb8a8c", "01c36ae4", "d6ebe1f9", "90d4f869", "a65cdea0", "3f09252d", "c208e69f", "b74e6132", "ce77e25b", "578fdfe3", "3ac372e6" } }; // Subkeys initialisation with digits of pi. String P[] = { "243f6a88", "85a308d3", "13198a2e", "03707344", "a4093822", "299f31d0", "082efa98", "ec4e6c89", "452821e6", "38d01377", "be5466cf", "34e90c6c", "c0ac29b7", "c97c50dd", "3f84d5b5", "b5470917", "9216d5d9", "8979fb1b" }; // to store 2^32(for addition modulo 2^32). long modVal = 1; // to convert hexadecimal to binary. private String hexToBin(String plainText) { String binary = ""; Long num; String binary4B; int n = plainText.length(); for (int i = 0; i < n; i++) { num = Long.parseUnsignedLong( plainText.charAt(i) + "", 16); binary4B = Long.toBinaryString(num); // each value in hexadecimal is 4 bits in binary. binary4B = "0000" + binary4B; binary4B = binary4B.substring(binary4B.length() - 4); binary += binary4B; } return binary; } // convert from binary to hexadecimal. private String binToHex(String plainText) { long num = Long.parseUnsignedLong(plainText, 2); String hexa = Long.toHexString(num); while (hexa.length() < (plainText.length() / 4)) // maintain output length same length // as input by appending leading zeroes. hexa = "0" + hexa; return hexa; } // xor two hexadecimal strings of the same length. private String xor(String a, String b) { a = hexToBin(a); b = hexToBin(b); String ans = ""; for (int i = 0; i < a.length(); i++) ans += (char)(((a.charAt(i) - '0') ^ (b.charAt(i) - '0')) + '0'); ans = binToHex(ans); return ans; } // addition modulo 2^32 of two hexadecimal strings. private String addBin(String a, String b) { String ans = ""; long n1 = Long.parseUnsignedLong(a, 16); long n2 = Long.parseUnsignedLong(b, 16); n1 = (n1 + n2) % modVal; ans = Long.toHexString(n1); ans = "00000000" + ans; return ans.substring(ans.length() - 8); } // function F explained above. private String f(String plainText) { String a[] = new String[4]; String ans = ""; for (int i = 0; i < 8; i += 2) { // the column number for S-box // is 8-bit value(8*4 = 32 bit plain text) long col = Long.parseUnsignedLong( hexToBin( plainText .substring(i, i + 2)), 2); a[i / 2] = S[i / 2][(int)col]; } ans = addBin(a[0], a[1]); ans = xor(ans, a[2]); ans = addBin(ans, a[3]); return ans; } // generate subkeys. private void keyGenerate(String key) { int j = 0; for (int i = 0; i < P.length; i++) { // xor-ing 32-bit parts of the key // with initial subkeys. P[i] = xor(P[i], key.substring(j, j + 8)); System.out.println("subkey " + (i + 1) + ": " + P[i]); j = (j + 8) % key.length(); } } // round function private String round(int time, String plainText) { String left, right; left = plainText.substring(0, 8); right = plainText.substring(8, 16); left = xor(left, P[time]); // output from F function String fOut = f(left); right = xor(fOut, right); System.out.println( "round " + time + ": " + right + left); // swap left and right return right + left; } // encryption private String encrypt(String plainText) { for (int i = 0; i < 16; i++) plainText = round(i, plainText); // postprocessing String right = plainText.substring(0, 8); String left = plainText.substring(8, 16); right = xor(right, P[16]); left = xor(left, P[17]); return left + right; } Main() { // storing 2^32 in modVal //(<<1 is equivalent to multiply by 2) for (int i = 0; i < 32; i++) modVal = modVal << 1; String plainText = "123456abcd132536"; String key = "aabb09182736ccdd"; keyGenerate(key); System.out.println("-----Encryption-----"); String cipherText = encrypt(plainText); System.out.println("Cipher Text: " + cipherText); } public static void main(String args[]) { new Main(); }} // This code is contributed by AbhayBhat subkey 1: 8e846390 subkey 2: a295c40e subkey 3: b9a28336 subkey 4: 2446bf99 subkey 5: 0eb2313a subkey 6: 0ea9fd0d subkey 7: a295f380 subkey 8: cb78a054 subkey 9: ef9328fe subkey 10: 1fe6dfaa subkey 11: 14ef6fd7 subkey 12: 13dfc0b1 subkey 13: 6a1720af subkey 14: ee4a9c00 subkey 15: 953fdcad subkey 16: 9271c5ca subkey 17: 38addcc1 subkey 18: ae4f37c6 -----Encryption----- round 0: 77b3ba639cb0353b round 1: 0cc7d63fd5267e6d round 2: c799728ab5655509 round 3: 69612395e3dfcd13 round 4: f3f5b74b67d312af round 5: 52023d4efd5c4a46 round 6: 5b785180f097cece round 7: cc946d119000f1d4 round 8: 6af47a4b230745ef round 9: 9fb82cc57512a5e1 round 10: 1106c1ab8b574312 round 11: 7d7a616502d9011a round 12: 81e9ce71176d41ca round 13: 9727e50a6fa35271 round 14: eb761e34021839a7 round 15: 0599d9367907dbfe Cipher Text: d748ec383d3405f7 The decryption process is similar to that of encryption and the subkeys are used in reverse{P[17] – P[0]}. The entire decryption process can be elaborated as: Lets see each step one by one: Step1: Generation of subkeys: 18 subkeys{P[0]...P[17]} are needed in decryption process. These 18 subkeys are stored in a P-array with each array element being a 32-bit entry. It is initialized with the digits of pi(?). The hexadecimal representation of each of the subkeys is given by: P[0] = "243f6a88" P[1] = "85a308d3" . . . P[17] = "8979fb1b" Note: See encryption for the initial values of P-array. Now each of the subkeys is changed with respect to the input key as: P[0] = P[0] xor 1st 32-bits of input key P[1] = P[1] xor 2nd 32-bits of input key . . . P[i] = P[i] xor (i+1)th 32-bits of input key (roll over to 1st 32-bits depending on the key length) . . . P[17] = P[17] xor 18th 32-bits of input key (roll over to 1st 32-bits depending on key length) The resultant P-array holds 18 subkeys that is used during the entire encryption process Step2: initialise Substitution Boxes: 4 Substitution boxes(S-boxes) are needed{S[0]...S[4]} in both encryption aswell as decryption process with each S-box having 256 entries{S[i][0]...S[i][255], 0&lei&le4} where each entry is 32-bit. It is initialised with the digits of pi(?) after initializing the P-array. You may find the s-boxes in here ! Step3: Decryption: The Decryption function also consists of two parts: Rounds: The decryption also consists of 16 rounds with each round(Ri)(as explained above) taking inputs the cipherText(C.T.) from previous round and corresponding subkey(P[17-i])(i.e for decryption the subkeys are used in reverse).Post-processing: The output after the 16 rounds is processed as follows: Rounds: The decryption also consists of 16 rounds with each round(Ri)(as explained above) taking inputs the cipherText(C.T.) from previous round and corresponding subkey(P[17-i])(i.e for decryption the subkeys are used in reverse).Post-processing: The output after the 16 rounds is processed as follows: Rounds: The decryption also consists of 16 rounds with each round(Ri)(as explained above) taking inputs the cipherText(C.T.) from previous round and corresponding subkey(P[17-i])(i.e for decryption the subkeys are used in reverse). Post-processing: The output after the 16 rounds is processed as follows: Below is a Java program to demonstrate decryption Java // Java program to demonstrate// Blowfish decryption Algorithm import java.util.*; public class Main { // Substitution boxes each string is a 32 bit hexadecimal value. String S[][] = { { "d1310ba6", "98dfb5ac", "2ffd72db", "d01adfb7", "b8e1afed", "6a267e96", "ba7c9045", "f12c7f99", "24a19947", "b3916cf7", "0801f2e2", "858efc16", "636920d8", "71574e69", "a458fea3", "f4933d7e", "0d95748f", "728eb658", "718bcd58", "82154aee", "7b54a41d", "c25a59b5", "9c30d539", "2af26013", "c5d1b023", "286085f0", "ca417918", "b8db38ef", "8e79dcb0", "603a180e", "6c9e0e8b", "b01e8a3e", "d71577c1", "bd314b27", "78af2fda", "55605c60", "e65525f3", "aa55ab94", "57489862", "63e81440", "55ca396a", "2aab10b6", "b4cc5c34", "1141e8ce", "a15486af", "7c72e993", "b3ee1411", "636fbc2a", "2ba9c55d", "741831f6", "ce5c3e16", "9b87931e", "afd6ba33", "6c24cf5c", "7a325381", "28958677", "3b8f4898", "6b4bb9af", "c4bfe81b", "66282193", "61d809cc", "fb21a991", "487cac60", "5dec8032", "ef845d5d", "e98575b1", "dc262302", "eb651b88", "23893e81", "d396acc5", "0f6d6ff3", "83f44239", "2e0b4482", "a4842004", "69c8f04a", "9e1f9b5e", "21c66842", "f6e96c9a", "670c9c61", "abd388f0", "6a51a0d2", "d8542f68", "960fa728", "ab5133a3", "6eef0b6c", "137a3be4", "ba3bf050", "7efb2a98", "a1f1651d", "39af0176", "66ca593e", "82430e88", "8cee8619", "456f9fb4", "7d84a5c3", "3b8b5ebe", "e06f75d8", "85c12073", "401a449f", "56c16aa6", "4ed3aa62", "363f7706", "1bfedf72", "429b023d", "37d0d724", "d00a1248", "db0fead3", "49f1c09b", "075372c9", "80991b7b", "25d479d8", "f6e8def7", "e3fe501a", "b6794c3b", "976ce0bd", "04c006ba", "c1a94fb6", "409f60c4", "5e5c9ec2", "196a2463", "68fb6faf", "3e6c53b5", "1339b2eb", "3b52ec6f", "6dfc511f", "9b30952c", "cc814544", "af5ebd09", "bee3d004", "de334afd", "660f2807", "192e4bb3", "c0cba857", "45c8740f", "d20b5f39", "b9d3fbdb", "5579c0bd", "1a60320a", "d6a100c6", "402c7279", "679f25fe", "fb1fa3cc", "8ea5e9f8", "db3222f8", "3c7516df", "fd616b15", "2f501ec8", "ad0552ab", "323db5fa", "fd238760", "53317b48", "3e00df82", "9e5c57bb", "ca6f8ca0", "1a87562e", "df1769db", "d542a8f6", "287effc3", "ac6732c6", "8c4f5573", "695b27b0", "bbca58c8", "e1ffa35d", "b8f011a0", "10fa3d98", "fd2183b8", "4afcb56c", "2dd1d35b", "9a53e479", "b6f84565", "d28e49bc", "4bfb9790", "e1ddf2da", "a4cb7e33", "62fb1341", "cee4c6e8", "ef20cada", "36774c01", "d07e9efe", "2bf11fb4", "95dbda4d", "ae909198", "eaad8e71", "6b93d5a0", "d08ed1d0", "afc725e0", "8e3c5b2f", "8e7594b7", "8ff6e2fb", "f2122b64", "8888b812", "900df01c", "4fad5ea0", "688fc31c", "d1cff191", "b3a8c1ad", "2f2f2218", "be0e1777", "ea752dfe", "8b021fa1", "e5a0cc0f", "b56f74e8", "18acf3d6", "ce89e299", "b4a84fe0", "fd13e0b7", "7cc43b81", "d2ada8d9", "165fa266", "80957705", "93cc7314", "211a1477", "e6ad2065", "77b5fa86", "c75442f5", "fb9d35cf", "ebcdaf0c", "7b3e89a0", "d6411bd3", "ae1e7e49", "00250e2d", "2071b35e", "226800bb", "57b8e0af", "2464369b", "f009b91e", "5563911d", "59dfa6aa", "78c14389", "d95a537f", "207d5ba2", "02e5b9c5", "83260376", "6295cfa9", "11c81968", "4e734a41", "b3472dca", "7b14a94a", "1b510052", "9a532915", "d60f573f", "bc9bc6e4", "2b60a476", "81e67400", "08ba6fb5", "571be91f", "f296ec6b", "2a0dd915", "b6636521", "e7b9f9b6", "ff34052e", "c5855664", "53b02d5d", "a99f8fa1", "08ba4799", "6e85076a" }, { "4b7a70e9", "b5b32944", "db75092e", "c4192623", "ad6ea6b0", "49a7df7d", "9cee60b8", "8fedb266", "ecaa8c71", "699a17ff", "5664526c", "c2b19ee1", "193602a5", "75094c29", "a0591340", "e4183a3e", "3f54989a", "5b429d65", "6b8fe4d6", "99f73fd6", "a1d29c07", "efe830f5", "4d2d38e6", "f0255dc1", "4cdd2086", "8470eb26", "6382e9c6", "021ecc5e", "09686b3f", "3ebaefc9", "3c971814", "6b6a70a1", "687f3584", "52a0e286", "b79c5305", "aa500737", "3e07841c", "7fdeae5c", "8e7d44ec", "5716f2b8", "b03ada37", "f0500c0d", "f01c1f04", "0200b3ff", "ae0cf51a", "3cb574b2", "25837a58", "dc0921bd", "d19113f9", "7ca92ff6", "94324773", "22f54701", "3ae5e581", "37c2dadc", "c8b57634", "9af3dda7", "a9446146", "0fd0030e", "ecc8c73e", "a4751e41", "e238cd99", "3bea0e2f", "3280bba1", "183eb331", "4e548b38", "4f6db908", "6f420d03", "f60a04bf", "2cb81290", "24977c79", "5679b072", "bcaf89af", "de9a771f", "d9930810", "b38bae12", "dccf3f2e", "5512721f", "2e6b7124", "501adde6", "9f84cd87", "7a584718", "7408da17", "bc9f9abc", "e94b7d8c", "ec7aec3a", "db851dfa", "63094366", "c464c3d2", "ef1c1847", "3215d908", "dd433b37", "24c2ba16", "12a14d43", "2a65c451", "50940002", "133ae4dd", "71dff89e", "10314e55", "81ac77d6", "5f11199b", "043556f1", "d7a3c76b", "3c11183b", "5924a509", "f28fe6ed", "97f1fbfa", "9ebabf2c", "1e153c6e", "86e34570", "eae96fb1", "860e5e0a", "5a3e2ab3", "771fe71c", "4e3d06fa", "2965dcb9", "99e71d0f", "803e89d6", "5266c825", "2e4cc978", "9c10b36a", "c6150eba", "94e2ea78", "a5fc3c53", "1e0a2df4", "f2f74ea7", "361d2b3d", "1939260f", "19c27960", "5223a708", "f71312b6", "ebadfe6e", "eac31f66", "e3bc4595", "a67bc883", "b17f37d1", "018cff28", "c332ddef", "be6c5aa5", "65582185", "68ab9802", "eecea50f", "db2f953b", "2aef7dad", "5b6e2f84", "1521b628", "29076170", "ecdd4775", "619f1510", "13cca830", "eb61bd96", "0334fe1e", "aa0363cf", "b5735c90", "4c70a239", "d59e9e0b", "cbaade14", "eecc86bc", "60622ca7", "9cab5cab", "b2f3846e", "648b1eaf", "19bdf0ca", "a02369b9", "655abb50", "40685a32", "3c2ab4b3", "319ee9d5", "c021b8f7", "9b540b19", "875fa099", "95f7997e", "623d7da8", "f837889a", "97e32d77", "11ed935f", "16681281", "0e358829", "c7e61fd6", "96dedfa1", "7858ba99", "57f584a5", "1b227263", "9b83c3ff", "1ac24696", "cdb30aeb", "532e3054", "8fd948e4", "6dbc3128", "58ebf2ef", "34c6ffea", "fe28ed61", "ee7c3c73", "5d4a14d9", "e864b7e3", "42105d14", "203e13e0", "45eee2b6", "a3aaabea", "db6c4f15", "facb4fd0", "c742f442", "ef6abbb5", "654f3b1d", "41cd2105", "d81e799e", "86854dc7", "e44b476a", "3d816250", "cf62a1f2", "5b8d2646", "fc8883a0", "c1c7b6a3", "7f1524c3", "69cb7492", "47848a0b", "5692b285", "095bbf00", "ad19489d", "1462b174", "23820e00", "58428d2a", "0c55f5ea", "1dadf43e", "233f7061", "3372f092", "8d937e41", "d65fecf1", "6c223bdb", "7cde3759", "cbee7460", "4085f2a7", "ce77326e", "a6078084", "19f8509e", "e8efd855", "61d99735", "a969a7aa", "c50c06c2", "5a04abfc", "800bcadc", "9e447a2e", "c3453484", "fdd56705", "0e1e9ec9", "db73dbd3", "105588cd", "675fda79", "e3674340", "c5c43465", "713e38d8", "3d28f89e", "f16dff20", "153e21e7", "8fb03d4a", "e6e39f2b", "db83adf7" }, { "e93d5a68", "948140f7", "f64c261c", "94692934", "411520f7", "7602d4f7", "bcf46b2e", "d4a20068", "d4082471", "3320f46a", "43b7d4b7", "500061af", "1e39f62e", "97244546", "14214f74", "bf8b8840", "4d95fc1d", "96b591af", "70f4ddd3", "66a02f45", "bfbc09ec", "03bd9785", "7fac6dd0", "31cb8504", "96eb27b3", "55fd3941", "da2547e6", "abca0a9a", "28507825", "530429f4", "0a2c86da", "e9b66dfb", "68dc1462", "d7486900", "680ec0a4", "27a18dee", "4f3ffea2", "e887ad8c", "b58ce006", "7af4d6b6", "aace1e7c", "d3375fec", "ce78a399", "406b2a42", "20fe9e35", "d9f385b9", "ee39d7ab", "3b124e8b", "1dc9faf7", "4b6d1856", "26a36631", "eae397b2", "3a6efa74", "dd5b4332", "6841e7f7", "ca7820fb", "fb0af54e", "d8feb397", "454056ac", "ba489527", "55533a3a", "20838d87", "fe6ba9b7", "d096954b", "55a867bc", "a1159a58", "cca92963", "99e1db33", "a62a4a56", "3f3125f9", "5ef47e1c", "9029317c", "fdf8e802", "04272f70", "80bb155c", "05282ce3", "95c11548", "e4c66d22", "48c1133f", "c70f86dc", "07f9c9ee", "41041f0f", "404779a4", "5d886e17", "325f51eb", "d59bc0d1", "f2bcc18f", "41113564", "257b7834", "602a9c60", "dff8e8a3", "1f636c1b", "0e12b4c2", "02e1329e", "af664fd1", "cad18115", "6b2395e0", "333e92e1", "3b240b62", "eebeb922", "85b2a20e", "e6ba0d99", "de720c8c", "2da2f728", "d0127845", "95b794fd", "647d0862", "e7ccf5f0", "5449a36f", "877d48fa", "c39dfd27", "f33e8d1e", "0a476341", "992eff74", "3a6f6eab", "f4f8fd37", "a812dc60", "a1ebddf8", "991be14c", "db6e6b0d", "c67b5510", "6d672c37", "2765d43b", "dcd0e804", "f1290dc7", "cc00ffa3", "b5390f92", "690fed0b", "667b9ffb", "cedb7d9c", "a091cf0b", "d9155ea3", "bb132f88", "515bad24", "7b9479bf", "763bd6eb", "37392eb3", "cc115979", "8026e297", "f42e312d", "6842ada7", "c66a2b3b", "12754ccc", "782ef11c", "6a124237", "b79251e7", "06a1bbe6", "4bfb6350", "1a6b1018", "11caedfa", "3d25bdd8", "e2e1c3c9", "44421659", "0a121386", "d90cec6e", "d5abea2a", "64af674e", "da86a85f", "bebfe988", "64e4c3fe", "9dbc8057", "f0f7c086", "60787bf8", "6003604d", "d1fd8346", "f6381fb0", "7745ae04", "d736fccc", "83426b33", "f01eab71", "b0804187", "3c005e5f", "77a057be", "bde8ae24", "55464299", "bf582e61", "4e58f48f", "f2ddfda2", "f474ef38", "8789bdc2", "5366f9c3", "c8b38e74", "b475f255", "46fcd9b9", "7aeb2661", "8b1ddf84", "846a0e79", "915f95e2", "466e598e", "20b45770", "8cd55591", "c902de4c", "b90bace1", "bb8205d0", "11a86248", "7574a99e", "b77f19b6", "e0a9dc09", "662d09a1", "c4324633", "e85a1f02", "09f0be8c", "4a99a025", "1d6efe10", "1ab93d1d", "0ba5a4df", "a186f20f", "2868f169", "dcb7da83", "573906fe", "a1e2ce9b", "4fcd7f52", "50115e01", "a70683fa", "a002b5c4", "0de6d027", "9af88c27", "773f8641", "c3604c06", "61a806b5", "f0177a28", "c0f586e0", "006058aa", "30dc7d62", "11e69ed7", "2338ea63", "53c2dd94", "c2c21634", "bbcbee56", "90bcb6de", "ebfc7da1", "ce591d76", "6f05e409", "4b7c0188", "39720a3d", "7c927c24", "86e3725f", "724d9db9", "1ac15bb4", "d39eb8fc", "ed545578", "08fca5b5", "d83d7cd3", "4dad0fc4", "1e50ef5e", "b161e6f8", "a28514d9", "6c51133c", "6fd5c7e7", "56e14ec4", "362abfce", "ddc6c837", "d79a3234", "92638212", "670efa8e", "406000e0" }, { "3a39ce37", "d3faf5cf", "abc27737", "5ac52d1b", "5cb0679e", "4fa33742", "d3822740", "99bc9bbe", "d5118e9d", "bf0f7315", "d62d1c7e", "c700c47b", "b78c1b6b", "21a19045", "b26eb1be", "6a366eb4", "5748ab2f", "bc946e79", "c6a376d2", "6549c2c8", "530ff8ee", "468dde7d", "d5730a1d", "4cd04dc6", "2939bbdb", "a9ba4650", "ac9526e8", "be5ee304", "a1fad5f0", "6a2d519a", "63ef8ce2", "9a86ee22", "c089c2b8", "43242ef6", "a51e03aa", "9cf2d0a4", "83c061ba", "9be96a4d", "8fe51550", "ba645bd6", "2826a2f9", "a73a3ae1", "4ba99586", "ef5562e9", "c72fefd3", "f752f7da", "3f046f69", "77fa0a59", "80e4a915", "87b08601", "9b09e6ad", "3b3ee593", "e990fd5a", "9e34d797", "2cf0b7d9", "022b8b51", "96d5ac3a", "017da67d", "d1cf3ed6", "7c7d2d28", "1f9f25cf", "adf2b89b", "5ad6b472", "5a88f54c", "e029ac71", "e019a5e6", "47b0acfd", "ed93fa9b", "e8d3c48d", "283b57cc", "f8d56629", "79132e28", "785f0191", "ed756055", "f7960e44", "e3d35e8c", "15056dd4", "88f46dba", "03a16125", "0564f0bd", "c3eb9e15", "3c9057a2", "97271aec", "a93a072a", "1b3f6d9b", "1e6321f5", "f59c66fb", "26dcf319", "7533d928", "b155fdf5", "03563482", "8aba3cbb", "28517711", "c20ad9f8", "abcc5167", "ccad925f", "4de81751", "3830dc8e", "379d5862", "9320f991", "ea7a90c2", "fb3e7bce", "5121ce64", "774fbe32", "a8b6e37e", "c3293d46", "48de5369", "6413e680", "a2ae0810", "dd6db224", "69852dfd", "09072166", "b39a460a", "6445c0dd", "586cdecf", "1c20c8ae", "5bbef7dd", "1b588d40", "ccd2017f", "6bb4e3bb", "dda26a7e", "3a59ff45", "3e350a44", "bcb4cdd5", "72eacea8", "fa6484bb", "8d6612ae", "bf3c6f47", "d29be463", "542f5d9e", "aec2771b", "f64e6370", "740e0d8d", "e75b1357", "f8721671", "af537d5d", "4040cb08", "4eb4e2cc", "34d2466a", "0115af84", "e1b00428", "95983a1d", "06b89fb4", "ce6ea048", "6f3f3b82", "3520ab82", "011a1d4b", "277227f8", "611560b1", "e7933fdc", "bb3a792b", "344525bd", "a08839e1", "51ce794b", "2f32c9b7", "a01fbac9", "e01cc87e", "bcc7d1f6", "cf0111c3", "a1e8aac7", "1a908749", "d44fbd9a", "d0dadecb", "d50ada38", "0339c32a", "c6913667", "8df9317c", "e0b12b4f", "f79e59b7", "43f5bb3a", "f2d519ff", "27d9459c", "bf97222c", "15e6fc2a", "0f91fc71", "9b941525", "fae59361", "ceb69ceb", "c2a86459", "12baa8d1", "b6c1075e", "e3056a0c", "10d25065", "cb03a442", "e0ec6e0e", "1698db3b", "4c98a0be", "3278e964", "9f1f9532", "e0d392df", "d3a0342b", "8971f21e", "1b0a7441", "4ba3348c", "c5be7120", "c37632d8", "df359f8d", "9b992f2e", "e60b6f47", "0fe3f11d", "e54cda54", "1edad891", "ce6279cf", "cd3e7e6f", "1618b166", "fd2c1d05", "848fd2c5", "f6fb2299", "f523f357", "a6327623", "93a83531", "56cccd02", "acf08162", "5a75ebb5", "6e163697", "88d273cc", "de966292", "81b949d0", "4c50901b", "71c65614", "e6c6c7bd", "327a140a", "45e1d006", "c3f27b9a", "c9aa53fd", "62a80f00", "bb25bfe2", "35bdd2f6", "71126905", "b2040222", "b6cbcf7c", "cd769c2b", "53113ec0", "1640e3d3", "38abbd60", "2547adf0", "ba38209c", "f746ce76", "77afa1c5", "20756060", "85cbfe4e", "8ae88dd8", "7aaaf9b0", "4cf9aa7e", "1948c25c", "02fb8a8c", "01c36ae4", "d6ebe1f9", "90d4f869", "a65cdea0", "3f09252d", "c208e69f", "b74e6132", "ce77e25b", "578fdfe3", "3ac372e6" } }; // Subkeys initialisation with digits of pi. String P[] = { "243f6a88", "85a308d3", "13198a2e", "03707344", "a4093822", "299f31d0", "082efa98", "ec4e6c89", "452821e6", "38d01377", "be5466cf", "34e90c6c", "c0ac29b7", "c97c50dd", "3f84d5b5", "b5470917", "9216d5d9", "8979fb1b" }; // to store 2^32(for addition modulo 2^32). long modVal = 1; // to convert hexadecimal to binary. private String hexToBin(String plainText) { String binary = ""; Long num; String binary4B; int n = plainText.length(); for (int i = 0; i < n; i++) { num = Long.parseUnsignedLong( plainText.charAt(i) + "", 16); binary4B = Long.toBinaryString(num); // each value in hexadecimal // is 4 bits in binary. binary4B = "0000" + binary4B; binary4B = binary4B.substring( binary4B.length() - 4); binary += binary4B; } return binary; } // convert from binary to hexadecimal. private String binToHex(String plainText) { long num = Long.parseUnsignedLong(plainText, 2); String hexa = Long.toHexString(num); while (hexa.length() < (plainText.length() / 4)) // maintain output length same length // as input by appending leading zeroes. hexa = "0" + hexa; return hexa; } // xor two hexadecimal strings of same length. private String xor(String a, String b) { a = hexToBin(a); b = hexToBin(b); String ans = ""; for (int i = 0; i < a.length(); i++) ans += (char)(((a.charAt(i) - '0') ^ (b.charAt(i) - '0')) + '0'); ans = binToHex(ans); return ans; } // addition modulo 2^32 of two hexadecimal strings. private String addBin(String a, String b) { String ans = ""; long n1 = Long.parseUnsignedLong(a, 16); long n2 = Long.parseUnsignedLong(b, 16); n1 = (n1 + n2) % modVal; ans = Long.toHexString(n1); ans = "00000000" + ans; return ans.substring(ans.length() - 8); } // function F explained above. private String f(String plainText) { String a[] = new String[4]; String ans = ""; for (int i = 0; i < 8; i += 2) { // the column number for S-box // is 8-bit value(8*4 = 32 bit plain text) long col = Long.parseUnsignedLong( hexToBin( plainText.substring(i, i + 2)), 2); a[i / 2] = S[i / 2][(int)col]; } ans = addBin(a[0], a[1]); ans = xor(ans, a[2]); ans = addBin(ans, a[3]); return ans; } // generate subkeys. private void keyGenerate(String key) { int j = 0; for (int i = 0; i < P.length; i++) { P[i] = xor(P[i], key.substring(j, j + 8)); System.out.println("subkey " + (i + 1) + ": " + P[i]); j = (j + 8) % key.length(); } } // round function private String round(int time, String plainText) { String left, right; left = plainText.substring(0, 8); right = plainText.substring(8, 16); left = xor(left, P[time]); String fOut = f(left); // output from F function right = xor(fOut, right); System.out.println("round " + time + ": " + right + left); // swap left and right return right + left; } // decryption private String decrypt(String plainText) { for (int i = 17; i > 1; i--) plainText = round(i, plainText); // postprocessing String right = plainText.substring(0, 8); String left = plainText.substring(8, 16); right = xor(right, P[1]); left = xor(left, P[0]); return left + right; } Main() { // storing 2^32 in modVal //(<<1 is equivalent to multiply by 2) for (int i = 0; i < 32; i++) modVal = modVal << 1; String cipherText = "d748ec383d3405f7"; String key = "aabb09182736ccdd"; keyGenerate(key); System.out.println("-----Decryption-----"); String plainText = decrypt(cipherText); System.out.println("Plain Text: " + plainText); } public static void main(String args[]) { new Main(); }} // This code is contributed by AbhayBhat subkey 1: 8e846390 subkey 2: a295c40e subkey 3: b9a28336 subkey 4: 2446bf99 subkey 5: 0eb2313a subkey 6: 0ea9fd0d subkey 7: a295f380 subkey 8: cb78a054 subkey 9: ef9328fe subkey 10: 1fe6dfaa subkey 11: 14ef6fd7 subkey 12: 13dfc0b1 subkey 13: 6a1720af subkey 14: ee4a9c00 subkey 15: 953fdcad subkey 16: 9271c5ca subkey 17: 38addcc1 subkey 18: ae4f37c6 -----Decryption----- round 17: 3ab5e5667907dbfe round 16: fdd297bb021839a7 round 15: 82529d676fa35271 round 14: ec939d1a176d41ca round 13: e14063bd02d9011a round 12: 66cd65508b574312 round 11: 37e82a387512a5e1 round 10: 8fe62e7e230745ef round 9: 1f04e6309000f1d4 round 8: 3624ea12f097cece round 7: c546e12ffd5c4a46 round 6: ed76301e67d312af round 5: bbd76433e3dfcd13 round 4: f160c1f4b5655509 round 3: 2512b60dd5267e6d round 2: 6f86e1389cb0353b Plain Text: 123456abcd132536 Blowfish is a fast block cipher except when changing keys. Each new key requires a pre-processing equivalent to 4KB of text. It is faster and much better than DES Encryption. Blowfish uses a 64-bit block size which makes it vulnerable to birthday attacks. A reduced round variant of blowfish is known to be susceptible to known plain text attacks(2nd order differential attacks – 4 rounds). Bulk Encryption. Packet Encryption(ATM Packets) Password Hashing varshagumber28 cryptography Algorithms cryptography Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments DSA Sheet by Love Babbar Quadratic Probing in Hashing SCAN (Elevator) Disk Scheduling Algorithms K means Clustering - Introduction Difference between Informed and Uninformed Search in AI Program for SSTF disk scheduling algorithm Difference between Algorithm, Pseudocode and Program K-Nearest Neighbours Travelling Salesman Problem implementation using BackTracking Hash Functions and list/types of Hash functions
[ { "code": null, "e": 24690, "s": 24662, "text": "\n30 Sep, 2021" }, { "code": null, "e": 25055, "s": 24690, "text": "Blowfish is an encryption technique designed by Bruce Schneier in 1993 as an alternative to DES Encryption Technique. It is significantly faster than DES and provides a good encryption rate with no effective cryptanalysis technique found to date. It is one of the first, secure block cyphers not subject to any patents and hence freely available for anyone to use." }, { "code": null, "e": 25240, "s": 25055, "text": "blockSize: 64-bitskeySize: 32-bits to 448-bits variable sizenumber of subkeys: 18 [P-array]number of rounds: 16number of substitution boxes: 4 [each having 512 entries of 32-bits each]" }, { "code": null, "e": 25259, "s": 25240, "text": "blockSize: 64-bits" }, { "code": null, "e": 25302, "s": 25259, "text": "keySize: 32-bits to 448-bits variable size" }, { "code": null, "e": 25334, "s": 25302, "text": "number of subkeys: 18 [P-array]" }, { "code": null, "e": 25355, "s": 25334, "text": "number of rounds: 16" }, { "code": null, "e": 25429, "s": 25355, "text": "number of substitution boxes: 4 [each having 512 entries of 32-bits each]" }, { "code": null, "e": 25459, "s": 25429, "text": "Blowfish Encryption Algorithm" }, { "code": null, "e": 25512, "s": 25459, "text": "The entire encryption process can be elaborated as: " }, { "code": null, "e": 25543, "s": 25512, "text": "Lets see each step one by one:" }, { "code": null, "e": 25574, "s": 25543, "text": "Step1: Generation of subkeys: " }, { "code": null, "e": 25713, "s": 25574, "text": "18 subkeys{P[0]...P[17]} are needed in both encryption as well as decryption process and the same subkeys are used for both the processes." }, { "code": null, "e": 25800, "s": 25713, "text": "These 18 subkeys are stored in a P-array with each array element being a 32-bit entry." }, { "code": null, "e": 25844, "s": 25800, "text": "It is initialized with the digits of pi(?)." }, { "code": null, "e": 25911, "s": 25844, "text": "The hexadecimal representation of each of the subkeys is given by:" }, { "code": null, "e": 25972, "s": 25911, "text": "P[0] = \"243f6a88\"\nP[1] = \"85a308d3\"\n.\n.\n.\nP[17] = \"8979fb1b\"" }, { "code": null, "e": 26040, "s": 25972, "text": "Now each of the subkey is changed with respect to the input key as:" }, { "code": null, "e": 26331, "s": 26040, "text": "P[0] = P[0] xor 1st 32-bits of input key\nP[1] = P[1] xor 2nd 32-bits of input key\n.\n.\n.\nP[i] = P[i] xor (i+1)th 32-bits of input key \n(roll over to 1st 32-bits depending on the key length)\n.\n.\n.\nP[17] = P[17] xor 18th 32-bits of input key \n(roll over to 1st 32-bits depending on key length)" }, { "code": null, "e": 26420, "s": 26331, "text": "The resultant P-array holds 18 subkeys that is used during the entire encryption process" }, { "code": null, "e": 26459, "s": 26420, "text": "Step2: initialise Substitution Boxes: " }, { "code": null, "e": 26656, "s": 26459, "text": "4 Substitution boxes(S-boxes) are needed{S[0]...S[4]} in both encryption aswell as decryption process with each S-box having 256 entries{S[i][0]...S[i][255], 0&lei&le4} where each entry is 32-bit." }, { "code": null, "e": 26765, "s": 26656, "text": "It is initialized with the digits of pi(?) after initializing the P-array. You may find the s-boxes in here!" }, { "code": null, "e": 26785, "s": 26765, "text": "Step3: Encryption: " }, { "code": null, "e": 27029, "s": 26785, "text": "The encryption function consists of two parts: a. Rounds: The encryption consists of 16 rounds with each round(Ri) taking inputs the plainText(P.T.) from previous round and corresponding subkey(Pi). The description of each round is as follows:" }, { "code": null, "e": 27083, "s": 27029, "text": "The description of the function ” F ” is as follows: " }, { "code": null, "e": 27133, "s": 27083, "text": "Here the function “add” is addition modulo 2^32. " }, { "code": null, "e": 27210, "s": 27133, "text": "b. Post-processing: The output after the 16 rounds is processed as follows: " }, { "code": null, "e": 27271, "s": 27210, "text": "Below is a Java Program to demonstrate Blowfish encryption: " }, { "code": null, "e": 27276, "s": 27271, "text": "Java" }, { "code": "// Java Program to demonstrate Blowfish encryption import java.util.*; public class Main { // Substitution boxes each string is a 32 bit hexadecimal value. String S[][] = { { \"d1310ba6\", \"98dfb5ac\", \"2ffd72db\", \"d01adfb7\", \"b8e1afed\", \"6a267e96\", \"ba7c9045\", \"f12c7f99\", \"24a19947\", \"b3916cf7\", \"0801f2e2\", \"858efc16\", \"636920d8\", \"71574e69\", \"a458fea3\", \"f4933d7e\", \"0d95748f\", \"728eb658\", \"718bcd58\", \"82154aee\", \"7b54a41d\", \"c25a59b5\", \"9c30d539\", \"2af26013\", \"c5d1b023\", \"286085f0\", \"ca417918\", \"b8db38ef\", \"8e79dcb0\", \"603a180e\", \"6c9e0e8b\", \"b01e8a3e\", \"d71577c1\", \"bd314b27\", \"78af2fda\", \"55605c60\", \"e65525f3\", \"aa55ab94\", \"57489862\", \"63e81440\", \"55ca396a\", \"2aab10b6\", \"b4cc5c34\", \"1141e8ce\", \"a15486af\", \"7c72e993\", \"b3ee1411\", \"636fbc2a\", \"2ba9c55d\", \"741831f6\", \"ce5c3e16\", \"9b87931e\", \"afd6ba33\", \"6c24cf5c\", \"7a325381\", \"28958677\", \"3b8f4898\", \"6b4bb9af\", \"c4bfe81b\", \"66282193\", \"61d809cc\", \"fb21a991\", \"487cac60\", \"5dec8032\", \"ef845d5d\", \"e98575b1\", \"dc262302\", \"eb651b88\", \"23893e81\", \"d396acc5\", \"0f6d6ff3\", \"83f44239\", \"2e0b4482\", \"a4842004\", \"69c8f04a\", \"9e1f9b5e\", \"21c66842\", \"f6e96c9a\", \"670c9c61\", \"abd388f0\", \"6a51a0d2\", \"d8542f68\", \"960fa728\", \"ab5133a3\", \"6eef0b6c\", \"137a3be4\", \"ba3bf050\", \"7efb2a98\", \"a1f1651d\", \"39af0176\", \"66ca593e\", \"82430e88\", \"8cee8619\", \"456f9fb4\", \"7d84a5c3\", \"3b8b5ebe\", \"e06f75d8\", \"85c12073\", \"401a449f\", \"56c16aa6\", \"4ed3aa62\", \"363f7706\", \"1bfedf72\", \"429b023d\", \"37d0d724\", \"d00a1248\", \"db0fead3\", \"49f1c09b\", \"075372c9\", \"80991b7b\", \"25d479d8\", \"f6e8def7\", \"e3fe501a\", \"b6794c3b\", \"976ce0bd\", \"04c006ba\", \"c1a94fb6\", \"409f60c4\", \"5e5c9ec2\", \"196a2463\", \"68fb6faf\", \"3e6c53b5\", \"1339b2eb\", \"3b52ec6f\", \"6dfc511f\", \"9b30952c\", \"cc814544\", \"af5ebd09\", \"bee3d004\", \"de334afd\", \"660f2807\", \"192e4bb3\", \"c0cba857\", \"45c8740f\", \"d20b5f39\", \"b9d3fbdb\", \"5579c0bd\", \"1a60320a\", \"d6a100c6\", \"402c7279\", \"679f25fe\", \"fb1fa3cc\", \"8ea5e9f8\", \"db3222f8\", \"3c7516df\", \"fd616b15\", \"2f501ec8\", \"ad0552ab\", \"323db5fa\", \"fd238760\", \"53317b48\", \"3e00df82\", \"9e5c57bb\", \"ca6f8ca0\", \"1a87562e\", \"df1769db\", \"d542a8f6\", \"287effc3\", \"ac6732c6\", \"8c4f5573\", \"695b27b0\", \"bbca58c8\", \"e1ffa35d\", \"b8f011a0\", \"10fa3d98\", \"fd2183b8\", \"4afcb56c\", \"2dd1d35b\", \"9a53e479\", \"b6f84565\", \"d28e49bc\", \"4bfb9790\", \"e1ddf2da\", \"a4cb7e33\", \"62fb1341\", \"cee4c6e8\", \"ef20cada\", \"36774c01\", \"d07e9efe\", \"2bf11fb4\", \"95dbda4d\", \"ae909198\", \"eaad8e71\", \"6b93d5a0\", \"d08ed1d0\", \"afc725e0\", \"8e3c5b2f\", \"8e7594b7\", \"8ff6e2fb\", \"f2122b64\", \"8888b812\", \"900df01c\", \"4fad5ea0\", \"688fc31c\", \"d1cff191\", \"b3a8c1ad\", \"2f2f2218\", \"be0e1777\", \"ea752dfe\", \"8b021fa1\", \"e5a0cc0f\", \"b56f74e8\", \"18acf3d6\", \"ce89e299\", \"b4a84fe0\", \"fd13e0b7\", \"7cc43b81\", \"d2ada8d9\", \"165fa266\", \"80957705\", \"93cc7314\", \"211a1477\", \"e6ad2065\", \"77b5fa86\", \"c75442f5\", \"fb9d35cf\", \"ebcdaf0c\", \"7b3e89a0\", \"d6411bd3\", \"ae1e7e49\", \"00250e2d\", \"2071b35e\", \"226800bb\", \"57b8e0af\", \"2464369b\", \"f009b91e\", \"5563911d\", \"59dfa6aa\", \"78c14389\", \"d95a537f\", \"207d5ba2\", \"02e5b9c5\", \"83260376\", \"6295cfa9\", \"11c81968\", \"4e734a41\", \"b3472dca\", \"7b14a94a\", \"1b510052\", \"9a532915\", \"d60f573f\", \"bc9bc6e4\", \"2b60a476\", \"81e67400\", \"08ba6fb5\", \"571be91f\", \"f296ec6b\", \"2a0dd915\", \"b6636521\", \"e7b9f9b6\", \"ff34052e\", \"c5855664\", \"53b02d5d\", \"a99f8fa1\", \"08ba4799\", \"6e85076a\" }, { \"4b7a70e9\", \"b5b32944\", \"db75092e\", \"c4192623\", \"ad6ea6b0\", \"49a7df7d\", \"9cee60b8\", \"8fedb266\", \"ecaa8c71\", \"699a17ff\", \"5664526c\", \"c2b19ee1\", \"193602a5\", \"75094c29\", \"a0591340\", \"e4183a3e\", \"3f54989a\", \"5b429d65\", \"6b8fe4d6\", \"99f73fd6\", \"a1d29c07\", \"efe830f5\", \"4d2d38e6\", \"f0255dc1\", \"4cdd2086\", \"8470eb26\", \"6382e9c6\", \"021ecc5e\", \"09686b3f\", \"3ebaefc9\", \"3c971814\", \"6b6a70a1\", \"687f3584\", \"52a0e286\", \"b79c5305\", \"aa500737\", \"3e07841c\", \"7fdeae5c\", \"8e7d44ec\", \"5716f2b8\", \"b03ada37\", \"f0500c0d\", \"f01c1f04\", \"0200b3ff\", \"ae0cf51a\", \"3cb574b2\", \"25837a58\", \"dc0921bd\", \"d19113f9\", \"7ca92ff6\", \"94324773\", \"22f54701\", \"3ae5e581\", \"37c2dadc\", \"c8b57634\", \"9af3dda7\", \"a9446146\", \"0fd0030e\", \"ecc8c73e\", \"a4751e41\", \"e238cd99\", \"3bea0e2f\", \"3280bba1\", \"183eb331\", \"4e548b38\", \"4f6db908\", \"6f420d03\", \"f60a04bf\", \"2cb81290\", \"24977c79\", \"5679b072\", \"bcaf89af\", \"de9a771f\", \"d9930810\", \"b38bae12\", \"dccf3f2e\", \"5512721f\", \"2e6b7124\", \"501adde6\", \"9f84cd87\", \"7a584718\", \"7408da17\", \"bc9f9abc\", \"e94b7d8c\", \"ec7aec3a\", \"db851dfa\", \"63094366\", \"c464c3d2\", \"ef1c1847\", \"3215d908\", \"dd433b37\", \"24c2ba16\", \"12a14d43\", \"2a65c451\", \"50940002\", \"133ae4dd\", \"71dff89e\", \"10314e55\", \"81ac77d6\", \"5f11199b\", \"043556f1\", \"d7a3c76b\", \"3c11183b\", \"5924a509\", \"f28fe6ed\", \"97f1fbfa\", \"9ebabf2c\", \"1e153c6e\", \"86e34570\", \"eae96fb1\", \"860e5e0a\", \"5a3e2ab3\", \"771fe71c\", \"4e3d06fa\", \"2965dcb9\", \"99e71d0f\", \"803e89d6\", \"5266c825\", \"2e4cc978\", \"9c10b36a\", \"c6150eba\", \"94e2ea78\", \"a5fc3c53\", \"1e0a2df4\", \"f2f74ea7\", \"361d2b3d\", \"1939260f\", \"19c27960\", \"5223a708\", \"f71312b6\", \"ebadfe6e\", \"eac31f66\", \"e3bc4595\", \"a67bc883\", \"b17f37d1\", \"018cff28\", \"c332ddef\", \"be6c5aa5\", \"65582185\", \"68ab9802\", \"eecea50f\", \"db2f953b\", \"2aef7dad\", \"5b6e2f84\", \"1521b628\", \"29076170\", \"ecdd4775\", \"619f1510\", \"13cca830\", \"eb61bd96\", \"0334fe1e\", \"aa0363cf\", \"b5735c90\", \"4c70a239\", \"d59e9e0b\", \"cbaade14\", \"eecc86bc\", \"60622ca7\", \"9cab5cab\", \"b2f3846e\", \"648b1eaf\", \"19bdf0ca\", \"a02369b9\", \"655abb50\", \"40685a32\", \"3c2ab4b3\", \"319ee9d5\", \"c021b8f7\", \"9b540b19\", \"875fa099\", \"95f7997e\", \"623d7da8\", \"f837889a\", \"97e32d77\", \"11ed935f\", \"16681281\", \"0e358829\", \"c7e61fd6\", \"96dedfa1\", \"7858ba99\", \"57f584a5\", \"1b227263\", \"9b83c3ff\", \"1ac24696\", \"cdb30aeb\", \"532e3054\", \"8fd948e4\", \"6dbc3128\", \"58ebf2ef\", \"34c6ffea\", \"fe28ed61\", \"ee7c3c73\", \"5d4a14d9\", \"e864b7e3\", \"42105d14\", \"203e13e0\", \"45eee2b6\", \"a3aaabea\", \"db6c4f15\", \"facb4fd0\", \"c742f442\", \"ef6abbb5\", \"654f3b1d\", \"41cd2105\", \"d81e799e\", \"86854dc7\", \"e44b476a\", \"3d816250\", \"cf62a1f2\", \"5b8d2646\", \"fc8883a0\", \"c1c7b6a3\", \"7f1524c3\", \"69cb7492\", \"47848a0b\", \"5692b285\", \"095bbf00\", \"ad19489d\", \"1462b174\", \"23820e00\", \"58428d2a\", \"0c55f5ea\", \"1dadf43e\", \"233f7061\", \"3372f092\", \"8d937e41\", \"d65fecf1\", \"6c223bdb\", \"7cde3759\", \"cbee7460\", \"4085f2a7\", \"ce77326e\", \"a6078084\", \"19f8509e\", \"e8efd855\", \"61d99735\", \"a969a7aa\", \"c50c06c2\", \"5a04abfc\", \"800bcadc\", \"9e447a2e\", \"c3453484\", \"fdd56705\", \"0e1e9ec9\", \"db73dbd3\", \"105588cd\", \"675fda79\", \"e3674340\", \"c5c43465\", \"713e38d8\", \"3d28f89e\", \"f16dff20\", \"153e21e7\", \"8fb03d4a\", \"e6e39f2b\", \"db83adf7\" }, { \"e93d5a68\", \"948140f7\", \"f64c261c\", \"94692934\", \"411520f7\", \"7602d4f7\", \"bcf46b2e\", \"d4a20068\", \"d4082471\", \"3320f46a\", \"43b7d4b7\", \"500061af\", \"1e39f62e\", \"97244546\", \"14214f74\", \"bf8b8840\", \"4d95fc1d\", \"96b591af\", \"70f4ddd3\", \"66a02f45\", \"bfbc09ec\", \"03bd9785\", \"7fac6dd0\", \"31cb8504\", \"96eb27b3\", \"55fd3941\", \"da2547e6\", \"abca0a9a\", \"28507825\", \"530429f4\", \"0a2c86da\", \"e9b66dfb\", \"68dc1462\", \"d7486900\", \"680ec0a4\", \"27a18dee\", \"4f3ffea2\", \"e887ad8c\", \"b58ce006\", \"7af4d6b6\", \"aace1e7c\", \"d3375fec\", \"ce78a399\", \"406b2a42\", \"20fe9e35\", \"d9f385b9\", \"ee39d7ab\", \"3b124e8b\", \"1dc9faf7\", \"4b6d1856\", \"26a36631\", \"eae397b2\", \"3a6efa74\", \"dd5b4332\", \"6841e7f7\", \"ca7820fb\", \"fb0af54e\", \"d8feb397\", \"454056ac\", \"ba489527\", \"55533a3a\", \"20838d87\", \"fe6ba9b7\", \"d096954b\", \"55a867bc\", \"a1159a58\", \"cca92963\", \"99e1db33\", \"a62a4a56\", \"3f3125f9\", \"5ef47e1c\", \"9029317c\", \"fdf8e802\", \"04272f70\", \"80bb155c\", \"05282ce3\", \"95c11548\", \"e4c66d22\", \"48c1133f\", \"c70f86dc\", \"07f9c9ee\", \"41041f0f\", \"404779a4\", \"5d886e17\", \"325f51eb\", \"d59bc0d1\", \"f2bcc18f\", \"41113564\", \"257b7834\", \"602a9c60\", \"dff8e8a3\", \"1f636c1b\", \"0e12b4c2\", \"02e1329e\", \"af664fd1\", \"cad18115\", \"6b2395e0\", \"333e92e1\", \"3b240b62\", \"eebeb922\", \"85b2a20e\", \"e6ba0d99\", \"de720c8c\", \"2da2f728\", \"d0127845\", \"95b794fd\", \"647d0862\", \"e7ccf5f0\", \"5449a36f\", \"877d48fa\", \"c39dfd27\", \"f33e8d1e\", \"0a476341\", \"992eff74\", \"3a6f6eab\", \"f4f8fd37\", \"a812dc60\", \"a1ebddf8\", \"991be14c\", \"db6e6b0d\", \"c67b5510\", \"6d672c37\", \"2765d43b\", \"dcd0e804\", \"f1290dc7\", \"cc00ffa3\", \"b5390f92\", \"690fed0b\", \"667b9ffb\", \"cedb7d9c\", \"a091cf0b\", \"d9155ea3\", \"bb132f88\", \"515bad24\", \"7b9479bf\", \"763bd6eb\", \"37392eb3\", \"cc115979\", \"8026e297\", \"f42e312d\", \"6842ada7\", \"c66a2b3b\", \"12754ccc\", \"782ef11c\", \"6a124237\", \"b79251e7\", \"06a1bbe6\", \"4bfb6350\", \"1a6b1018\", \"11caedfa\", \"3d25bdd8\", \"e2e1c3c9\", \"44421659\", \"0a121386\", \"d90cec6e\", \"d5abea2a\", \"64af674e\", \"da86a85f\", \"bebfe988\", \"64e4c3fe\", \"9dbc8057\", \"f0f7c086\", \"60787bf8\", \"6003604d\", \"d1fd8346\", \"f6381fb0\", \"7745ae04\", \"d736fccc\", \"83426b33\", \"f01eab71\", \"b0804187\", \"3c005e5f\", \"77a057be\", \"bde8ae24\", \"55464299\", \"bf582e61\", \"4e58f48f\", \"f2ddfda2\", \"f474ef38\", \"8789bdc2\", \"5366f9c3\", \"c8b38e74\", \"b475f255\", \"46fcd9b9\", \"7aeb2661\", \"8b1ddf84\", \"846a0e79\", \"915f95e2\", \"466e598e\", \"20b45770\", \"8cd55591\", \"c902de4c\", \"b90bace1\", \"bb8205d0\", \"11a86248\", \"7574a99e\", \"b77f19b6\", \"e0a9dc09\", \"662d09a1\", \"c4324633\", \"e85a1f02\", \"09f0be8c\", \"4a99a025\", \"1d6efe10\", \"1ab93d1d\", \"0ba5a4df\", \"a186f20f\", \"2868f169\", \"dcb7da83\", \"573906fe\", \"a1e2ce9b\", \"4fcd7f52\", \"50115e01\", \"a70683fa\", \"a002b5c4\", \"0de6d027\", \"9af88c27\", \"773f8641\", \"c3604c06\", \"61a806b5\", \"f0177a28\", \"c0f586e0\", \"006058aa\", \"30dc7d62\", \"11e69ed7\", \"2338ea63\", \"53c2dd94\", \"c2c21634\", \"bbcbee56\", \"90bcb6de\", \"ebfc7da1\", \"ce591d76\", \"6f05e409\", \"4b7c0188\", \"39720a3d\", \"7c927c24\", \"86e3725f\", \"724d9db9\", \"1ac15bb4\", \"d39eb8fc\", \"ed545578\", \"08fca5b5\", \"d83d7cd3\", \"4dad0fc4\", \"1e50ef5e\", \"b161e6f8\", \"a28514d9\", \"6c51133c\", \"6fd5c7e7\", \"56e14ec4\", \"362abfce\", \"ddc6c837\", \"d79a3234\", \"92638212\", \"670efa8e\", \"406000e0\" }, { \"3a39ce37\", \"d3faf5cf\", \"abc27737\", \"5ac52d1b\", \"5cb0679e\", \"4fa33742\", \"d3822740\", \"99bc9bbe\", \"d5118e9d\", \"bf0f7315\", \"d62d1c7e\", \"c700c47b\", \"b78c1b6b\", \"21a19045\", \"b26eb1be\", \"6a366eb4\", \"5748ab2f\", \"bc946e79\", \"c6a376d2\", \"6549c2c8\", \"530ff8ee\", \"468dde7d\", \"d5730a1d\", \"4cd04dc6\", \"2939bbdb\", \"a9ba4650\", \"ac9526e8\", \"be5ee304\", \"a1fad5f0\", \"6a2d519a\", \"63ef8ce2\", \"9a86ee22\", \"c089c2b8\", \"43242ef6\", \"a51e03aa\", \"9cf2d0a4\", \"83c061ba\", \"9be96a4d\", \"8fe51550\", \"ba645bd6\", \"2826a2f9\", \"a73a3ae1\", \"4ba99586\", \"ef5562e9\", \"c72fefd3\", \"f752f7da\", \"3f046f69\", \"77fa0a59\", \"80e4a915\", \"87b08601\", \"9b09e6ad\", \"3b3ee593\", \"e990fd5a\", \"9e34d797\", \"2cf0b7d9\", \"022b8b51\", \"96d5ac3a\", \"017da67d\", \"d1cf3ed6\", \"7c7d2d28\", \"1f9f25cf\", \"adf2b89b\", \"5ad6b472\", \"5a88f54c\", \"e029ac71\", \"e019a5e6\", \"47b0acfd\", \"ed93fa9b\", \"e8d3c48d\", \"283b57cc\", \"f8d56629\", \"79132e28\", \"785f0191\", \"ed756055\", \"f7960e44\", \"e3d35e8c\", \"15056dd4\", \"88f46dba\", \"03a16125\", \"0564f0bd\", \"c3eb9e15\", \"3c9057a2\", \"97271aec\", \"a93a072a\", \"1b3f6d9b\", \"1e6321f5\", \"f59c66fb\", \"26dcf319\", \"7533d928\", \"b155fdf5\", \"03563482\", \"8aba3cbb\", \"28517711\", \"c20ad9f8\", \"abcc5167\", \"ccad925f\", \"4de81751\", \"3830dc8e\", \"379d5862\", \"9320f991\", \"ea7a90c2\", \"fb3e7bce\", \"5121ce64\", \"774fbe32\", \"a8b6e37e\", \"c3293d46\", \"48de5369\", \"6413e680\", \"a2ae0810\", \"dd6db224\", \"69852dfd\", \"09072166\", \"b39a460a\", \"6445c0dd\", \"586cdecf\", \"1c20c8ae\", \"5bbef7dd\", \"1b588d40\", \"ccd2017f\", \"6bb4e3bb\", \"dda26a7e\", \"3a59ff45\", \"3e350a44\", \"bcb4cdd5\", \"72eacea8\", \"fa6484bb\", \"8d6612ae\", \"bf3c6f47\", \"d29be463\", \"542f5d9e\", \"aec2771b\", \"f64e6370\", \"740e0d8d\", \"e75b1357\", \"f8721671\", \"af537d5d\", \"4040cb08\", \"4eb4e2cc\", \"34d2466a\", \"0115af84\", \"e1b00428\", \"95983a1d\", \"06b89fb4\", \"ce6ea048\", \"6f3f3b82\", \"3520ab82\", \"011a1d4b\", \"277227f8\", \"611560b1\", \"e7933fdc\", \"bb3a792b\", \"344525bd\", \"a08839e1\", \"51ce794b\", \"2f32c9b7\", \"a01fbac9\", \"e01cc87e\", \"bcc7d1f6\", \"cf0111c3\", \"a1e8aac7\", \"1a908749\", \"d44fbd9a\", \"d0dadecb\", \"d50ada38\", \"0339c32a\", \"c6913667\", \"8df9317c\", \"e0b12b4f\", \"f79e59b7\", \"43f5bb3a\", \"f2d519ff\", \"27d9459c\", \"bf97222c\", \"15e6fc2a\", \"0f91fc71\", \"9b941525\", \"fae59361\", \"ceb69ceb\", \"c2a86459\", \"12baa8d1\", \"b6c1075e\", \"e3056a0c\", \"10d25065\", \"cb03a442\", \"e0ec6e0e\", \"1698db3b\", \"4c98a0be\", \"3278e964\", \"9f1f9532\", \"e0d392df\", \"d3a0342b\", \"8971f21e\", \"1b0a7441\", \"4ba3348c\", \"c5be7120\", \"c37632d8\", \"df359f8d\", \"9b992f2e\", \"e60b6f47\", \"0fe3f11d\", \"e54cda54\", \"1edad891\", \"ce6279cf\", \"cd3e7e6f\", \"1618b166\", \"fd2c1d05\", \"848fd2c5\", \"f6fb2299\", \"f523f357\", \"a6327623\", \"93a83531\", \"56cccd02\", \"acf08162\", \"5a75ebb5\", \"6e163697\", \"88d273cc\", \"de966292\", \"81b949d0\", \"4c50901b\", \"71c65614\", \"e6c6c7bd\", \"327a140a\", \"45e1d006\", \"c3f27b9a\", \"c9aa53fd\", \"62a80f00\", \"bb25bfe2\", \"35bdd2f6\", \"71126905\", \"b2040222\", \"b6cbcf7c\", \"cd769c2b\", \"53113ec0\", \"1640e3d3\", \"38abbd60\", \"2547adf0\", \"ba38209c\", \"f746ce76\", \"77afa1c5\", \"20756060\", \"85cbfe4e\", \"8ae88dd8\", \"7aaaf9b0\", \"4cf9aa7e\", \"1948c25c\", \"02fb8a8c\", \"01c36ae4\", \"d6ebe1f9\", \"90d4f869\", \"a65cdea0\", \"3f09252d\", \"c208e69f\", \"b74e6132\", \"ce77e25b\", \"578fdfe3\", \"3ac372e6\" } }; // Subkeys initialisation with digits of pi. String P[] = { \"243f6a88\", \"85a308d3\", \"13198a2e\", \"03707344\", \"a4093822\", \"299f31d0\", \"082efa98\", \"ec4e6c89\", \"452821e6\", \"38d01377\", \"be5466cf\", \"34e90c6c\", \"c0ac29b7\", \"c97c50dd\", \"3f84d5b5\", \"b5470917\", \"9216d5d9\", \"8979fb1b\" }; // to store 2^32(for addition modulo 2^32). long modVal = 1; // to convert hexadecimal to binary. private String hexToBin(String plainText) { String binary = \"\"; Long num; String binary4B; int n = plainText.length(); for (int i = 0; i < n; i++) { num = Long.parseUnsignedLong( plainText.charAt(i) + \"\", 16); binary4B = Long.toBinaryString(num); // each value in hexadecimal is 4 bits in binary. binary4B = \"0000\" + binary4B; binary4B = binary4B.substring(binary4B.length() - 4); binary += binary4B; } return binary; } // convert from binary to hexadecimal. private String binToHex(String plainText) { long num = Long.parseUnsignedLong(plainText, 2); String hexa = Long.toHexString(num); while (hexa.length() < (plainText.length() / 4)) // maintain output length same length // as input by appending leading zeroes. hexa = \"0\" + hexa; return hexa; } // xor two hexadecimal strings of the same length. private String xor(String a, String b) { a = hexToBin(a); b = hexToBin(b); String ans = \"\"; for (int i = 0; i < a.length(); i++) ans += (char)(((a.charAt(i) - '0') ^ (b.charAt(i) - '0')) + '0'); ans = binToHex(ans); return ans; } // addition modulo 2^32 of two hexadecimal strings. private String addBin(String a, String b) { String ans = \"\"; long n1 = Long.parseUnsignedLong(a, 16); long n2 = Long.parseUnsignedLong(b, 16); n1 = (n1 + n2) % modVal; ans = Long.toHexString(n1); ans = \"00000000\" + ans; return ans.substring(ans.length() - 8); } // function F explained above. private String f(String plainText) { String a[] = new String[4]; String ans = \"\"; for (int i = 0; i < 8; i += 2) { // the column number for S-box // is 8-bit value(8*4 = 32 bit plain text) long col = Long.parseUnsignedLong( hexToBin( plainText .substring(i, i + 2)), 2); a[i / 2] = S[i / 2][(int)col]; } ans = addBin(a[0], a[1]); ans = xor(ans, a[2]); ans = addBin(ans, a[3]); return ans; } // generate subkeys. private void keyGenerate(String key) { int j = 0; for (int i = 0; i < P.length; i++) { // xor-ing 32-bit parts of the key // with initial subkeys. P[i] = xor(P[i], key.substring(j, j + 8)); System.out.println(\"subkey \" + (i + 1) + \": \" + P[i]); j = (j + 8) % key.length(); } } // round function private String round(int time, String plainText) { String left, right; left = plainText.substring(0, 8); right = plainText.substring(8, 16); left = xor(left, P[time]); // output from F function String fOut = f(left); right = xor(fOut, right); System.out.println( \"round \" + time + \": \" + right + left); // swap left and right return right + left; } // encryption private String encrypt(String plainText) { for (int i = 0; i < 16; i++) plainText = round(i, plainText); // postprocessing String right = plainText.substring(0, 8); String left = plainText.substring(8, 16); right = xor(right, P[16]); left = xor(left, P[17]); return left + right; } Main() { // storing 2^32 in modVal //(<<1 is equivalent to multiply by 2) for (int i = 0; i < 32; i++) modVal = modVal << 1; String plainText = \"123456abcd132536\"; String key = \"aabb09182736ccdd\"; keyGenerate(key); System.out.println(\"-----Encryption-----\"); String cipherText = encrypt(plainText); System.out.println(\"Cipher Text: \" + cipherText); } public static void main(String args[]) { new Main(); }} // This code is contributed by AbhayBhat", "e": 47131, "s": 27276, "text": null }, { "code": null, "e": 47955, "s": 47131, "text": "subkey 1: 8e846390\nsubkey 2: a295c40e\nsubkey 3: b9a28336\nsubkey 4: 2446bf99\nsubkey 5: 0eb2313a\nsubkey 6: 0ea9fd0d\nsubkey 7: a295f380\nsubkey 8: cb78a054\nsubkey 9: ef9328fe\nsubkey 10: 1fe6dfaa\nsubkey 11: 14ef6fd7\nsubkey 12: 13dfc0b1\nsubkey 13: 6a1720af\nsubkey 14: ee4a9c00\nsubkey 15: 953fdcad\nsubkey 16: 9271c5ca\nsubkey 17: 38addcc1\nsubkey 18: ae4f37c6\n-----Encryption-----\nround 0: 77b3ba639cb0353b\nround 1: 0cc7d63fd5267e6d\nround 2: c799728ab5655509\nround 3: 69612395e3dfcd13\nround 4: f3f5b74b67d312af\nround 5: 52023d4efd5c4a46\nround 6: 5b785180f097cece\nround 7: cc946d119000f1d4\nround 8: 6af47a4b230745ef\nround 9: 9fb82cc57512a5e1\nround 10: 1106c1ab8b574312\nround 11: 7d7a616502d9011a\nround 12: 81e9ce71176d41ca\nround 13: 9727e50a6fa35271\nround 14: eb761e34021839a7\nround 15: 0599d9367907dbfe\nCipher Text: d748ec383d3405f7" }, { "code": null, "e": 48117, "s": 47957, "text": "The decryption process is similar to that of encryption and the subkeys are used in reverse{P[17] – P[0]}. The entire decryption process can be elaborated as: " }, { "code": null, "e": 48149, "s": 48117, "text": "Lets see each step one by one: " }, { "code": null, "e": 48180, "s": 48149, "text": "Step1: Generation of subkeys: " }, { "code": null, "e": 48239, "s": 48180, "text": "18 subkeys{P[0]...P[17]} are needed in decryption process." }, { "code": null, "e": 48326, "s": 48239, "text": "These 18 subkeys are stored in a P-array with each array element being a 32-bit entry." }, { "code": null, "e": 48370, "s": 48326, "text": "It is initialized with the digits of pi(?)." }, { "code": null, "e": 48437, "s": 48370, "text": "The hexadecimal representation of each of the subkeys is given by:" }, { "code": null, "e": 48498, "s": 48437, "text": "P[0] = \"243f6a88\"\nP[1] = \"85a308d3\"\n.\n.\n.\nP[17] = \"8979fb1b\"" }, { "code": null, "e": 48554, "s": 48498, "text": "Note: See encryption for the initial values of P-array." }, { "code": null, "e": 48623, "s": 48554, "text": "Now each of the subkeys is changed with respect to the input key as:" }, { "code": null, "e": 48912, "s": 48623, "text": "P[0] = P[0] xor 1st 32-bits of input key\nP[1] = P[1] xor 2nd 32-bits of input key\n.\n.\n.\nP[i] = P[i] xor (i+1)th 32-bits of input key\n(roll over to 1st 32-bits depending on the key length)\n.\n.\n.\nP[17] = P[17] xor 18th 32-bits of input key\n(roll over to 1st 32-bits depending on key length)" }, { "code": null, "e": 49001, "s": 48912, "text": "The resultant P-array holds 18 subkeys that is used during the entire encryption process" }, { "code": null, "e": 49040, "s": 49001, "text": "Step2: initialise Substitution Boxes: " }, { "code": null, "e": 49237, "s": 49040, "text": "4 Substitution boxes(S-boxes) are needed{S[0]...S[4]} in both encryption aswell as decryption process with each S-box having 256 entries{S[i][0]...S[i][255], 0&lei&le4} where each entry is 32-bit." }, { "code": null, "e": 49347, "s": 49237, "text": "It is initialised with the digits of pi(?) after initializing the P-array. You may find the s-boxes in here !" }, { "code": null, "e": 49367, "s": 49347, "text": "Step3: Decryption: " }, { "code": null, "e": 49723, "s": 49367, "text": "The Decryption function also consists of two parts: Rounds: The decryption also consists of 16 rounds with each round(Ri)(as explained above) taking inputs the cipherText(C.T.) from previous round and corresponding subkey(P[17-i])(i.e for decryption the subkeys are used in reverse).Post-processing: The output after the 16 rounds is processed as follows:" }, { "code": null, "e": 50027, "s": 49723, "text": "Rounds: The decryption also consists of 16 rounds with each round(Ri)(as explained above) taking inputs the cipherText(C.T.) from previous round and corresponding subkey(P[17-i])(i.e for decryption the subkeys are used in reverse).Post-processing: The output after the 16 rounds is processed as follows:" }, { "code": null, "e": 50259, "s": 50027, "text": "Rounds: The decryption also consists of 16 rounds with each round(Ri)(as explained above) taking inputs the cipherText(C.T.) from previous round and corresponding subkey(P[17-i])(i.e for decryption the subkeys are used in reverse)." }, { "code": null, "e": 50332, "s": 50259, "text": "Post-processing: The output after the 16 rounds is processed as follows:" }, { "code": null, "e": 50383, "s": 50332, "text": "Below is a Java program to demonstrate decryption " }, { "code": null, "e": 50388, "s": 50383, "text": "Java" }, { "code": "// Java program to demonstrate// Blowfish decryption Algorithm import java.util.*; public class Main { // Substitution boxes each string is a 32 bit hexadecimal value. String S[][] = { { \"d1310ba6\", \"98dfb5ac\", \"2ffd72db\", \"d01adfb7\", \"b8e1afed\", \"6a267e96\", \"ba7c9045\", \"f12c7f99\", \"24a19947\", \"b3916cf7\", \"0801f2e2\", \"858efc16\", \"636920d8\", \"71574e69\", \"a458fea3\", \"f4933d7e\", \"0d95748f\", \"728eb658\", \"718bcd58\", \"82154aee\", \"7b54a41d\", \"c25a59b5\", \"9c30d539\", \"2af26013\", \"c5d1b023\", \"286085f0\", \"ca417918\", \"b8db38ef\", \"8e79dcb0\", \"603a180e\", \"6c9e0e8b\", \"b01e8a3e\", \"d71577c1\", \"bd314b27\", \"78af2fda\", \"55605c60\", \"e65525f3\", \"aa55ab94\", \"57489862\", \"63e81440\", \"55ca396a\", \"2aab10b6\", \"b4cc5c34\", \"1141e8ce\", \"a15486af\", \"7c72e993\", \"b3ee1411\", \"636fbc2a\", \"2ba9c55d\", \"741831f6\", \"ce5c3e16\", \"9b87931e\", \"afd6ba33\", \"6c24cf5c\", \"7a325381\", \"28958677\", \"3b8f4898\", \"6b4bb9af\", \"c4bfe81b\", \"66282193\", \"61d809cc\", \"fb21a991\", \"487cac60\", \"5dec8032\", \"ef845d5d\", \"e98575b1\", \"dc262302\", \"eb651b88\", \"23893e81\", \"d396acc5\", \"0f6d6ff3\", \"83f44239\", \"2e0b4482\", \"a4842004\", \"69c8f04a\", \"9e1f9b5e\", \"21c66842\", \"f6e96c9a\", \"670c9c61\", \"abd388f0\", \"6a51a0d2\", \"d8542f68\", \"960fa728\", \"ab5133a3\", \"6eef0b6c\", \"137a3be4\", \"ba3bf050\", \"7efb2a98\", \"a1f1651d\", \"39af0176\", \"66ca593e\", \"82430e88\", \"8cee8619\", \"456f9fb4\", \"7d84a5c3\", \"3b8b5ebe\", \"e06f75d8\", \"85c12073\", \"401a449f\", \"56c16aa6\", \"4ed3aa62\", \"363f7706\", \"1bfedf72\", \"429b023d\", \"37d0d724\", \"d00a1248\", \"db0fead3\", \"49f1c09b\", \"075372c9\", \"80991b7b\", \"25d479d8\", \"f6e8def7\", \"e3fe501a\", \"b6794c3b\", \"976ce0bd\", \"04c006ba\", \"c1a94fb6\", \"409f60c4\", \"5e5c9ec2\", \"196a2463\", \"68fb6faf\", \"3e6c53b5\", \"1339b2eb\", \"3b52ec6f\", \"6dfc511f\", \"9b30952c\", \"cc814544\", \"af5ebd09\", \"bee3d004\", \"de334afd\", \"660f2807\", \"192e4bb3\", \"c0cba857\", \"45c8740f\", \"d20b5f39\", \"b9d3fbdb\", \"5579c0bd\", \"1a60320a\", \"d6a100c6\", \"402c7279\", \"679f25fe\", \"fb1fa3cc\", \"8ea5e9f8\", \"db3222f8\", \"3c7516df\", \"fd616b15\", \"2f501ec8\", \"ad0552ab\", \"323db5fa\", \"fd238760\", \"53317b48\", \"3e00df82\", \"9e5c57bb\", \"ca6f8ca0\", \"1a87562e\", \"df1769db\", \"d542a8f6\", \"287effc3\", \"ac6732c6\", \"8c4f5573\", \"695b27b0\", \"bbca58c8\", \"e1ffa35d\", \"b8f011a0\", \"10fa3d98\", \"fd2183b8\", \"4afcb56c\", \"2dd1d35b\", \"9a53e479\", \"b6f84565\", \"d28e49bc\", \"4bfb9790\", \"e1ddf2da\", \"a4cb7e33\", \"62fb1341\", \"cee4c6e8\", \"ef20cada\", \"36774c01\", \"d07e9efe\", \"2bf11fb4\", \"95dbda4d\", \"ae909198\", \"eaad8e71\", \"6b93d5a0\", \"d08ed1d0\", \"afc725e0\", \"8e3c5b2f\", \"8e7594b7\", \"8ff6e2fb\", \"f2122b64\", \"8888b812\", \"900df01c\", \"4fad5ea0\", \"688fc31c\", \"d1cff191\", \"b3a8c1ad\", \"2f2f2218\", \"be0e1777\", \"ea752dfe\", \"8b021fa1\", \"e5a0cc0f\", \"b56f74e8\", \"18acf3d6\", \"ce89e299\", \"b4a84fe0\", \"fd13e0b7\", \"7cc43b81\", \"d2ada8d9\", \"165fa266\", \"80957705\", \"93cc7314\", \"211a1477\", \"e6ad2065\", \"77b5fa86\", \"c75442f5\", \"fb9d35cf\", \"ebcdaf0c\", \"7b3e89a0\", \"d6411bd3\", \"ae1e7e49\", \"00250e2d\", \"2071b35e\", \"226800bb\", \"57b8e0af\", \"2464369b\", \"f009b91e\", \"5563911d\", \"59dfa6aa\", \"78c14389\", \"d95a537f\", \"207d5ba2\", \"02e5b9c5\", \"83260376\", \"6295cfa9\", \"11c81968\", \"4e734a41\", \"b3472dca\", \"7b14a94a\", \"1b510052\", \"9a532915\", \"d60f573f\", \"bc9bc6e4\", \"2b60a476\", \"81e67400\", \"08ba6fb5\", \"571be91f\", \"f296ec6b\", \"2a0dd915\", \"b6636521\", \"e7b9f9b6\", \"ff34052e\", \"c5855664\", \"53b02d5d\", \"a99f8fa1\", \"08ba4799\", \"6e85076a\" }, { \"4b7a70e9\", \"b5b32944\", \"db75092e\", \"c4192623\", \"ad6ea6b0\", \"49a7df7d\", \"9cee60b8\", \"8fedb266\", \"ecaa8c71\", \"699a17ff\", \"5664526c\", \"c2b19ee1\", \"193602a5\", \"75094c29\", \"a0591340\", \"e4183a3e\", \"3f54989a\", \"5b429d65\", \"6b8fe4d6\", \"99f73fd6\", \"a1d29c07\", \"efe830f5\", \"4d2d38e6\", \"f0255dc1\", \"4cdd2086\", \"8470eb26\", \"6382e9c6\", \"021ecc5e\", \"09686b3f\", \"3ebaefc9\", \"3c971814\", \"6b6a70a1\", \"687f3584\", \"52a0e286\", \"b79c5305\", \"aa500737\", \"3e07841c\", \"7fdeae5c\", \"8e7d44ec\", \"5716f2b8\", \"b03ada37\", \"f0500c0d\", \"f01c1f04\", \"0200b3ff\", \"ae0cf51a\", \"3cb574b2\", \"25837a58\", \"dc0921bd\", \"d19113f9\", \"7ca92ff6\", \"94324773\", \"22f54701\", \"3ae5e581\", \"37c2dadc\", \"c8b57634\", \"9af3dda7\", \"a9446146\", \"0fd0030e\", \"ecc8c73e\", \"a4751e41\", \"e238cd99\", \"3bea0e2f\", \"3280bba1\", \"183eb331\", \"4e548b38\", \"4f6db908\", \"6f420d03\", \"f60a04bf\", \"2cb81290\", \"24977c79\", \"5679b072\", \"bcaf89af\", \"de9a771f\", \"d9930810\", \"b38bae12\", \"dccf3f2e\", \"5512721f\", \"2e6b7124\", \"501adde6\", \"9f84cd87\", \"7a584718\", \"7408da17\", \"bc9f9abc\", \"e94b7d8c\", \"ec7aec3a\", \"db851dfa\", \"63094366\", \"c464c3d2\", \"ef1c1847\", \"3215d908\", \"dd433b37\", \"24c2ba16\", \"12a14d43\", \"2a65c451\", \"50940002\", \"133ae4dd\", \"71dff89e\", \"10314e55\", \"81ac77d6\", \"5f11199b\", \"043556f1\", \"d7a3c76b\", \"3c11183b\", \"5924a509\", \"f28fe6ed\", \"97f1fbfa\", \"9ebabf2c\", \"1e153c6e\", \"86e34570\", \"eae96fb1\", \"860e5e0a\", \"5a3e2ab3\", \"771fe71c\", \"4e3d06fa\", \"2965dcb9\", \"99e71d0f\", \"803e89d6\", \"5266c825\", \"2e4cc978\", \"9c10b36a\", \"c6150eba\", \"94e2ea78\", \"a5fc3c53\", \"1e0a2df4\", \"f2f74ea7\", \"361d2b3d\", \"1939260f\", \"19c27960\", \"5223a708\", \"f71312b6\", \"ebadfe6e\", \"eac31f66\", \"e3bc4595\", \"a67bc883\", \"b17f37d1\", \"018cff28\", \"c332ddef\", \"be6c5aa5\", \"65582185\", \"68ab9802\", \"eecea50f\", \"db2f953b\", \"2aef7dad\", \"5b6e2f84\", \"1521b628\", \"29076170\", \"ecdd4775\", \"619f1510\", \"13cca830\", \"eb61bd96\", \"0334fe1e\", \"aa0363cf\", \"b5735c90\", \"4c70a239\", \"d59e9e0b\", \"cbaade14\", \"eecc86bc\", \"60622ca7\", \"9cab5cab\", \"b2f3846e\", \"648b1eaf\", \"19bdf0ca\", \"a02369b9\", \"655abb50\", \"40685a32\", \"3c2ab4b3\", \"319ee9d5\", \"c021b8f7\", \"9b540b19\", \"875fa099\", \"95f7997e\", \"623d7da8\", \"f837889a\", \"97e32d77\", \"11ed935f\", \"16681281\", \"0e358829\", \"c7e61fd6\", \"96dedfa1\", \"7858ba99\", \"57f584a5\", \"1b227263\", \"9b83c3ff\", \"1ac24696\", \"cdb30aeb\", \"532e3054\", \"8fd948e4\", \"6dbc3128\", \"58ebf2ef\", \"34c6ffea\", \"fe28ed61\", \"ee7c3c73\", \"5d4a14d9\", \"e864b7e3\", \"42105d14\", \"203e13e0\", \"45eee2b6\", \"a3aaabea\", \"db6c4f15\", \"facb4fd0\", \"c742f442\", \"ef6abbb5\", \"654f3b1d\", \"41cd2105\", \"d81e799e\", \"86854dc7\", \"e44b476a\", \"3d816250\", \"cf62a1f2\", \"5b8d2646\", \"fc8883a0\", \"c1c7b6a3\", \"7f1524c3\", \"69cb7492\", \"47848a0b\", \"5692b285\", \"095bbf00\", \"ad19489d\", \"1462b174\", \"23820e00\", \"58428d2a\", \"0c55f5ea\", \"1dadf43e\", \"233f7061\", \"3372f092\", \"8d937e41\", \"d65fecf1\", \"6c223bdb\", \"7cde3759\", \"cbee7460\", \"4085f2a7\", \"ce77326e\", \"a6078084\", \"19f8509e\", \"e8efd855\", \"61d99735\", \"a969a7aa\", \"c50c06c2\", \"5a04abfc\", \"800bcadc\", \"9e447a2e\", \"c3453484\", \"fdd56705\", \"0e1e9ec9\", \"db73dbd3\", \"105588cd\", \"675fda79\", \"e3674340\", \"c5c43465\", \"713e38d8\", \"3d28f89e\", \"f16dff20\", \"153e21e7\", \"8fb03d4a\", \"e6e39f2b\", \"db83adf7\" }, { \"e93d5a68\", \"948140f7\", \"f64c261c\", \"94692934\", \"411520f7\", \"7602d4f7\", \"bcf46b2e\", \"d4a20068\", \"d4082471\", \"3320f46a\", \"43b7d4b7\", \"500061af\", \"1e39f62e\", \"97244546\", \"14214f74\", \"bf8b8840\", \"4d95fc1d\", \"96b591af\", \"70f4ddd3\", \"66a02f45\", \"bfbc09ec\", \"03bd9785\", \"7fac6dd0\", \"31cb8504\", \"96eb27b3\", \"55fd3941\", \"da2547e6\", \"abca0a9a\", \"28507825\", \"530429f4\", \"0a2c86da\", \"e9b66dfb\", \"68dc1462\", \"d7486900\", \"680ec0a4\", \"27a18dee\", \"4f3ffea2\", \"e887ad8c\", \"b58ce006\", \"7af4d6b6\", \"aace1e7c\", \"d3375fec\", \"ce78a399\", \"406b2a42\", \"20fe9e35\", \"d9f385b9\", \"ee39d7ab\", \"3b124e8b\", \"1dc9faf7\", \"4b6d1856\", \"26a36631\", \"eae397b2\", \"3a6efa74\", \"dd5b4332\", \"6841e7f7\", \"ca7820fb\", \"fb0af54e\", \"d8feb397\", \"454056ac\", \"ba489527\", \"55533a3a\", \"20838d87\", \"fe6ba9b7\", \"d096954b\", \"55a867bc\", \"a1159a58\", \"cca92963\", \"99e1db33\", \"a62a4a56\", \"3f3125f9\", \"5ef47e1c\", \"9029317c\", \"fdf8e802\", \"04272f70\", \"80bb155c\", \"05282ce3\", \"95c11548\", \"e4c66d22\", \"48c1133f\", \"c70f86dc\", \"07f9c9ee\", \"41041f0f\", \"404779a4\", \"5d886e17\", \"325f51eb\", \"d59bc0d1\", \"f2bcc18f\", \"41113564\", \"257b7834\", \"602a9c60\", \"dff8e8a3\", \"1f636c1b\", \"0e12b4c2\", \"02e1329e\", \"af664fd1\", \"cad18115\", \"6b2395e0\", \"333e92e1\", \"3b240b62\", \"eebeb922\", \"85b2a20e\", \"e6ba0d99\", \"de720c8c\", \"2da2f728\", \"d0127845\", \"95b794fd\", \"647d0862\", \"e7ccf5f0\", \"5449a36f\", \"877d48fa\", \"c39dfd27\", \"f33e8d1e\", \"0a476341\", \"992eff74\", \"3a6f6eab\", \"f4f8fd37\", \"a812dc60\", \"a1ebddf8\", \"991be14c\", \"db6e6b0d\", \"c67b5510\", \"6d672c37\", \"2765d43b\", \"dcd0e804\", \"f1290dc7\", \"cc00ffa3\", \"b5390f92\", \"690fed0b\", \"667b9ffb\", \"cedb7d9c\", \"a091cf0b\", \"d9155ea3\", \"bb132f88\", \"515bad24\", \"7b9479bf\", \"763bd6eb\", \"37392eb3\", \"cc115979\", \"8026e297\", \"f42e312d\", \"6842ada7\", \"c66a2b3b\", \"12754ccc\", \"782ef11c\", \"6a124237\", \"b79251e7\", \"06a1bbe6\", \"4bfb6350\", \"1a6b1018\", \"11caedfa\", \"3d25bdd8\", \"e2e1c3c9\", \"44421659\", \"0a121386\", \"d90cec6e\", \"d5abea2a\", \"64af674e\", \"da86a85f\", \"bebfe988\", \"64e4c3fe\", \"9dbc8057\", \"f0f7c086\", \"60787bf8\", \"6003604d\", \"d1fd8346\", \"f6381fb0\", \"7745ae04\", \"d736fccc\", \"83426b33\", \"f01eab71\", \"b0804187\", \"3c005e5f\", \"77a057be\", \"bde8ae24\", \"55464299\", \"bf582e61\", \"4e58f48f\", \"f2ddfda2\", \"f474ef38\", \"8789bdc2\", \"5366f9c3\", \"c8b38e74\", \"b475f255\", \"46fcd9b9\", \"7aeb2661\", \"8b1ddf84\", \"846a0e79\", \"915f95e2\", \"466e598e\", \"20b45770\", \"8cd55591\", \"c902de4c\", \"b90bace1\", \"bb8205d0\", \"11a86248\", \"7574a99e\", \"b77f19b6\", \"e0a9dc09\", \"662d09a1\", \"c4324633\", \"e85a1f02\", \"09f0be8c\", \"4a99a025\", \"1d6efe10\", \"1ab93d1d\", \"0ba5a4df\", \"a186f20f\", \"2868f169\", \"dcb7da83\", \"573906fe\", \"a1e2ce9b\", \"4fcd7f52\", \"50115e01\", \"a70683fa\", \"a002b5c4\", \"0de6d027\", \"9af88c27\", \"773f8641\", \"c3604c06\", \"61a806b5\", \"f0177a28\", \"c0f586e0\", \"006058aa\", \"30dc7d62\", \"11e69ed7\", \"2338ea63\", \"53c2dd94\", \"c2c21634\", \"bbcbee56\", \"90bcb6de\", \"ebfc7da1\", \"ce591d76\", \"6f05e409\", \"4b7c0188\", \"39720a3d\", \"7c927c24\", \"86e3725f\", \"724d9db9\", \"1ac15bb4\", \"d39eb8fc\", \"ed545578\", \"08fca5b5\", \"d83d7cd3\", \"4dad0fc4\", \"1e50ef5e\", \"b161e6f8\", \"a28514d9\", \"6c51133c\", \"6fd5c7e7\", \"56e14ec4\", \"362abfce\", \"ddc6c837\", \"d79a3234\", \"92638212\", \"670efa8e\", \"406000e0\" }, { \"3a39ce37\", \"d3faf5cf\", \"abc27737\", \"5ac52d1b\", \"5cb0679e\", \"4fa33742\", \"d3822740\", \"99bc9bbe\", \"d5118e9d\", \"bf0f7315\", \"d62d1c7e\", \"c700c47b\", \"b78c1b6b\", \"21a19045\", \"b26eb1be\", \"6a366eb4\", \"5748ab2f\", \"bc946e79\", \"c6a376d2\", \"6549c2c8\", \"530ff8ee\", \"468dde7d\", \"d5730a1d\", \"4cd04dc6\", \"2939bbdb\", \"a9ba4650\", \"ac9526e8\", \"be5ee304\", \"a1fad5f0\", \"6a2d519a\", \"63ef8ce2\", \"9a86ee22\", \"c089c2b8\", \"43242ef6\", \"a51e03aa\", \"9cf2d0a4\", \"83c061ba\", \"9be96a4d\", \"8fe51550\", \"ba645bd6\", \"2826a2f9\", \"a73a3ae1\", \"4ba99586\", \"ef5562e9\", \"c72fefd3\", \"f752f7da\", \"3f046f69\", \"77fa0a59\", \"80e4a915\", \"87b08601\", \"9b09e6ad\", \"3b3ee593\", \"e990fd5a\", \"9e34d797\", \"2cf0b7d9\", \"022b8b51\", \"96d5ac3a\", \"017da67d\", \"d1cf3ed6\", \"7c7d2d28\", \"1f9f25cf\", \"adf2b89b\", \"5ad6b472\", \"5a88f54c\", \"e029ac71\", \"e019a5e6\", \"47b0acfd\", \"ed93fa9b\", \"e8d3c48d\", \"283b57cc\", \"f8d56629\", \"79132e28\", \"785f0191\", \"ed756055\", \"f7960e44\", \"e3d35e8c\", \"15056dd4\", \"88f46dba\", \"03a16125\", \"0564f0bd\", \"c3eb9e15\", \"3c9057a2\", \"97271aec\", \"a93a072a\", \"1b3f6d9b\", \"1e6321f5\", \"f59c66fb\", \"26dcf319\", \"7533d928\", \"b155fdf5\", \"03563482\", \"8aba3cbb\", \"28517711\", \"c20ad9f8\", \"abcc5167\", \"ccad925f\", \"4de81751\", \"3830dc8e\", \"379d5862\", \"9320f991\", \"ea7a90c2\", \"fb3e7bce\", \"5121ce64\", \"774fbe32\", \"a8b6e37e\", \"c3293d46\", \"48de5369\", \"6413e680\", \"a2ae0810\", \"dd6db224\", \"69852dfd\", \"09072166\", \"b39a460a\", \"6445c0dd\", \"586cdecf\", \"1c20c8ae\", \"5bbef7dd\", \"1b588d40\", \"ccd2017f\", \"6bb4e3bb\", \"dda26a7e\", \"3a59ff45\", \"3e350a44\", \"bcb4cdd5\", \"72eacea8\", \"fa6484bb\", \"8d6612ae\", \"bf3c6f47\", \"d29be463\", \"542f5d9e\", \"aec2771b\", \"f64e6370\", \"740e0d8d\", \"e75b1357\", \"f8721671\", \"af537d5d\", \"4040cb08\", \"4eb4e2cc\", \"34d2466a\", \"0115af84\", \"e1b00428\", \"95983a1d\", \"06b89fb4\", \"ce6ea048\", \"6f3f3b82\", \"3520ab82\", \"011a1d4b\", \"277227f8\", \"611560b1\", \"e7933fdc\", \"bb3a792b\", \"344525bd\", \"a08839e1\", \"51ce794b\", \"2f32c9b7\", \"a01fbac9\", \"e01cc87e\", \"bcc7d1f6\", \"cf0111c3\", \"a1e8aac7\", \"1a908749\", \"d44fbd9a\", \"d0dadecb\", \"d50ada38\", \"0339c32a\", \"c6913667\", \"8df9317c\", \"e0b12b4f\", \"f79e59b7\", \"43f5bb3a\", \"f2d519ff\", \"27d9459c\", \"bf97222c\", \"15e6fc2a\", \"0f91fc71\", \"9b941525\", \"fae59361\", \"ceb69ceb\", \"c2a86459\", \"12baa8d1\", \"b6c1075e\", \"e3056a0c\", \"10d25065\", \"cb03a442\", \"e0ec6e0e\", \"1698db3b\", \"4c98a0be\", \"3278e964\", \"9f1f9532\", \"e0d392df\", \"d3a0342b\", \"8971f21e\", \"1b0a7441\", \"4ba3348c\", \"c5be7120\", \"c37632d8\", \"df359f8d\", \"9b992f2e\", \"e60b6f47\", \"0fe3f11d\", \"e54cda54\", \"1edad891\", \"ce6279cf\", \"cd3e7e6f\", \"1618b166\", \"fd2c1d05\", \"848fd2c5\", \"f6fb2299\", \"f523f357\", \"a6327623\", \"93a83531\", \"56cccd02\", \"acf08162\", \"5a75ebb5\", \"6e163697\", \"88d273cc\", \"de966292\", \"81b949d0\", \"4c50901b\", \"71c65614\", \"e6c6c7bd\", \"327a140a\", \"45e1d006\", \"c3f27b9a\", \"c9aa53fd\", \"62a80f00\", \"bb25bfe2\", \"35bdd2f6\", \"71126905\", \"b2040222\", \"b6cbcf7c\", \"cd769c2b\", \"53113ec0\", \"1640e3d3\", \"38abbd60\", \"2547adf0\", \"ba38209c\", \"f746ce76\", \"77afa1c5\", \"20756060\", \"85cbfe4e\", \"8ae88dd8\", \"7aaaf9b0\", \"4cf9aa7e\", \"1948c25c\", \"02fb8a8c\", \"01c36ae4\", \"d6ebe1f9\", \"90d4f869\", \"a65cdea0\", \"3f09252d\", \"c208e69f\", \"b74e6132\", \"ce77e25b\", \"578fdfe3\", \"3ac372e6\" } }; // Subkeys initialisation with digits of pi. String P[] = { \"243f6a88\", \"85a308d3\", \"13198a2e\", \"03707344\", \"a4093822\", \"299f31d0\", \"082efa98\", \"ec4e6c89\", \"452821e6\", \"38d01377\", \"be5466cf\", \"34e90c6c\", \"c0ac29b7\", \"c97c50dd\", \"3f84d5b5\", \"b5470917\", \"9216d5d9\", \"8979fb1b\" }; // to store 2^32(for addition modulo 2^32). long modVal = 1; // to convert hexadecimal to binary. private String hexToBin(String plainText) { String binary = \"\"; Long num; String binary4B; int n = plainText.length(); for (int i = 0; i < n; i++) { num = Long.parseUnsignedLong( plainText.charAt(i) + \"\", 16); binary4B = Long.toBinaryString(num); // each value in hexadecimal // is 4 bits in binary. binary4B = \"0000\" + binary4B; binary4B = binary4B.substring( binary4B.length() - 4); binary += binary4B; } return binary; } // convert from binary to hexadecimal. private String binToHex(String plainText) { long num = Long.parseUnsignedLong(plainText, 2); String hexa = Long.toHexString(num); while (hexa.length() < (plainText.length() / 4)) // maintain output length same length // as input by appending leading zeroes. hexa = \"0\" + hexa; return hexa; } // xor two hexadecimal strings of same length. private String xor(String a, String b) { a = hexToBin(a); b = hexToBin(b); String ans = \"\"; for (int i = 0; i < a.length(); i++) ans += (char)(((a.charAt(i) - '0') ^ (b.charAt(i) - '0')) + '0'); ans = binToHex(ans); return ans; } // addition modulo 2^32 of two hexadecimal strings. private String addBin(String a, String b) { String ans = \"\"; long n1 = Long.parseUnsignedLong(a, 16); long n2 = Long.parseUnsignedLong(b, 16); n1 = (n1 + n2) % modVal; ans = Long.toHexString(n1); ans = \"00000000\" + ans; return ans.substring(ans.length() - 8); } // function F explained above. private String f(String plainText) { String a[] = new String[4]; String ans = \"\"; for (int i = 0; i < 8; i += 2) { // the column number for S-box // is 8-bit value(8*4 = 32 bit plain text) long col = Long.parseUnsignedLong( hexToBin( plainText.substring(i, i + 2)), 2); a[i / 2] = S[i / 2][(int)col]; } ans = addBin(a[0], a[1]); ans = xor(ans, a[2]); ans = addBin(ans, a[3]); return ans; } // generate subkeys. private void keyGenerate(String key) { int j = 0; for (int i = 0; i < P.length; i++) { P[i] = xor(P[i], key.substring(j, j + 8)); System.out.println(\"subkey \" + (i + 1) + \": \" + P[i]); j = (j + 8) % key.length(); } } // round function private String round(int time, String plainText) { String left, right; left = plainText.substring(0, 8); right = plainText.substring(8, 16); left = xor(left, P[time]); String fOut = f(left); // output from F function right = xor(fOut, right); System.out.println(\"round \" + time + \": \" + right + left); // swap left and right return right + left; } // decryption private String decrypt(String plainText) { for (int i = 17; i > 1; i--) plainText = round(i, plainText); // postprocessing String right = plainText.substring(0, 8); String left = plainText.substring(8, 16); right = xor(right, P[1]); left = xor(left, P[0]); return left + right; } Main() { // storing 2^32 in modVal //(<<1 is equivalent to multiply by 2) for (int i = 0; i < 32; i++) modVal = modVal << 1; String cipherText = \"d748ec383d3405f7\"; String key = \"aabb09182736ccdd\"; keyGenerate(key); System.out.println(\"-----Decryption-----\"); String plainText = decrypt(cipherText); System.out.println(\"Plain Text: \" + plainText); } public static void main(String args[]) { new Main(); }} // This code is contributed by AbhayBhat", "e": 70219, "s": 50388, "text": null }, { "code": null, "e": 71044, "s": 70219, "text": "subkey 1: 8e846390\nsubkey 2: a295c40e\nsubkey 3: b9a28336\nsubkey 4: 2446bf99\nsubkey 5: 0eb2313a\nsubkey 6: 0ea9fd0d\nsubkey 7: a295f380\nsubkey 8: cb78a054\nsubkey 9: ef9328fe\nsubkey 10: 1fe6dfaa\nsubkey 11: 14ef6fd7\nsubkey 12: 13dfc0b1\nsubkey 13: 6a1720af\nsubkey 14: ee4a9c00\nsubkey 15: 953fdcad\nsubkey 16: 9271c5ca\nsubkey 17: 38addcc1\nsubkey 18: ae4f37c6\n-----Decryption-----\nround 17: 3ab5e5667907dbfe\nround 16: fdd297bb021839a7\nround 15: 82529d676fa35271\nround 14: ec939d1a176d41ca\nround 13: e14063bd02d9011a\nround 12: 66cd65508b574312\nround 11: 37e82a387512a5e1\nround 10: 8fe62e7e230745ef\nround 9: 1f04e6309000f1d4\nround 8: 3624ea12f097cece\nround 7: c546e12ffd5c4a46\nround 6: ed76301e67d312af\nround 5: bbd76433e3dfcd13\nround 4: f160c1f4b5655509\nround 3: 2512b60dd5267e6d\nround 2: 6f86e1389cb0353b\nPlain Text: 123456abcd132536" }, { "code": null, "e": 71171, "s": 71046, "text": "Blowfish is a fast block cipher except when changing keys. Each new key requires a pre-processing equivalent to 4KB of text." }, { "code": null, "e": 71221, "s": 71171, "text": "It is faster and much better than DES Encryption." }, { "code": null, "e": 71302, "s": 71221, "text": "Blowfish uses a 64-bit block size which makes it vulnerable to birthday attacks." }, { "code": null, "e": 71439, "s": 71302, "text": "A reduced round variant of blowfish is known to be susceptible to known plain text attacks(2nd order differential attacks – 4 rounds). " }, { "code": null, "e": 71456, "s": 71439, "text": "Bulk Encryption." }, { "code": null, "e": 71487, "s": 71456, "text": "Packet Encryption(ATM Packets)" }, { "code": null, "e": 71506, "s": 71487, "text": "Password Hashing " }, { "code": null, "e": 71521, "s": 71506, "text": "varshagumber28" }, { "code": null, "e": 71534, "s": 71521, "text": "cryptography" }, { "code": null, "e": 71545, "s": 71534, "text": "Algorithms" }, { "code": null, "e": 71558, "s": 71545, "text": "cryptography" }, { "code": null, "e": 71569, "s": 71558, "text": "Algorithms" }, { "code": null, "e": 71667, "s": 71569, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 71676, "s": 71667, "text": "Comments" }, { "code": null, "e": 71689, "s": 71676, "text": "Old Comments" }, { "code": null, "e": 71714, "s": 71689, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 71743, "s": 71714, "text": "Quadratic Probing in Hashing" }, { "code": null, "e": 71786, "s": 71743, "text": "SCAN (Elevator) Disk Scheduling Algorithms" }, { "code": null, "e": 71820, "s": 71786, "text": "K means Clustering - Introduction" }, { "code": null, "e": 71876, "s": 71820, "text": "Difference between Informed and Uninformed Search in AI" }, { "code": null, "e": 71919, "s": 71876, "text": "Program for SSTF disk scheduling algorithm" }, { "code": null, "e": 71972, "s": 71919, "text": "Difference between Algorithm, Pseudocode and Program" }, { "code": null, "e": 71993, "s": 71972, "text": "K-Nearest Neighbours" }, { "code": null, "e": 72055, "s": 71993, "text": "Travelling Salesman Problem implementation using BackTracking" } ]
A Non-Confusing Guide to Confusion Matrix | by Dario Radečić | Towards Data Science
You are hyped about machine learning. You don’t know much about statistics, but you know what the mean is. You’ve decided to skip all the prerequisites and train your first machine learning model. You’ve followed a code-along video tutorial by some Indian on YouTube. After spending 10 hours realizing you’ve missed an indentation on IF statement, your model is finally trained. You’ve obtained above 90% accuracy. Life is good. But I’m here to tell you, your model most probably sucks. And that’s expected, heck, that’s great! Jokes aside, model evaluation can be difficult when you are a novice in data science and machine learning. The confusion matrix is something that confuses you, and that’s expected. You won’t believe how many stuff you can pull from stupidly simple-looking 2x2 matrix. Here’s an example of a confusion matrix obtained after model training: Is it good? Is it bad? The answer is your favorite — it depends (results are horrible in this case). Here’s a more generic-looking confusion matrix: Yeah, I know what you are thinking — good job, moron, now I’m even more confused! But hold your horses, let’s break it down into smaller, more understandable chunks. Values from the dataset (ones from the target variable) Values your model predicted Value in the target variable If predicting disease, this would be ‘Has a disease’ 1 in the binary target variable Value in the target variable If predicting disease, this would be ‘Doesn’t have a disease’ 0 in the binary target variable Okay, that was easily understandable, but what do those true positives and negatives mean? Good question reader. I was wondering when you will ask that. Explanations of those will be very easy for you to read. But they will be even easier to forget, so you might want to re-read them every couple of days. Or even better, write them down on a piece of paper. Writing something down will make it much easier to stick. But I’m getting off point here, we were talking about false positives and true negatives, let’s dive into those. Your model predicted positive and the actual is positive Would be 1 in the binomial variable Eg. you predicted that the patient has a disease and he has it Your model predicted positive and the actual is negative The model predicted 1, but it’s 0 in the binomial variable Eg. you predicted that the patient has a disease but he doesn’t have it Type I Error Your model predicted negative and the actual is positive The model predicted 0, but it’s 1 in the binomial variable Eg. you predicted that the patient doesn’t have the disease, but he has it Type II Error Your model predicted negative and the actual is negative The model predicted 0, and it’s 0 in the binomial variable Eg. you predicted that the patient doesn’t have the disease, and he doesn’t have it You see, there isn’t anything confusing about confusion matrix. Sure, you need to memorize those terms, and yeah, they sound similar, but at least they aren’t as abstract as some other machine learning concepts you’ve probably encountered. After reading all of that stuff about positive and negatives (a couple of times preferably), you now have a basic idea and intuition about confusion matrix, and you see that it’s not that confusing after all — it just needs to “sink in” properly. But is that all about confusion matrix? I hope you’re kidding. We’re only about halfway through. Maybe. Up next I want to discuss various scorings that can be obtained from the confusion matrix. And there are a lot of them. Here’s the list of all of them, according to Wikipedia[1]: Sensitivity / Recall / Hit Rate / True Positive Rate (TPR)Specificity / Selectivity / True Negative Rate (TNR)Precision / Positive Predictive Value (PPV)Negative Predictive Value (NPV)Miss Rate / False Negative Rate (FNR)Fall-out / False Positive Rate (FPR)False Discovery Rate (FDR)False Omission Rate (FOR)Threat Score / Critical Success Index (CSI)Accuracy (ACC)F1 ScoreMatthews Correlation Coefficient (MCC)Informedness / Bookmaker Informediness (BM)Markedness (MK) Sensitivity / Recall / Hit Rate / True Positive Rate (TPR) Specificity / Selectivity / True Negative Rate (TNR) Precision / Positive Predictive Value (PPV) Negative Predictive Value (NPV) Miss Rate / False Negative Rate (FNR) Fall-out / False Positive Rate (FPR) False Discovery Rate (FDR) False Omission Rate (FOR) Threat Score / Critical Success Index (CSI) Accuracy (ACC) F1 Score Matthews Correlation Coefficient (MCC) Informedness / Bookmaker Informediness (BM) Markedness (MK) Feeling confused? That’s expected. I am also. I’ve never heard for some of those terms, but I still wanted to put them here, just to prove that you can understand everything confusion matrix has to offer without you know, going insane. But it’s amazing to think about how you can calculate so many different scorings just from this plainly stupid-looking 2x2 matrix. I mean that are only 4 numbers, for God sake! For the second part of this article, I want to drill down to most commonly used scorings in the realm of machine learning, and those are: Accuracy Recall Precision F1 Score That’s right, I’ll cover only 4 of 14 because I feel that those are most important and that you’ll be perfectly capable of optimizing your model with just basic understanding of those. You don’t need to memorize the formula, those are already built-in to Python’s Scikit-Learn, but you should know when to choose one over the other. Before diving right in, let’s see the confusion matrix you’ll be working on: And to boil it down, in the given matrix we have: True Negatives (TN) — 1943 False Positives (FP) — 32 True Positives (TP) — 181 False Negatives (FN) — 344 As you might have noticed, this is the same confusion matrix from the beginning of the article, just more nicely presented. Without further ado, let’s dive into the scorings! Most intuitive to understand — a ratio of correctly predicted observation to the total observations Not well suited for most business needs The calculation is straightforward: all true instances are divided by the number of total instances (TP+TN) / (TP+FP+FN+TN) Implementation in Python: from sklearn.metrics import accuracy_scoreprint(accuracy_score(y_true, y_pred))>>> 0.8496 The ability of a model to find all the relevant cases within a dataset For our example, it would be the ability of the model to find all cases where the patient has the disease The calculation is straightforward: divide True Positives (TP) by the sum of True Positives (TP) and False Negatives (FN) TP / (TP + FN) Python Implementation: from sklearn.metrics import recall_scoreprint(recall_score(y_true, y_pred))>>> 0.3448 The ability of a model to identify only the relevant data points For our example, it would be the ability of the model to correctly classify patients that don’t have the disease Calculation: divide True Positives (TP) by the sum of True Positives (TP) and False Positives (FP) TP / (TP + FP) Implementation in Python: from sklearn.metrics import precision_scoreprint(precision_score(y_true, y_pred))>>> 0.8498 The weighted average of Precision and Recall. Takes both false positives and false negatives into account You have low False Positives (FP) and low False Negatives (FN) — correctly identifying real threats and you are not disturbed by false alarms The calculation needs both Recall and Precision previously calculated 2*(Recall * Precision) / (Recall + Precision) Implementation in Python: from sklearn.metrics import f1_scoreprint(f1_score(y_true, y_pred))>>> 0.4905 Those explanations should give you a clear picture that using accuracy as a scoring metric isn’t always a good option. In our case with patients and diseases, it would be better to use recall, because you probably want to correctly identify each patient which has a disease — just think how horrible would it be to have a large number of misclassifications in cancer detection. And that’s right about enough materials to keep you busy for some time. When this becomes easy to you, please refer to the Wikipedia article (posted at the bottom of the article) to learn a few more scorings. My intention was to break down this stupidly simple-looking matrix in a non-confusing way because it can get very confusing when you encounter it for the first time. I certainly didn’t say all there is about the topic, but every key idea and concept is here, waiting to be learned. It’s so easy to forget this stuff and trying to learn it in a single day will only make those terms to mix up even further. Slow and steady wins the race. Yes, most of the terms are called similarly and you will be confused by it — and that is perfectly normal. Review the materials every now and then, from whichever article you want. What are your thoughts? Is there anything you don’t understand after a couple of readings? Feel free to drop a comment below. Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you.
[ { "code": null, "e": 551, "s": 172, "text": "You are hyped about machine learning. You don’t know much about statistics, but you know what the mean is. You’ve decided to skip all the prerequisites and train your first machine learning model. You’ve followed a code-along video tutorial by some Indian on YouTube. After spending 10 hours realizing you’ve missed an indentation on IF statement, your model is finally trained." }, { "code": null, "e": 601, "s": 551, "text": "You’ve obtained above 90% accuracy. Life is good." }, { "code": null, "e": 700, "s": 601, "text": "But I’m here to tell you, your model most probably sucks. And that’s expected, heck, that’s great!" }, { "code": null, "e": 968, "s": 700, "text": "Jokes aside, model evaluation can be difficult when you are a novice in data science and machine learning. The confusion matrix is something that confuses you, and that’s expected. You won’t believe how many stuff you can pull from stupidly simple-looking 2x2 matrix." }, { "code": null, "e": 1039, "s": 968, "text": "Here’s an example of a confusion matrix obtained after model training:" }, { "code": null, "e": 1140, "s": 1039, "text": "Is it good? Is it bad? The answer is your favorite — it depends (results are horrible in this case)." }, { "code": null, "e": 1188, "s": 1140, "text": "Here’s a more generic-looking confusion matrix:" }, { "code": null, "e": 1354, "s": 1188, "text": "Yeah, I know what you are thinking — good job, moron, now I’m even more confused! But hold your horses, let’s break it down into smaller, more understandable chunks." }, { "code": null, "e": 1410, "s": 1354, "text": "Values from the dataset (ones from the target variable)" }, { "code": null, "e": 1438, "s": 1410, "text": "Values your model predicted" }, { "code": null, "e": 1467, "s": 1438, "text": "Value in the target variable" }, { "code": null, "e": 1520, "s": 1467, "text": "If predicting disease, this would be ‘Has a disease’" }, { "code": null, "e": 1552, "s": 1520, "text": "1 in the binary target variable" }, { "code": null, "e": 1581, "s": 1552, "text": "Value in the target variable" }, { "code": null, "e": 1643, "s": 1581, "text": "If predicting disease, this would be ‘Doesn’t have a disease’" }, { "code": null, "e": 1675, "s": 1643, "text": "0 in the binary target variable" }, { "code": null, "e": 1766, "s": 1675, "text": "Okay, that was easily understandable, but what do those true positives and negatives mean?" }, { "code": null, "e": 2205, "s": 1766, "text": "Good question reader. I was wondering when you will ask that. Explanations of those will be very easy for you to read. But they will be even easier to forget, so you might want to re-read them every couple of days. Or even better, write them down on a piece of paper. Writing something down will make it much easier to stick. But I’m getting off point here, we were talking about false positives and true negatives, let’s dive into those." }, { "code": null, "e": 2262, "s": 2205, "text": "Your model predicted positive and the actual is positive" }, { "code": null, "e": 2298, "s": 2262, "text": "Would be 1 in the binomial variable" }, { "code": null, "e": 2361, "s": 2298, "text": "Eg. you predicted that the patient has a disease and he has it" }, { "code": null, "e": 2418, "s": 2361, "text": "Your model predicted positive and the actual is negative" }, { "code": null, "e": 2477, "s": 2418, "text": "The model predicted 1, but it’s 0 in the binomial variable" }, { "code": null, "e": 2549, "s": 2477, "text": "Eg. you predicted that the patient has a disease but he doesn’t have it" }, { "code": null, "e": 2562, "s": 2549, "text": "Type I Error" }, { "code": null, "e": 2619, "s": 2562, "text": "Your model predicted negative and the actual is positive" }, { "code": null, "e": 2678, "s": 2619, "text": "The model predicted 0, but it’s 1 in the binomial variable" }, { "code": null, "e": 2753, "s": 2678, "text": "Eg. you predicted that the patient doesn’t have the disease, but he has it" }, { "code": null, "e": 2767, "s": 2753, "text": "Type II Error" }, { "code": null, "e": 2824, "s": 2767, "text": "Your model predicted negative and the actual is negative" }, { "code": null, "e": 2883, "s": 2824, "text": "The model predicted 0, and it’s 0 in the binomial variable" }, { "code": null, "e": 2967, "s": 2883, "text": "Eg. you predicted that the patient doesn’t have the disease, and he doesn’t have it" }, { "code": null, "e": 3207, "s": 2967, "text": "You see, there isn’t anything confusing about confusion matrix. Sure, you need to memorize those terms, and yeah, they sound similar, but at least they aren’t as abstract as some other machine learning concepts you’ve probably encountered." }, { "code": null, "e": 3454, "s": 3207, "text": "After reading all of that stuff about positive and negatives (a couple of times preferably), you now have a basic idea and intuition about confusion matrix, and you see that it’s not that confusing after all — it just needs to “sink in” properly." }, { "code": null, "e": 3494, "s": 3454, "text": "But is that all about confusion matrix?" }, { "code": null, "e": 3558, "s": 3494, "text": "I hope you’re kidding. We’re only about halfway through. Maybe." }, { "code": null, "e": 3737, "s": 3558, "text": "Up next I want to discuss various scorings that can be obtained from the confusion matrix. And there are a lot of them. Here’s the list of all of them, according to Wikipedia[1]:" }, { "code": null, "e": 4207, "s": 3737, "text": "Sensitivity / Recall / Hit Rate / True Positive Rate (TPR)Specificity / Selectivity / True Negative Rate (TNR)Precision / Positive Predictive Value (PPV)Negative Predictive Value (NPV)Miss Rate / False Negative Rate (FNR)Fall-out / False Positive Rate (FPR)False Discovery Rate (FDR)False Omission Rate (FOR)Threat Score / Critical Success Index (CSI)Accuracy (ACC)F1 ScoreMatthews Correlation Coefficient (MCC)Informedness / Bookmaker Informediness (BM)Markedness (MK)" }, { "code": null, "e": 4266, "s": 4207, "text": "Sensitivity / Recall / Hit Rate / True Positive Rate (TPR)" }, { "code": null, "e": 4319, "s": 4266, "text": "Specificity / Selectivity / True Negative Rate (TNR)" }, { "code": null, "e": 4363, "s": 4319, "text": "Precision / Positive Predictive Value (PPV)" }, { "code": null, "e": 4395, "s": 4363, "text": "Negative Predictive Value (NPV)" }, { "code": null, "e": 4433, "s": 4395, "text": "Miss Rate / False Negative Rate (FNR)" }, { "code": null, "e": 4470, "s": 4433, "text": "Fall-out / False Positive Rate (FPR)" }, { "code": null, "e": 4497, "s": 4470, "text": "False Discovery Rate (FDR)" }, { "code": null, "e": 4523, "s": 4497, "text": "False Omission Rate (FOR)" }, { "code": null, "e": 4567, "s": 4523, "text": "Threat Score / Critical Success Index (CSI)" }, { "code": null, "e": 4582, "s": 4567, "text": "Accuracy (ACC)" }, { "code": null, "e": 4591, "s": 4582, "text": "F1 Score" }, { "code": null, "e": 4630, "s": 4591, "text": "Matthews Correlation Coefficient (MCC)" }, { "code": null, "e": 4674, "s": 4630, "text": "Informedness / Bookmaker Informediness (BM)" }, { "code": null, "e": 4690, "s": 4674, "text": "Markedness (MK)" }, { "code": null, "e": 4926, "s": 4690, "text": "Feeling confused? That’s expected. I am also. I’ve never heard for some of those terms, but I still wanted to put them here, just to prove that you can understand everything confusion matrix has to offer without you know, going insane." }, { "code": null, "e": 5103, "s": 4926, "text": "But it’s amazing to think about how you can calculate so many different scorings just from this plainly stupid-looking 2x2 matrix. I mean that are only 4 numbers, for God sake!" }, { "code": null, "e": 5241, "s": 5103, "text": "For the second part of this article, I want to drill down to most commonly used scorings in the realm of machine learning, and those are:" }, { "code": null, "e": 5250, "s": 5241, "text": "Accuracy" }, { "code": null, "e": 5257, "s": 5250, "text": "Recall" }, { "code": null, "e": 5267, "s": 5257, "text": "Precision" }, { "code": null, "e": 5276, "s": 5267, "text": "F1 Score" }, { "code": null, "e": 5609, "s": 5276, "text": "That’s right, I’ll cover only 4 of 14 because I feel that those are most important and that you’ll be perfectly capable of optimizing your model with just basic understanding of those. You don’t need to memorize the formula, those are already built-in to Python’s Scikit-Learn, but you should know when to choose one over the other." }, { "code": null, "e": 5686, "s": 5609, "text": "Before diving right in, let’s see the confusion matrix you’ll be working on:" }, { "code": null, "e": 5736, "s": 5686, "text": "And to boil it down, in the given matrix we have:" }, { "code": null, "e": 5763, "s": 5736, "text": "True Negatives (TN) — 1943" }, { "code": null, "e": 5789, "s": 5763, "text": "False Positives (FP) — 32" }, { "code": null, "e": 5815, "s": 5789, "text": "True Positives (TP) — 181" }, { "code": null, "e": 5842, "s": 5815, "text": "False Negatives (FN) — 344" }, { "code": null, "e": 6017, "s": 5842, "text": "As you might have noticed, this is the same confusion matrix from the beginning of the article, just more nicely presented. Without further ado, let’s dive into the scorings!" }, { "code": null, "e": 6117, "s": 6017, "text": "Most intuitive to understand — a ratio of correctly predicted observation to the total observations" }, { "code": null, "e": 6157, "s": 6117, "text": "Not well suited for most business needs" }, { "code": null, "e": 6257, "s": 6157, "text": "The calculation is straightforward: all true instances are divided by the number of total instances" }, { "code": null, "e": 6281, "s": 6257, "text": "(TP+TN) / (TP+FP+FN+TN)" }, { "code": null, "e": 6307, "s": 6281, "text": "Implementation in Python:" }, { "code": null, "e": 6397, "s": 6307, "text": "from sklearn.metrics import accuracy_scoreprint(accuracy_score(y_true, y_pred))>>> 0.8496" }, { "code": null, "e": 6468, "s": 6397, "text": "The ability of a model to find all the relevant cases within a dataset" }, { "code": null, "e": 6574, "s": 6468, "text": "For our example, it would be the ability of the model to find all cases where the patient has the disease" }, { "code": null, "e": 6696, "s": 6574, "text": "The calculation is straightforward: divide True Positives (TP) by the sum of True Positives (TP) and False Negatives (FN)" }, { "code": null, "e": 6711, "s": 6696, "text": "TP / (TP + FN)" }, { "code": null, "e": 6734, "s": 6711, "text": "Python Implementation:" }, { "code": null, "e": 6820, "s": 6734, "text": "from sklearn.metrics import recall_scoreprint(recall_score(y_true, y_pred))>>> 0.3448" }, { "code": null, "e": 6885, "s": 6820, "text": "The ability of a model to identify only the relevant data points" }, { "code": null, "e": 6998, "s": 6885, "text": "For our example, it would be the ability of the model to correctly classify patients that don’t have the disease" }, { "code": null, "e": 7097, "s": 6998, "text": "Calculation: divide True Positives (TP) by the sum of True Positives (TP) and False Positives (FP)" }, { "code": null, "e": 7112, "s": 7097, "text": "TP / (TP + FP)" }, { "code": null, "e": 7138, "s": 7112, "text": "Implementation in Python:" }, { "code": null, "e": 7230, "s": 7138, "text": "from sklearn.metrics import precision_scoreprint(precision_score(y_true, y_pred))>>> 0.8498" }, { "code": null, "e": 7276, "s": 7230, "text": "The weighted average of Precision and Recall." }, { "code": null, "e": 7336, "s": 7276, "text": "Takes both false positives and false negatives into account" }, { "code": null, "e": 7478, "s": 7336, "text": "You have low False Positives (FP) and low False Negatives (FN) — correctly identifying real threats and you are not disturbed by false alarms" }, { "code": null, "e": 7548, "s": 7478, "text": "The calculation needs both Recall and Precision previously calculated" }, { "code": null, "e": 7594, "s": 7548, "text": "2*(Recall * Precision) / (Recall + Precision)" }, { "code": null, "e": 7620, "s": 7594, "text": "Implementation in Python:" }, { "code": null, "e": 7698, "s": 7620, "text": "from sklearn.metrics import f1_scoreprint(f1_score(y_true, y_pred))>>> 0.4905" }, { "code": null, "e": 8076, "s": 7698, "text": "Those explanations should give you a clear picture that using accuracy as a scoring metric isn’t always a good option. In our case with patients and diseases, it would be better to use recall, because you probably want to correctly identify each patient which has a disease — just think how horrible would it be to have a large number of misclassifications in cancer detection." }, { "code": null, "e": 8285, "s": 8076, "text": "And that’s right about enough materials to keep you busy for some time. When this becomes easy to you, please refer to the Wikipedia article (posted at the bottom of the article) to learn a few more scorings." }, { "code": null, "e": 8451, "s": 8285, "text": "My intention was to break down this stupidly simple-looking matrix in a non-confusing way because it can get very confusing when you encounter it for the first time." }, { "code": null, "e": 8722, "s": 8451, "text": "I certainly didn’t say all there is about the topic, but every key idea and concept is here, waiting to be learned. It’s so easy to forget this stuff and trying to learn it in a single day will only make those terms to mix up even further. Slow and steady wins the race." }, { "code": null, "e": 8903, "s": 8722, "text": "Yes, most of the terms are called similarly and you will be confused by it — and that is perfectly normal. Review the materials every now and then, from whichever article you want." }, { "code": null, "e": 9029, "s": 8903, "text": "What are your thoughts? Is there anything you don’t understand after a couple of readings? Feel free to drop a comment below." } ]
How to handle error object in JSP using JSTL tags?
You can make use of JSTL tags to write an error page ShowError.jsp with better structure and more information − <%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %> <%@page isErrorPage = "true" %> <html> <head> <title>Show Error Page</title> </head> <body> <h1>Opps...</h1> <table width = "100%" border = "1"> <tr valign = "top"> <td width = "40%"><b>Error:</b></td> <td>${pageContext.exception}</td> </tr> <tr valign = "top"> <td><b>URI:</b></td> <td>${pageContext.errorData.requestURI}</td> </tr> <tr valign = "top"> <td><b>Status code:</b></td> <td>${pageContext.errorData.statusCode}</td> </tr> <tr valign = "top"> <td><b>Stack trace:</b></td> <td> <c:forEach var = "trace" items = "${pageContext.exception.stackTrace}"> <p>${trace}</p> </c:forEach> </td> </tr> </table> </body> </html> Access the main.jsp, the following will be generated −
[ { "code": null, "e": 1174, "s": 1062, "text": "You can make use of JSTL tags to write an error page ShowError.jsp with better structure and more information −" }, { "code": null, "e": 2152, "s": 1174, "text": "<%@ taglib prefix = \"c\" uri = \"http://java.sun.com/jsp/jstl/core\" %>\n<%@page isErrorPage = \"true\" %>\n\n<html>\n <head>\n <title>Show Error Page</title>\n </head>\n <body>\n <h1>Opps...</h1>\n <table width = \"100%\" border = \"1\">\n <tr valign = \"top\">\n <td width = \"40%\"><b>Error:</b></td>\n <td>${pageContext.exception}</td>\n </tr>\n <tr valign = \"top\">\n <td><b>URI:</b></td>\n <td>${pageContext.errorData.requestURI}</td>\n </tr>\n <tr valign = \"top\">\n <td><b>Status code:</b></td>\n <td>${pageContext.errorData.statusCode}</td>\n </tr>\n <tr valign = \"top\">\n <td><b>Stack trace:</b></td>\n <td>\n <c:forEach var = \"trace\"\n items = \"${pageContext.exception.stackTrace}\">\n <p>${trace}</p>\n </c:forEach>\n </td>\n </tr>\n </table>\n </body>\n</html>" }, { "code": null, "e": 2207, "s": 2152, "text": "Access the main.jsp, the following will be generated −" } ]
C++ Program to Implement B Tree
The B-tree is a generalization of a binary search tree in that a node can have more than two children. It is basically a self-balancing tree data structure that maintains sorted data and allows sequential access, searches, insertions, and deletions in logarithmic time. Here is a C++ program to implement B tree of order 6. Begin function insert() to insert the nodes into the tree: Initialize x as root. if x is leaf and having space for one more info then insert a to x. else if x is not leaf, do Find the child of x that is going to be traversed next. If the child is not full, change x to point to the child. If the child is full, split it and change x to point to one of the two parts of the child. If a is smaller than mid key in the child, then set x as first part of the child. Else second part of the child. When split the child, move a key from the child to its parent x. End #include<iostream> using namespace std; struct BTree//node declaration { int *d; BTree **child_ptr; bool l; int n; }*r = NULL, *np = NULL, *x = NULL; BTree* init()//creation of node { int i; np = new BTree; np->d = new int[6];//order 6 np->child_ptr = new BTree *[7]; np->l = true; np->n = 0; for (i = 0; i < 7; i++) { np->child_ptr[i] = NULL; } return np; } void traverse(BTree *p)//traverse the tree { cout<<endl; int i; for (i = 0; i < p->n; i++) { if (p->l == false) { traverse(p->child_ptr[i]); } cout << " " << p->d[i]; } if (p->l == false) { traverse(p->child_ptr[i]); } cout<<endl; } void sort(int *p, int n)//sort the tree { int i, j, t; for (i = 0; i < n; i++) { for (j = i; j <= n; j++) { if (p[i] >p[j]) { t = p[i]; p[i] = p[j]; p[j] = t; } } } } int split_child(BTree *x, int i) { int j, mid; BTree *np1, *np3, *y; np3 = init();//create new node np3->l = true; if (i == -1) { mid = x->d[2];//find mid x->d[2] = 0; x->n--; np1 = init(); np1->l= false; x->l= true; for (j = 3; j < 6; j++) { np3->d[j - 3] = x->d[j]; np3->child_ptr[j - 3] = x->child_ptr[j]; np3->n++; x->d[j] = 0; x->n--; } for (j = 0; j < 6; j++) { x->child_ptr[j] = NULL; } np1->d[0] = mid; np1->child_ptr[np1->n] = x; np1->child_ptr[np1->n + 1] = np3; np1->n++; r = np1; } else { y = x->child_ptr[i]; mid = y->d[2]; y->d[2] = 0; y->n--; for (j = 3; j <6 ; j++) { np3->d[j - 3] = y->d[j]; np3->n++; y->d[j] = 0; y->n--; } x->child_ptr[i + 1] = y; x->child_ptr[i + 1] = np3; } return mid; } void insert(int a) { int i, t; x = r; if (x == NULL) { r = init(); x = r; } else { if (x->l== true && x->n == 6) { t = split_child(x, -1); x = r; for (i = 0; i < (x->n); i++) { if ((a >x->d[i]) && (a < x->d[i + 1])) { i++; break; } else if (a < x->d[0]) { break; } else { continue; } } x = x->child_ptr[i]; } else { while (x->l == false) { for (i = 0; i < (x->n); i++) { if ((a >x->d[i]) && (a < x->d[i + 1])) { i++; break; } else if (a < x->d[0]) { break; } else { continue; } } if ((x->child_ptr[i])->n == 6) { t = split_child(x, i); x->d[x->n] = t; x->n++; continue; } else { x = x->child_ptr[i]; } } } } x->d[x->n] = a; sort(x->d, x->n); x->n++; } int main() { int i, n, t; cout<<"enter the no of elements to be inserted\n"; cin>>n; for(i = 0; i < n; i++) { cout<<"enter the element\n"; cin>>t; insert(t); } cout<<"traversal of constructed B tree\n"; traverse(r); } enter the no of elements to be inserted 7 enter the element 10 enter the element 20 enter the element 30 enter the element 40 enter the element 50 enter the element 60 enter the element 70 traversal of constructed B tree 10 20 30 40 50 60 70
[ { "code": null, "e": 1332, "s": 1062, "text": "The B-tree is a generalization of a binary search tree in that a node can have more than two children. It is basically a self-balancing tree data structure that maintains sorted data and allows sequential access, searches, insertions, and deletions in logarithmic time." }, { "code": null, "e": 1386, "s": 1332, "text": "Here is a C++ program to implement B tree of order 6." }, { "code": null, "e": 1990, "s": 1386, "text": "Begin\n function insert() to insert the nodes into the tree:\n Initialize x as root.\n if x is leaf and having space for one more info then insert a to x.\n else if x is not leaf, do\n Find the child of x that is going to be traversed next.\n If the child is not full, change x to point to the child.\n If the child is full, split it and change x to point to one of the two parts of the child. If a is smaller\n than mid key in the child, then set x as first part of the child. Else second part of the child. When split the child, move a key from the child to its parent x.\nEnd" }, { "code": null, "e": 5292, "s": 1990, "text": "#include<iostream>\nusing namespace std;\nstruct BTree//node declaration {\n int *d;\n BTree **child_ptr;\n bool l;\n int n;\n}*r = NULL, *np = NULL, *x = NULL;\n\nBTree* init()//creation of node {\n int i;\n np = new BTree;\n np->d = new int[6];//order 6\n np->child_ptr = new BTree *[7];\n np->l = true;\n np->n = 0;\n for (i = 0; i < 7; i++) {\n np->child_ptr[i] = NULL;\n }\n return np;\n}\n\nvoid traverse(BTree *p)//traverse the tree {\n cout<<endl;\n int i;\n for (i = 0; i < p->n; i++) {\n if (p->l == false) {\n traverse(p->child_ptr[i]);\n }\n cout << \" \" << p->d[i];\n }\n if (p->l == false) {\n traverse(p->child_ptr[i]);\n }\n cout<<endl;\n}\n\nvoid sort(int *p, int n)//sort the tree {\n int i, j, t;\n for (i = 0; i < n; i++) {\n for (j = i; j <= n; j++) {\n if (p[i] >p[j]) {\n t = p[i];\n p[i] = p[j];\n p[j] = t;\n }\n }\n }\n}\n\nint split_child(BTree *x, int i) {\n int j, mid;\n BTree *np1, *np3, *y;\n np3 = init();//create new node\n np3->l = true;\n if (i == -1) {\n mid = x->d[2];//find mid\n x->d[2] = 0;\n x->n--;\n np1 = init();\n np1->l= false;\n x->l= true;\n for (j = 3; j < 6; j++) {\n np3->d[j - 3] = x->d[j];\n np3->child_ptr[j - 3] = x->child_ptr[j];\n np3->n++;\n x->d[j] = 0;\n x->n--;\n }\n for (j = 0; j < 6; j++) {\n x->child_ptr[j] = NULL;\n }\n np1->d[0] = mid;\n np1->child_ptr[np1->n] = x;\n np1->child_ptr[np1->n + 1] = np3;\n np1->n++;\n r = np1;\n } else {\n y = x->child_ptr[i];\n mid = y->d[2];\n y->d[2] = 0;\n y->n--;\n for (j = 3; j <6 ; j++) {\n np3->d[j - 3] = y->d[j];\n np3->n++;\n y->d[j] = 0;\n y->n--;\n }\n x->child_ptr[i + 1] = y;\n x->child_ptr[i + 1] = np3;\n }\n return mid;\n}\n\nvoid insert(int a) {\n int i, t;\n x = r;\n if (x == NULL) {\n r = init();\n x = r;\n } else {\n if (x->l== true && x->n == 6) {\n t = split_child(x, -1);\n x = r;\n for (i = 0; i < (x->n); i++) {\n if ((a >x->d[i]) && (a < x->d[i + 1])) {\n i++;\n break;\n } else if (a < x->d[0]) {\n break;\n } else {\n continue;\n }\n }\n x = x->child_ptr[i];\n } else {\n while (x->l == false) {\n for (i = 0; i < (x->n); i++) {\n if ((a >x->d[i]) && (a < x->d[i + 1])) {\n i++;\n break;\n } else if (a < x->d[0]) {\n break;\n } else {\n continue;\n }\n }\n if ((x->child_ptr[i])->n == 6) {\n t = split_child(x, i);\n x->d[x->n] = t;\n x->n++;\n continue;\n } else {\n x = x->child_ptr[i];\n }\n }\n }\n }\n x->d[x->n] = a;\n sort(x->d, x->n);\n x->n++;\n}\n\nint main() {\n int i, n, t;\n cout<<\"enter the no of elements to be inserted\\n\";\n cin>>n;\n for(i = 0; i < n; i++) {\n cout<<\"enter the element\\n\";\n cin>>t;\n insert(t);\n }\n cout<<\"traversal of constructed B tree\\n\";\n traverse(r);\n}" }, { "code": null, "e": 5534, "s": 5292, "text": "enter the no of elements to be inserted\n7\nenter the element\n10\nenter the element\n20\nenter the element\n30\nenter the element\n40\nenter the element\n50\nenter the element\n60\nenter the element\n70\ntraversal of constructed B tree\n10 20\n30\n40 50 60 70" } ]
XQuery - XPath
XQuery is XPath compliant. It uses XPath expressions to restrict the search results on XML collections. For more details on how to use XPath, see our XPath Tutorial. Recall the following XPath expression which we have used earlier to get the list of books. doc("books.xml")/books/book We will use the books.xml file and apply XQuery to it. <?xml version="1.0" encoding="UTF-8"?> <books> <book category="JAVA"> <title lang="en">Learn Java in 24 Hours</title> <author>Robert</author> <year>2005</year> <price>30.00</price> </book> <book category="DOTNET"> <title lang="en">Learn .Net in 24 hours</title> <author>Peter</author> <year>2011</year> <price>40.50</price> </book> <book category="XML"> <title lang="en">Learn XQuery in 24 hours</title> <author>Robert</author> <author>Peter</author> <year>2013</year> <price>50.00</price> </book> <book category="XML"> <title lang="en">Learn XPath in 24 hours</title> <author>Jay Ban</author> <year>2010</year> <price>16.50</price> </book> </books> We have given here three versions of an XQuery statement that fulfil the same objective of displaying the book titles having a price value greater than 30. (: read the entire xml document :) let $books := doc("books.xml") for $x in $books/books/book where $x/price > 30 return $x/title <title lang="en">Learn .Net in 24 hours</title> <title lang="en">Learn XQuery in 24 hours</title> (: read all books :) let $books := doc("books.xml")/books/book for $x in $books where $x/price > 30 return $x/title <title lang="en">Learn .Net in 24 hours</title> <title lang="en">Learn XQuery in 24 hours</title> (: read books with price > 30 :) let $books := doc("books.xml")/books/book[price > 30] for $x in $books return $x/title <title lang="en">Learn .Net in 24 hours</title> <title lang="en">Learn XQuery in 24 hours</title> To verify the result, replace the contents of books.xqy (given in the Environment Setup chapter) with the above XQuery expression and execute the XQueryTester java program. Print Add Notes Bookmark this page
[ { "code": null, "e": 2038, "s": 1872, "text": "XQuery is XPath compliant. It uses XPath expressions to restrict the search results on XML collections. For more details on how to use XPath, see our XPath Tutorial." }, { "code": null, "e": 2129, "s": 2038, "text": "Recall the following XPath expression which we have used earlier to get the list of books." }, { "code": null, "e": 2157, "s": 2129, "text": "doc(\"books.xml\")/books/book" }, { "code": null, "e": 2212, "s": 2157, "text": "We will use the books.xml file and apply XQuery to it." }, { "code": null, "e": 3009, "s": 2212, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<books>\n \n <book category=\"JAVA\">\n <title lang=\"en\">Learn Java in 24 Hours</title>\n <author>Robert</author>\n <year>2005</year>\n <price>30.00</price>\n </book>\n \n <book category=\"DOTNET\">\n <title lang=\"en\">Learn .Net in 24 hours</title>\n <author>Peter</author>\n <year>2011</year>\n <price>40.50</price>\n </book>\n \n <book category=\"XML\">\n <title lang=\"en\">Learn XQuery in 24 hours</title>\n <author>Robert</author>\n <author>Peter</author> \n <year>2013</year>\n <price>50.00</price>\n </book>\n \n <book category=\"XML\">\n <title lang=\"en\">Learn XPath in 24 hours</title>\n <author>Jay Ban</author>\n <year>2010</year>\n <price>16.50</price>\n </book>\n \n</books>" }, { "code": null, "e": 3165, "s": 3009, "text": "We have given here three versions of an XQuery statement that fulfil the same objective of displaying the book titles having a price value greater than 30." }, { "code": null, "e": 3296, "s": 3165, "text": "(: read the entire xml document :)\nlet $books := doc(\"books.xml\")\n\nfor $x in $books/books/book\nwhere $x/price > 30\nreturn $x/title" }, { "code": null, "e": 3395, "s": 3296, "text": "<title lang=\"en\">Learn .Net in 24 hours</title>\n<title lang=\"en\">Learn XQuery in 24 hours</title>\n" }, { "code": null, "e": 3512, "s": 3395, "text": "(: read all books :)\nlet $books := doc(\"books.xml\")/books/book\n\nfor $x in $books\nwhere $x/price > 30\nreturn $x/title" }, { "code": null, "e": 3611, "s": 3512, "text": "<title lang=\"en\">Learn .Net in 24 hours</title>\n<title lang=\"en\">Learn XQuery in 24 hours</title>\n" }, { "code": null, "e": 3732, "s": 3611, "text": "(: read books with price > 30 :)\nlet $books := doc(\"books.xml\")/books/book[price > 30]\n\nfor $x in $books\nreturn $x/title" }, { "code": null, "e": 3831, "s": 3732, "text": "<title lang=\"en\">Learn .Net in 24 hours</title>\n<title lang=\"en\">Learn XQuery in 24 hours</title>\n" }, { "code": null, "e": 4004, "s": 3831, "text": "To verify the result, replace the contents of books.xqy (given in the Environment Setup chapter) with the above XQuery expression and execute the XQueryTester java program." }, { "code": null, "e": 4011, "s": 4004, "text": " Print" }, { "code": null, "e": 4022, "s": 4011, "text": " Add Notes" } ]
Introduction to Genetic Algorithm and Python Implementation For Function Optimization | by Awan-Ur-Rahman | Towards Data Science
Here, in this article, I will try to give you an idea of how a genetic algorithm works and we will implement the genetic algorithm for function optimization. So, let’s start. The genetic algorithm is a search-based optimization technique. It is frequently used to find the optimal or nearest optimal solution. It was introduced by John Holland. It is based on Darwins Natural Selection Theory. Before explaining how the genetic algorithm works let me first explain Darwin’s theory on natural selection. In his theory, he defined natural selection as the “principle by which each slight variation [of a trait], if useful, is preserved”. The concept was simple but powerful: individuals best adapted to their environments are more likely to survive and reproduce.[Wikipedia] Sometimes this theory is described as“ survival of the fittest”. Those who are fittest than others have the chance to survive in this evolution. The genetic algorithm is all about this. It mimics the process of natural selection to find the best solution. In genetic we will use some biological terms such as population, chromosome, gene, selection, crossover, mutation. Now, first of all, let’s try to understand what these terms mean. At the beginning of this process, we need to initialize some possible solutions to this problem. The population is a subset of all possible solutions to the given problem. In another way, we can say that the population is a set of chromosomes. A chromosome is one of that solution to that current problem. And each chromosome is a set of genes. For simplicity, We can describe a chromosome as a string. So, we can say that a population is a collection of some string(each character is a binary value, either 0 or 1 ). And each character of the string is a gene. For starting the process of the genetic algorithm, we first need to initialize the population. We can initialize the population in two ways. The first one is random and the second one is heuristical. It is always better to start the algorithm with some random population. After initializing the population, we need to calculate the fitness value of these chromosomes. Now the question is what this fitness function is and how it calculates the fitness value. As an example, let consider that we have an equation, f(x) = -x2 + 5 .We need the solution for which it has the maximum value and the constraint is 0≤x≤31. Now, let consider that we have a random population of four chromosomes like below. The length of our chromosome is 5 as 25=32 and 0≤x≤31. Our fitness function will calculate the functional value of each chromosome as stated in the problem statement : For the 1st chromosome, 01110 means 14 in integer. So, f(x) = -(14*14) + 5 = -191. For the 2nd chromosome, 10101 means 21 in integer. So, f(x) = -(21*21) + 5 = -436. For the 3rd chromosome, 00011 means 3 in integer. So, f(x) = -(3*3) + 5 = -4. For the 4th chromosome, 10111 means 23 in integer. So, f(x) = -(23*23) + 5 = -524. Parent selection is done by using the fitness values of the chromosomes calculated by the fitness function. Based on these fitness values we need to select a pair chromosomes with the highest fitness value. There are many ways for fitness calculation like Roulette wheel selection, rank selection. In Roulette wheel selection, the chromosome with the highest fitness value has the maximum possibility to be selected as a parent. But in this selection process, a lower can be selected. In rank selection, chromosomes are ranked based on their fitness values from higher to lower. As an example, According to those fitness values calculated above, we can rank those chromosomes from higher to lower like 3rd>1st>2nd>4th. So, in the selection phase, 3rd and 1st chromosomes will be selected based on the fitness valued calculated from the fitness function. Crossover is used to vary the programming of the chromosomes from one generation to another by creating children or offsprings. Parent chromosomes are used to create these offsprings(generated chromosomes). To create offsprings, there are some ways like a single-point crossover, two or multi-point crossover. For a single point crossover, first, we need to select a point and then exchange these portions divided by this point between parent chromosomes to create offsprings. You can use the color combination for easy understanding. For a two-point crossover, we need to select two points and then exchange the bits. Finally, these new offsprings are added to the population. Mutation brings diversity to the population. There are different kinds of mutations like Bit Flip mutation, Swap mutation, Inversion mutation, etc. These are so so simple. In Bit Flip mutation, Just select one or more bits and then flip them. If the selected bit is 0 then turn it to 1 and if the selected bit is 1 then turn it to 0. In Swap Bit mutation, select two bits and just swap them. In inverse mutation, just inverse the bits. Let’s try to implement the genetic algorithm in python for function optimization. Problem Statement Let consider that we have an equation, f(x) = -x2 + 5 . We need the solution for which it has the maximum value and the constraint is 0≤x≤31. To select an initial population use the probability 0.2. You can find the full code here. Initial Population Random Initialization is better than heuristic initialization. Therefore, here random initialization is used for population initialization. #initialize populationimport randombest=-100000populations =([[random.randint(0,1) for x in range(6)] for i in range(4)])print(type(populations))parents=[]new_populations = []print(populations) Fitness Function The fitness function calculates the fitness value of chromosomes. The functionality of the fitness function depends on the problem’s requirements. #fitness score calculation ............def fitness_score() : global populations,best fit_value = [] fit_score=[] for i in range(4) : chromosome_value=0 for j in range(5,0,-1) : chromosome_value += populations[i][j]*(2**(5-j)) chromosome_value = -1*chromosome_value if populations[i][0]==1 else chromosome_value print(chromosome_value) fit_value.append(-(chromosome_value**2) + 5 ) print(fit_value) fit_value, populations = zip(*sorted(zip(fit_value, populations) , reverse = True)) best= fit_value[0] fitness_score() Selection Fittest chromosomes are selected based on the fitness scores. Here rank selection process is used. def selectparent(): global parents #global populations , parents parents=populations[0:2] print(type(parents)) print(parents)selectparent() Crossover After selecting the fittest parents, a crossover is required to generate offsprings. Here, the single-point crossover is used. def crossover() : global parents cross_point = random.randint(0,5) parents=parents + tuple([(parents[0][0:cross_point +1] +parents[1][cross_point+1:6])]) parents =parents+ tuple([(parents[1][0:cross_point +1] +parents[0][cross_point+1:6])]) print(parents) Mutation After crossover is done, a mutation is done for maintaining the diversity from one generation to another. Here, we will single point bit-flip mutation. def mutation() : global populations, parents mute = random.randint(0,49) if mute == 20 : x=random.randint(0,3) y = random.randint(0,5) parents[x][y] = 1-parents[x][y] populations = parents print(populations) We need to iterate the whole process multiple times until we find our best solution. You will find the full code on Kaggle. Genetic algorithm — mutationGenetic algorithm — crossoverGenetic algorithm — parent selectionGenetic algorithm — population initialization Genetic algorithm — mutation Genetic algorithm — crossover Genetic algorithm — parent selection Genetic algorithm — population initialization
[ { "code": null, "e": 347, "s": 172, "text": "Here, in this article, I will try to give you an idea of how a genetic algorithm works and we will implement the genetic algorithm for function optimization. So, let’s start." }, { "code": null, "e": 1201, "s": 347, "text": "The genetic algorithm is a search-based optimization technique. It is frequently used to find the optimal or nearest optimal solution. It was introduced by John Holland. It is based on Darwins Natural Selection Theory. Before explaining how the genetic algorithm works let me first explain Darwin’s theory on natural selection. In his theory, he defined natural selection as the “principle by which each slight variation [of a trait], if useful, is preserved”. The concept was simple but powerful: individuals best adapted to their environments are more likely to survive and reproduce.[Wikipedia] Sometimes this theory is described as“ survival of the fittest”. Those who are fittest than others have the chance to survive in this evolution. The genetic algorithm is all about this. It mimics the process of natural selection to find the best solution." }, { "code": null, "e": 1382, "s": 1201, "text": "In genetic we will use some biological terms such as population, chromosome, gene, selection, crossover, mutation. Now, first of all, let’s try to understand what these terms mean." }, { "code": null, "e": 1727, "s": 1382, "text": "At the beginning of this process, we need to initialize some possible solutions to this problem. The population is a subset of all possible solutions to the given problem. In another way, we can say that the population is a set of chromosomes. A chromosome is one of that solution to that current problem. And each chromosome is a set of genes." }, { "code": null, "e": 1944, "s": 1727, "text": "For simplicity, We can describe a chromosome as a string. So, we can say that a population is a collection of some string(each character is a binary value, either 0 or 1 ). And each character of the string is a gene." }, { "code": null, "e": 2216, "s": 1944, "text": "For starting the process of the genetic algorithm, we first need to initialize the population. We can initialize the population in two ways. The first one is random and the second one is heuristical. It is always better to start the algorithm with some random population." }, { "code": null, "e": 2403, "s": 2216, "text": "After initializing the population, we need to calculate the fitness value of these chromosomes. Now the question is what this fitness function is and how it calculates the fitness value." }, { "code": null, "e": 2559, "s": 2403, "text": "As an example, let consider that we have an equation, f(x) = -x2 + 5 .We need the solution for which it has the maximum value and the constraint is 0≤x≤31." }, { "code": null, "e": 2697, "s": 2559, "text": "Now, let consider that we have a random population of four chromosomes like below. The length of our chromosome is 5 as 25=32 and 0≤x≤31." }, { "code": null, "e": 2810, "s": 2697, "text": "Our fitness function will calculate the functional value of each chromosome as stated in the problem statement :" }, { "code": null, "e": 2893, "s": 2810, "text": "For the 1st chromosome, 01110 means 14 in integer. So, f(x) = -(14*14) + 5 = -191." }, { "code": null, "e": 2976, "s": 2893, "text": "For the 2nd chromosome, 10101 means 21 in integer. So, f(x) = -(21*21) + 5 = -436." }, { "code": null, "e": 3054, "s": 2976, "text": "For the 3rd chromosome, 00011 means 3 in integer. So, f(x) = -(3*3) + 5 = -4." }, { "code": null, "e": 3137, "s": 3054, "text": "For the 4th chromosome, 10111 means 23 in integer. So, f(x) = -(23*23) + 5 = -524." }, { "code": null, "e": 3344, "s": 3137, "text": "Parent selection is done by using the fitness values of the chromosomes calculated by the fitness function. Based on these fitness values we need to select a pair chromosomes with the highest fitness value." }, { "code": null, "e": 3435, "s": 3344, "text": "There are many ways for fitness calculation like Roulette wheel selection, rank selection." }, { "code": null, "e": 3622, "s": 3435, "text": "In Roulette wheel selection, the chromosome with the highest fitness value has the maximum possibility to be selected as a parent. But in this selection process, a lower can be selected." }, { "code": null, "e": 3991, "s": 3622, "text": "In rank selection, chromosomes are ranked based on their fitness values from higher to lower. As an example, According to those fitness values calculated above, we can rank those chromosomes from higher to lower like 3rd>1st>2nd>4th. So, in the selection phase, 3rd and 1st chromosomes will be selected based on the fitness valued calculated from the fitness function." }, { "code": null, "e": 4198, "s": 3991, "text": "Crossover is used to vary the programming of the chromosomes from one generation to another by creating children or offsprings. Parent chromosomes are used to create these offsprings(generated chromosomes)." }, { "code": null, "e": 4301, "s": 4198, "text": "To create offsprings, there are some ways like a single-point crossover, two or multi-point crossover." }, { "code": null, "e": 4526, "s": 4301, "text": "For a single point crossover, first, we need to select a point and then exchange these portions divided by this point between parent chromosomes to create offsprings. You can use the color combination for easy understanding." }, { "code": null, "e": 4610, "s": 4526, "text": "For a two-point crossover, we need to select two points and then exchange the bits." }, { "code": null, "e": 4669, "s": 4610, "text": "Finally, these new offsprings are added to the population." }, { "code": null, "e": 4841, "s": 4669, "text": "Mutation brings diversity to the population. There are different kinds of mutations like Bit Flip mutation, Swap mutation, Inversion mutation, etc. These are so so simple." }, { "code": null, "e": 5003, "s": 4841, "text": "In Bit Flip mutation, Just select one or more bits and then flip them. If the selected bit is 0 then turn it to 1 and if the selected bit is 1 then turn it to 0." }, { "code": null, "e": 5061, "s": 5003, "text": "In Swap Bit mutation, select two bits and just swap them." }, { "code": null, "e": 5105, "s": 5061, "text": "In inverse mutation, just inverse the bits." }, { "code": null, "e": 5187, "s": 5105, "text": "Let’s try to implement the genetic algorithm in python for function optimization." }, { "code": null, "e": 5205, "s": 5187, "text": "Problem Statement" }, { "code": null, "e": 5404, "s": 5205, "text": "Let consider that we have an equation, f(x) = -x2 + 5 . We need the solution for which it has the maximum value and the constraint is 0≤x≤31. To select an initial population use the probability 0.2." }, { "code": null, "e": 5437, "s": 5404, "text": "You can find the full code here." }, { "code": null, "e": 5456, "s": 5437, "text": "Initial Population" }, { "code": null, "e": 5596, "s": 5456, "text": "Random Initialization is better than heuristic initialization. Therefore, here random initialization is used for population initialization." }, { "code": null, "e": 5790, "s": 5596, "text": "#initialize populationimport randombest=-100000populations =([[random.randint(0,1) for x in range(6)] for i in range(4)])print(type(populations))parents=[]new_populations = []print(populations)" }, { "code": null, "e": 5807, "s": 5790, "text": "Fitness Function" }, { "code": null, "e": 5954, "s": 5807, "text": "The fitness function calculates the fitness value of chromosomes. The functionality of the fitness function depends on the problem’s requirements." }, { "code": null, "e": 6549, "s": 5954, "text": "#fitness score calculation ............def fitness_score() : global populations,best fit_value = [] fit_score=[] for i in range(4) : chromosome_value=0 for j in range(5,0,-1) : chromosome_value += populations[i][j]*(2**(5-j)) chromosome_value = -1*chromosome_value if populations[i][0]==1 else chromosome_value print(chromosome_value) fit_value.append(-(chromosome_value**2) + 5 ) print(fit_value) fit_value, populations = zip(*sorted(zip(fit_value, populations) , reverse = True)) best= fit_value[0] fitness_score()" }, { "code": null, "e": 6559, "s": 6549, "text": "Selection" }, { "code": null, "e": 6658, "s": 6559, "text": "Fittest chromosomes are selected based on the fitness scores. Here rank selection process is used." }, { "code": null, "e": 6813, "s": 6658, "text": "def selectparent(): global parents #global populations , parents parents=populations[0:2] print(type(parents)) print(parents)selectparent()" }, { "code": null, "e": 6823, "s": 6813, "text": "Crossover" }, { "code": null, "e": 6950, "s": 6823, "text": "After selecting the fittest parents, a crossover is required to generate offsprings. Here, the single-point crossover is used." }, { "code": null, "e": 7229, "s": 6950, "text": "def crossover() : global parents cross_point = random.randint(0,5) parents=parents + tuple([(parents[0][0:cross_point +1] +parents[1][cross_point+1:6])]) parents =parents+ tuple([(parents[1][0:cross_point +1] +parents[0][cross_point+1:6])]) print(parents)" }, { "code": null, "e": 7238, "s": 7229, "text": "Mutation" }, { "code": null, "e": 7390, "s": 7238, "text": "After crossover is done, a mutation is done for maintaining the diversity from one generation to another. Here, we will single point bit-flip mutation." }, { "code": null, "e": 7634, "s": 7390, "text": "def mutation() : global populations, parents mute = random.randint(0,49) if mute == 20 : x=random.randint(0,3) y = random.randint(0,5) parents[x][y] = 1-parents[x][y] populations = parents print(populations)" }, { "code": null, "e": 7719, "s": 7634, "text": "We need to iterate the whole process multiple times until we find our best solution." }, { "code": null, "e": 7758, "s": 7719, "text": "You will find the full code on Kaggle." }, { "code": null, "e": 7897, "s": 7758, "text": "Genetic algorithm — mutationGenetic algorithm — crossoverGenetic algorithm — parent selectionGenetic algorithm — population initialization" }, { "code": null, "e": 7926, "s": 7897, "text": "Genetic algorithm — mutation" }, { "code": null, "e": 7956, "s": 7926, "text": "Genetic algorithm — crossover" }, { "code": null, "e": 7993, "s": 7956, "text": "Genetic algorithm — parent selection" } ]
Python | Generator Expressions - GeeksforGeeks
07 Sep, 2021 In Python, to create iterators, we can use both regular functions and generators. Generators are written just like a normal function but we use yield() instead of return() for returning a result. It is more powerful as a tool to implement iterators. It is easy and more convenient to implement because it offers the evaluation of elements on demand. Unlike regular functions which on encountering a return statement terminates entirely, generators use a yield statement in which the state of the function is saved from the last call and can be picked up or resumed the next time we call a generator function. Another great advantage of the generator over a list is that it takes much less memory. In addition to that, two more functions _next_() and _iter_() make the generator function more compact and reliable. Example : Python3 # Python code to illustrate generator, yield() and next().def generator(): t = 1 print ('First result is ',t) yield t t += 1 print ('Second result is ',t) yield t t += 1 print('Third result is ',t) yield t call = generator()next(call)next(call)next(call) Output : First result is 1 Second result is 2 Third result is 3 Difference between Generator function and Normal function – Once the function yields, the function is paused and the control is transferred to the caller. When the function terminates, StopIteration is raised automatically on further calls. Local variables and their states are remembered between successive calls. The generator function contains one or more yield statements instead of a return statement. As the methods like _next_() and _iter_() are implemented automatically, we can iterate through the items using next(). There are various other expressions that can be simply coded similar to list comprehensions but instead of brackets we use parenthesis. These expressions are designed for situations where the generator is used right away by an enclosing function. Generator expression allows creating a generator without a yield keyword. However, it doesn’t share the whole power of the generator created with a yield function. Example : Python3 # Python code to illustrate generator expressiongenerator = (num ** 2 for num in range(10))for num in generator: print(num) Output : 0 1 4 9 16 25 36 49 64 81 We can also generate a list using generator expressions : Python3 string = 'geek'li = list(string[i] for i in range(len(string)-1, -1, -1))print(li) Output: ['k', 'e', 'e', 'g'] This article is contributed by Chinmoy Lenka. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. sg4ipiafwot258z3lh6xa2mjq2qtxd89f49zgt7g 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 Python OOPs Concepts Python | Get unique values from a list Check if element exists in list in Python Python Classes and Objects Python | os.path.join() method How To Convert Python Dictionary To JSON? Python | Pandas dataframe.groupby() Create a directory in Python
[ { "code": null, "e": 24238, "s": 24210, "text": "\n07 Sep, 2021" }, { "code": null, "e": 24936, "s": 24238, "text": "In Python, to create iterators, we can use both regular functions and generators. Generators are written just like a normal function but we use yield() instead of return() for returning a result. It is more powerful as a tool to implement iterators. It is easy and more convenient to implement because it offers the evaluation of elements on demand. Unlike regular functions which on encountering a return statement terminates entirely, generators use a yield statement in which the state of the function is saved from the last call and can be picked up or resumed the next time we call a generator function. Another great advantage of the generator over a list is that it takes much less memory. " }, { "code": null, "e": 25064, "s": 24936, "text": "In addition to that, two more functions _next_() and _iter_() make the generator function more compact and reliable. Example : " }, { "code": null, "e": 25072, "s": 25064, "text": "Python3" }, { "code": "# Python code to illustrate generator, yield() and next().def generator(): t = 1 print ('First result is ',t) yield t t += 1 print ('Second result is ',t) yield t t += 1 print('Third result is ',t) yield t call = generator()next(call)next(call)next(call)", "e": 25356, "s": 25072, "text": null }, { "code": null, "e": 25366, "s": 25356, "text": "Output : " }, { "code": null, "e": 25424, "s": 25366, "text": "First result is 1\nSecond result is 2\nThird result is 3" }, { "code": null, "e": 25485, "s": 25424, "text": "Difference between Generator function and Normal function – " }, { "code": null, "e": 25580, "s": 25485, "text": "Once the function yields, the function is paused and the control is transferred to the caller." }, { "code": null, "e": 25666, "s": 25580, "text": "When the function terminates, StopIteration is raised automatically on further calls." }, { "code": null, "e": 25740, "s": 25666, "text": "Local variables and their states are remembered between successive calls." }, { "code": null, "e": 25832, "s": 25740, "text": "The generator function contains one or more yield statements instead of a return statement." }, { "code": null, "e": 25952, "s": 25832, "text": "As the methods like _next_() and _iter_() are implemented automatically, we can iterate through the items using next()." }, { "code": null, "e": 26375, "s": 25952, "text": "There are various other expressions that can be simply coded similar to list comprehensions but instead of brackets we use parenthesis. These expressions are designed for situations where the generator is used right away by an enclosing function. Generator expression allows creating a generator without a yield keyword. However, it doesn’t share the whole power of the generator created with a yield function. Example : " }, { "code": null, "e": 26383, "s": 26375, "text": "Python3" }, { "code": "# Python code to illustrate generator expressiongenerator = (num ** 2 for num in range(10))for num in generator: print(num)", "e": 26510, "s": 26383, "text": null }, { "code": null, "e": 26520, "s": 26510, "text": "Output : " }, { "code": null, "e": 26546, "s": 26520, "text": "0\n1\n4\n9\n16\n25\n36\n49\n64\n81" }, { "code": null, "e": 26605, "s": 26546, "text": "We can also generate a list using generator expressions : " }, { "code": null, "e": 26613, "s": 26605, "text": "Python3" }, { "code": "string = 'geek'li = list(string[i] for i in range(len(string)-1, -1, -1))print(li)", "e": 26696, "s": 26613, "text": null }, { "code": null, "e": 26705, "s": 26696, "text": "Output: " }, { "code": null, "e": 26726, "s": 26705, "text": "['k', 'e', 'e', 'g']" }, { "code": null, "e": 27148, "s": 26726, "text": "This article is contributed by Chinmoy Lenka. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 27189, "s": 27148, "text": "sg4ipiafwot258z3lh6xa2mjq2qtxd89f49zgt7g" }, { "code": null, "e": 27196, "s": 27189, "text": "Python" }, { "code": null, "e": 27294, "s": 27196, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27303, "s": 27294, "text": "Comments" }, { "code": null, "e": 27316, "s": 27303, "text": "Old Comments" }, { "code": null, "e": 27348, "s": 27316, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27404, "s": 27348, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27425, "s": 27404, "text": "Python OOPs Concepts" }, { "code": null, "e": 27464, "s": 27425, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27506, "s": 27464, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27533, "s": 27506, "text": "Python Classes and Objects" }, { "code": null, "e": 27564, "s": 27533, "text": "Python | os.path.join() method" }, { "code": null, "e": 27606, "s": 27564, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27642, "s": 27606, "text": "Python | Pandas dataframe.groupby()" } ]
Groovy - Regular Expressions
A regular expression is a pattern that is used to find substrings in text. Groovy supports regular expressions natively using the ~”regex” expression. The text enclosed within the quotations represent the expression for comparison. For example we can create a regular expression object as shown below − def regex = ~'Groovy' When the Groovy operator =~ appears as a predicate (expression returning a Boolean) in if and while statements (see Chapter 8), the String operand on the left is matched against the regular expression operand on the right. Hence, each of the following delivers the value true. When defining regular expression, the following special characters can be used − There are two special positional characters that are used to denote the beginning and end of a line: caret (∧) and dollar sign ($). There are two special positional characters that are used to denote the beginning and end of a line: caret (∧) and dollar sign ($). Regular expressions can also include quantifiers. The plus sign (+) represents one or more times, applied to the preceding element of the expression. The asterisk (*) is used to represent zero or more occurrences. The question mark (?) denotes zero or once. Regular expressions can also include quantifiers. The plus sign (+) represents one or more times, applied to the preceding element of the expression. The asterisk (*) is used to represent zero or more occurrences. The question mark (?) denotes zero or once. The metacharacter { and } is used to match a specific number of instances of the preceding character. The metacharacter { and } is used to match a specific number of instances of the preceding character. In a regular expression, the period symbol (.) can represent any character. This is described as the wildcard character. In a regular expression, the period symbol (.) can represent any character. This is described as the wildcard character. A regular expression may include character classes. A set of characters can be given as a simple sequence of characters enclosed in the metacharacters [and] as in [aeiou]. For letter or number ranges, you can use a dash separator as in [a–z] or [a–mA–M]. The complement of a character class is denoted by a leading caret within the square rackets as in [∧a–z] and represents all characters other than those specified. Some examples of Regular expressions are given below A regular expression may include character classes. A set of characters can be given as a simple sequence of characters enclosed in the metacharacters [and] as in [aeiou]. For letter or number ranges, you can use a dash separator as in [a–z] or [a–mA–M]. The complement of a character class is denoted by a leading caret within the square rackets as in [∧a–z] and represents all characters other than those specified. Some examples of Regular expressions are given below 'Groovy' =~ 'Groovy' 'Groovy' =~ 'oo' 'Groovy' ==~ 'Groovy' 'Groovy' ==~ 'oo' 'Groovy' =~ '∧G' ‘Groovy' =~ 'G$' ‘Groovy' =~ 'Gro*vy' 'Groovy' =~ 'Gro{2}vy' 52 Lectures 8 hours Krishna Sakinala 49 Lectures 2.5 hours Packt Publishing Print Add Notes Bookmark this page
[ { "code": null, "e": 2470, "s": 2238, "text": "A regular expression is a pattern that is used to find substrings in text. Groovy supports regular expressions natively using the ~”regex” expression. The text enclosed within the quotations represent the expression for comparison." }, { "code": null, "e": 2541, "s": 2470, "text": "For example we can create a regular expression object as shown below −" }, { "code": null, "e": 2564, "s": 2541, "text": "def regex = ~'Groovy'\n" }, { "code": null, "e": 2841, "s": 2564, "text": "When the Groovy operator =~ appears as a predicate (expression returning a Boolean) in if and while statements (see Chapter 8), the String operand on the left is matched against the regular expression operand on the right. Hence, each of the following delivers the value true." }, { "code": null, "e": 2922, "s": 2841, "text": "When defining regular expression, the following special characters can be used −" }, { "code": null, "e": 3054, "s": 2922, "text": "There are two special positional characters that are used to denote the beginning and end of a line: caret (∧) and dollar sign ($)." }, { "code": null, "e": 3186, "s": 3054, "text": "There are two special positional characters that are used to denote the beginning and end of a line: caret (∧) and dollar sign ($)." }, { "code": null, "e": 3444, "s": 3186, "text": "Regular expressions can also include quantifiers. The plus sign (+) represents one or more times, applied to the preceding element of the expression. The asterisk (*) is used to represent zero or more occurrences. The question mark (?) denotes zero or once." }, { "code": null, "e": 3702, "s": 3444, "text": "Regular expressions can also include quantifiers. The plus sign (+) represents one or more times, applied to the preceding element of the expression. The asterisk (*) is used to represent zero or more occurrences. The question mark (?) denotes zero or once." }, { "code": null, "e": 3804, "s": 3702, "text": "The metacharacter { and } is used to match a specific number of instances of the preceding character." }, { "code": null, "e": 3906, "s": 3804, "text": "The metacharacter { and } is used to match a specific number of instances of the preceding character." }, { "code": null, "e": 4027, "s": 3906, "text": "In a regular expression, the period symbol (.) can represent any character. This is described as the wildcard character." }, { "code": null, "e": 4148, "s": 4027, "text": "In a regular expression, the period symbol (.) can represent any character. This is described as the wildcard character." }, { "code": null, "e": 4619, "s": 4148, "text": "A regular expression may include character classes. A set of characters can be given as a simple sequence of characters enclosed in the metacharacters [and] as in [aeiou]. For letter or number ranges, you can use a dash separator as in [a–z] or [a–mA–M]. The complement of a character class is denoted by a leading caret within the square rackets as in [∧a–z] and represents all characters other than those specified. Some examples of Regular expressions are given below" }, { "code": null, "e": 5090, "s": 4619, "text": "A regular expression may include character classes. A set of characters can be given as a simple sequence of characters enclosed in the metacharacters [and] as in [aeiou]. For letter or number ranges, you can use a dash separator as in [a–z] or [a–mA–M]. The complement of a character class is denoted by a leading caret within the square rackets as in [∧a–z] and represents all characters other than those specified. Some examples of Regular expressions are given below" }, { "code": null, "e": 5253, "s": 5090, "text": "'Groovy' =~ 'Groovy' \n'Groovy' =~ 'oo' \n'Groovy' ==~ 'Groovy' \n'Groovy' ==~ 'oo' \n'Groovy' =~ '∧G' \n‘Groovy' =~ 'G$' \n‘Groovy' =~ 'Gro*vy' 'Groovy' =~ 'Gro{2}vy'\n" }, { "code": null, "e": 5286, "s": 5253, "text": "\n 52 Lectures \n 8 hours \n" }, { "code": null, "e": 5304, "s": 5286, "text": " Krishna Sakinala" }, { "code": null, "e": 5339, "s": 5304, "text": "\n 49 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5357, "s": 5339, "text": " Packt Publishing" }, { "code": null, "e": 5364, "s": 5357, "text": " Print" }, { "code": null, "e": 5375, "s": 5364, "text": " Add Notes" } ]
ASP.NET Core - Razor Tag Helpers
Tag Helpers enable server-side code to participate in creating and rendering HTML elements in Razor files. Tag helpers are a new feature and similar to HTML helpers, which help us render HTML. There are many built-in Tag Helpers for common tasks, such as creating forms, links, loading assets etc. Tag Helpers are authored in C#, and they target HTML elements based on the element name, the attribute name, or the parent tag. There are many built-in Tag Helpers for common tasks, such as creating forms, links, loading assets etc. Tag Helpers are authored in C#, and they target HTML elements based on the element name, the attribute name, or the parent tag. For example, the built-in LabelTagHelper can target the HTML <label> element when the LabelTagHelper attributes are applied. For example, the built-in LabelTagHelper can target the HTML <label> element when the LabelTagHelper attributes are applied. If you are familiar with HTML Helpers, Tag Helpers reduce the explicit transitions between HTML and C# in Razor views. If you are familiar with HTML Helpers, Tag Helpers reduce the explicit transitions between HTML and C# in Razor views. In order to use Tag Helpers, we need to install a NuGet library and also add an addTagHelper directive to the view or views that use these tag helpers. Let us right-click on your project in the Solution Explorer and select Manage NuGet Packages.... Search for Microsoft.AspNet.Mvc.TagHelpers and click the Install button. You will receive the following Preview dialog box. Click the OK button. Click the I Accept button. Once the Microsoft.AspNet.Mvc.TagHelpers is installed, go to the project.json file. { "version": "1.0.0-*", "compilationOptions": { "emitEntryPoint": true }, "dependencies": { "Microsoft.AspNet.Mvc": "6.0.0-rc1-final", "Microsoft.AspNet.Diagnostics": "1.0.0-rc1-final", "Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final", "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final", "Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final", "EntityFramework.MicrosoftSqlServer": "7.0.0-rc1-final", "EntityFramework.Commands": "7.0.0-rc1-final", "Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-rc1-final" }, "commands": { "web": "Microsoft.AspNet.Server.Kestrel", "ef": "EntityFramework.Commands" }, "frameworks": { "dnx451": { }, "dnxcore50": { } }, "exclude": [ "wwwroot", "node_modules" ], "publishExclude": [ "**.user", "**.vspscc" ] } In the dependencies section, you will see that "Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-rc1-final" is added. Now anybody can author a tag helper, so if you can think of a tag helper that you need, you can write your own tag helper. Now anybody can author a tag helper, so if you can think of a tag helper that you need, you can write your own tag helper. You can place it right inside your application project, but you need to tell the Razor view engine about the tag helper. You can place it right inside your application project, but you need to tell the Razor view engine about the tag helper. By default, they are not just rendered down to the client, even though these tag helpers look like they blend into the HTML. By default, they are not just rendered down to the client, even though these tag helpers look like they blend into the HTML. Razor will call into some code to process a tag helper; it can remove itself from the HTML and it can also add additional HTML. Razor will call into some code to process a tag helper; it can remove itself from the HTML and it can also add additional HTML. There are many wonderful things that you can do with a tag helper, but you need to register your tag helpers with Razor, even the Microsoft tag helpers, in order for Razor to be able to spot these tag helpers in the markup and to be able to call into the code that processes the tag helper. There are many wonderful things that you can do with a tag helper, but you need to register your tag helpers with Razor, even the Microsoft tag helpers, in order for Razor to be able to spot these tag helpers in the markup and to be able to call into the code that processes the tag helper. The directive to do that is addTagHelper, and you can place this into an individual view, or if you plan on using tag helpers throughout the application, you can use addTagHelper inside the ViewImports file as shown below. The directive to do that is addTagHelper, and you can place this into an individual view, or if you plan on using tag helpers throughout the application, you can use addTagHelper inside the ViewImports file as shown below. @using FirstAppDemo.Controllers @addTagHelper "*, Microsoft.AspNet.Mvc.TagHelpers" The syntax to register all the tag helpers that are in an assembly is to use asterisk comma (*,) and then the assembly name, Microsoft.AspNet.Mvc.TagHelpers. Because the first piece here is a type name, this is where we could list a specific tag helper if you only wanted to use one. But if you just wanted to take all the tag helpers that are in this assembly, you can just use the asterisk(*). There are many tag helpers available in the tag helper library. Let us have a look at the Index view. @model HomePageViewModel @{ ViewBag.Title = "Home"; } <h1>Welcome!</h1> <table> @foreach (var employee in Model.Employees) { <tr> <td> @Html.ActionLink(employee.Id.ToString(), "Details", new { id = employee.Id }) </td> <td>@employee.Name</td> </tr> } </table> We already have an HTML helper using the ActionLink to generate an anchor tag that will point to a URL that allows us to get to the details of an employee. Let us first add the Details action in the home controller as shown in the following program. public IActionResult Details(int id) { var context = new FirstAppDemoDbContext(); SQLEmployeeData sqlData = new SQLEmployeeData(context); var model = sqlData.Get(id); if (model == null) { return RedirectToAction("Index"); } return View(model); } Now we need to add a view for the Details action. Let us create a new view in the Views → Home folder and call it Details.cshtml and add the following code. @model FirstAppDemo.Models.Employee <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>@Model.Name</title> </head> <body> <h1>@Model.Name</h1> <div>Id: @Model.Id</div> <div> @Html.ActionLink("Home", "Index") </div> </body> </html> Let us now run the application. When you click on the ID of an employee then it will get you to the details view. Let us click the first employee ID. Now to use tag helper for this, let us add the following line in the index.cshtml file and remove the HTML helper. <a asp-action = "Details" asp-rout-id = "@employee.Id" >Details</a> The asp-action = "Details" is the name of the action that we want to get to. If there is any parameter that you want to be passed along, you can use the asp-route tag helper and here we want to include ID as parameter so we can use asp-route-Id taghelper. The following is the complete implantation of index.cshtml file. @model HomePageViewModel @{ ViewBag.Title = "Home"; } <h1>Welcome!</h1> <table> @foreach (var employee in Model.Employees) { <tr> <td> <a asp-action="Details" asp-route-id="@employee.Id" >Details</a> </td> <td>@employee.Name</td> </tr> } </table> Let us run your application again. After you run the application, you will see the following page. Previously, we were displaying the ID as the linking text, but now we are showing the text Details. Now, we click on the details and are creating the correct URL now using the tag helpers instead of the HTML helpers. Whether you choose to use HTML helpers or tag helpers, it's really a matter of personal preference. Many developers find tag helpers to be easier to author and maintain. 51 Lectures 5.5 hours Anadi Sharma 44 Lectures 4.5 hours Kaushik Roy Chowdhury 42 Lectures 18 hours SHIVPRASAD KOIRALA 57 Lectures 3.5 hours University Code 40 Lectures 2.5 hours University Code 138 Lectures 9 hours Bhrugen Patel Print Add Notes Bookmark this page
[ { "code": null, "e": 2654, "s": 2461, "text": "Tag Helpers enable server-side code to participate in creating and rendering HTML elements in Razor files. Tag helpers are a new feature and similar to HTML helpers, which help us render HTML." }, { "code": null, "e": 2887, "s": 2654, "text": "There are many built-in Tag Helpers for common tasks, such as creating forms, links, loading assets etc. Tag Helpers are authored in C#, and they target HTML elements based on the element name, the attribute name, or the parent tag." }, { "code": null, "e": 3120, "s": 2887, "text": "There are many built-in Tag Helpers for common tasks, such as creating forms, links, loading assets etc. Tag Helpers are authored in C#, and they target HTML elements based on the element name, the attribute name, or the parent tag." }, { "code": null, "e": 3245, "s": 3120, "text": "For example, the built-in LabelTagHelper can target the HTML <label> element when the LabelTagHelper attributes are applied." }, { "code": null, "e": 3370, "s": 3245, "text": "For example, the built-in LabelTagHelper can target the HTML <label> element when the LabelTagHelper attributes are applied." }, { "code": null, "e": 3489, "s": 3370, "text": "If you are familiar with HTML Helpers, Tag Helpers reduce the explicit transitions between HTML and C# in Razor views." }, { "code": null, "e": 3608, "s": 3489, "text": "If you are familiar with HTML Helpers, Tag Helpers reduce the explicit transitions between HTML and C# in Razor views." }, { "code": null, "e": 3857, "s": 3608, "text": "In order to use Tag Helpers, we need to install a NuGet library and also add an addTagHelper directive to the view or views that use these tag helpers. Let us right-click on your project in the Solution Explorer and select Manage NuGet Packages...." }, { "code": null, "e": 3930, "s": 3857, "text": "Search for Microsoft.AspNet.Mvc.TagHelpers and click the Install button." }, { "code": null, "e": 3981, "s": 3930, "text": "You will receive the following Preview dialog box." }, { "code": null, "e": 4002, "s": 3981, "text": "Click the OK button." }, { "code": null, "e": 4113, "s": 4002, "text": "Click the I Accept button. Once the Microsoft.AspNet.Mvc.TagHelpers is installed, go to the project.json file." }, { "code": null, "e": 5048, "s": 4113, "text": "{ \n \"version\": \"1.0.0-*\", \n \"compilationOptions\": { \n \"emitEntryPoint\": true \n }, \n \n \"dependencies\": { \n \"Microsoft.AspNet.Mvc\": \"6.0.0-rc1-final\", \n \"Microsoft.AspNet.Diagnostics\": \"1.0.0-rc1-final\", \n \"Microsoft.AspNet.IISPlatformHandler\": \"1.0.0-rc1-final\", \n \"Microsoft.AspNet.Server.Kestrel\": \"1.0.0-rc1-final\", \n \"Microsoft.AspNet.StaticFiles\": \"1.0.0-rc1-final\", \n \"EntityFramework.MicrosoftSqlServer\": \"7.0.0-rc1-final\", \n \"EntityFramework.Commands\": \"7.0.0-rc1-final\", \n \"Microsoft.AspNet.Mvc.TagHelpers\": \"6.0.0-rc1-final\" \n }, \n \n \"commands\": { \n \"web\": \"Microsoft.AspNet.Server.Kestrel\", \n \"ef\": \"EntityFramework.Commands\" \n }, \n \n \"frameworks\": { \n \"dnx451\": { }, \n \"dnxcore50\": { } \n }, \n \n \"exclude\": [ \n \"wwwroot\", \n \"node_modules\" \n ], \n \n \"publishExclude\": [ \n \"**.user\", \n \"**.vspscc\" \n ] \n}" }, { "code": null, "e": 5158, "s": 5048, "text": "In the dependencies section, you will see that \"Microsoft.AspNet.Mvc.TagHelpers\": \"6.0.0-rc1-final\" is added." }, { "code": null, "e": 5281, "s": 5158, "text": "Now anybody can author a tag helper, so if you can think of a tag helper that you need, you can write your own tag helper." }, { "code": null, "e": 5404, "s": 5281, "text": "Now anybody can author a tag helper, so if you can think of a tag helper that you need, you can write your own tag helper." }, { "code": null, "e": 5525, "s": 5404, "text": "You can place it right inside your application project, but you need to tell the Razor view engine about the tag helper." }, { "code": null, "e": 5646, "s": 5525, "text": "You can place it right inside your application project, but you need to tell the Razor view engine about the tag helper." }, { "code": null, "e": 5771, "s": 5646, "text": "By default, they are not just rendered down to the client, even though these tag helpers look like they blend into the HTML." }, { "code": null, "e": 5896, "s": 5771, "text": "By default, they are not just rendered down to the client, even though these tag helpers look like they blend into the HTML." }, { "code": null, "e": 6024, "s": 5896, "text": "Razor will call into some code to process a tag helper; it can remove itself from the HTML and it can also add additional HTML." }, { "code": null, "e": 6152, "s": 6024, "text": "Razor will call into some code to process a tag helper; it can remove itself from the HTML and it can also add additional HTML." }, { "code": null, "e": 6443, "s": 6152, "text": "There are many wonderful things that you can do with a tag helper, but you need to register your tag helpers with Razor, even the Microsoft tag helpers, in order for Razor to be able to spot these tag helpers in the markup and to be able to call into the code that processes the tag helper." }, { "code": null, "e": 6734, "s": 6443, "text": "There are many wonderful things that you can do with a tag helper, but you need to register your tag helpers with Razor, even the Microsoft tag helpers, in order for Razor to be able to spot these tag helpers in the markup and to be able to call into the code that processes the tag helper." }, { "code": null, "e": 6957, "s": 6734, "text": "The directive to do that is addTagHelper, and you can place this into an individual view, or if you plan on using tag helpers throughout the application, you can use addTagHelper inside the ViewImports file as shown below." }, { "code": null, "e": 7180, "s": 6957, "text": "The directive to do that is addTagHelper, and you can place this into an individual view, or if you plan on using tag helpers throughout the application, you can use addTagHelper inside the ViewImports file as shown below." }, { "code": null, "e": 7266, "s": 7180, "text": "@using FirstAppDemo.Controllers \n@addTagHelper \"*, Microsoft.AspNet.Mvc.TagHelpers\" \n" }, { "code": null, "e": 7550, "s": 7266, "text": "The syntax to register all the tag helpers that are in an assembly is to use asterisk comma (*,) and then the assembly name, Microsoft.AspNet.Mvc.TagHelpers. Because the first piece here is a type name, this is where we could list a specific tag helper if you only wanted to use one." }, { "code": null, "e": 7764, "s": 7550, "text": "But if you just wanted to take all the tag helpers that are in this assembly, you can just use the asterisk(*). There are many tag helpers available in the tag helper library. Let us have a look at the Index view." }, { "code": null, "e": 8099, "s": 7764, "text": "@model HomePageViewModel \n@{ \n ViewBag.Title = \"Home\"; \n} \n<h1>Welcome!</h1> \n\n<table> \n @foreach (var employee in Model.Employees) { \n <tr> \n <td>\n @Html.ActionLink(employee.Id.ToString(), \"Details\", new { id = employee.Id })\n </td> \n <td>@employee.Name</td> \n </tr> \n } \n</table>" }, { "code": null, "e": 8255, "s": 8099, "text": "We already have an HTML helper using the ActionLink to generate an anchor tag that will point to a URL that allows us to get to the details of an employee." }, { "code": null, "e": 8349, "s": 8255, "text": "Let us first add the Details action in the home controller as shown in the following program." }, { "code": null, "e": 8632, "s": 8349, "text": "public IActionResult Details(int id) { \n var context = new FirstAppDemoDbContext(); \n SQLEmployeeData sqlData = new SQLEmployeeData(context); \n var model = sqlData.Get(id); \n \n if (model == null) { \n return RedirectToAction(\"Index\"); \n } \n return View(model); \n} " }, { "code": null, "e": 8789, "s": 8632, "text": "Now we need to add a view for the Details action. Let us create a new view in the Views → Home folder and call it Details.cshtml and add the following code." }, { "code": null, "e": 9110, "s": 8789, "text": "@model FirstAppDemo.Models.Employee \n<html xmlns = \"http://www.w3.org/1999/xhtml\"> \n <head> \n <title>@Model.Name</title> \n </head> \n \n <body> \n <h1>@Model.Name</h1> \n <div>Id: @Model.Id</div> \n \n <div> \n @Html.ActionLink(\"Home\", \"Index\") \n </div> \n \n </body> \n</html>" }, { "code": null, "e": 9142, "s": 9110, "text": "Let us now run the application." }, { "code": null, "e": 9224, "s": 9142, "text": "When you click on the ID of an employee then it will get you to the details view." }, { "code": null, "e": 9260, "s": 9224, "text": "Let us click the first employee ID." }, { "code": null, "e": 9375, "s": 9260, "text": "Now to use tag helper for this, let us add the following line in the index.cshtml file and remove the HTML helper." }, { "code": null, "e": 9445, "s": 9375, "text": "<a asp-action = \"Details\" asp-rout-id = \"@employee.Id\" >Details</a> \n" }, { "code": null, "e": 9701, "s": 9445, "text": "The asp-action = \"Details\" is the name of the action that we want to get to. If there is any parameter that you want to be passed along, you can use the asp-route tag helper and here we want to include ID as parameter so we can use asp-route-Id taghelper." }, { "code": null, "e": 9766, "s": 9701, "text": "The following is the complete implantation of index.cshtml file." }, { "code": null, "e": 10091, "s": 9766, "text": "@model HomePageViewModel \n@{ \n ViewBag.Title = \"Home\"; \n} \n<h1>Welcome!</h1> \n\n<table> \n @foreach (var employee in Model.Employees) { \n <tr> \n <td> \n <a asp-action=\"Details\" asp-route-id=\"@employee.Id\" >Details</a> \n </td> \n <td>@employee.Name</td> \n </tr> \n } \n</table> " }, { "code": null, "e": 10190, "s": 10091, "text": "Let us run your application again. After you run the application, you will see the following page." }, { "code": null, "e": 10407, "s": 10190, "text": "Previously, we were displaying the ID as the linking text, but now we are showing the text Details. Now, we click on the details and are creating the correct URL now using the tag helpers instead of the HTML helpers." }, { "code": null, "e": 10577, "s": 10407, "text": "Whether you choose to use HTML helpers or tag helpers, it's really a matter of personal preference. Many developers find tag helpers to be easier to author and maintain." }, { "code": null, "e": 10612, "s": 10577, "text": "\n 51 Lectures \n 5.5 hours \n" }, { "code": null, "e": 10626, "s": 10612, "text": " Anadi Sharma" }, { "code": null, "e": 10661, "s": 10626, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 10684, "s": 10661, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 10718, "s": 10684, "text": "\n 42 Lectures \n 18 hours \n" }, { "code": null, "e": 10738, "s": 10718, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 10773, "s": 10738, "text": "\n 57 Lectures \n 3.5 hours \n" }, { "code": null, "e": 10790, "s": 10773, "text": " University Code" }, { "code": null, "e": 10825, "s": 10790, "text": "\n 40 Lectures \n 2.5 hours \n" }, { "code": null, "e": 10842, "s": 10825, "text": " University Code" }, { "code": null, "e": 10876, "s": 10842, "text": "\n 138 Lectures \n 9 hours \n" }, { "code": null, "e": 10891, "s": 10876, "text": " Bhrugen Patel" }, { "code": null, "e": 10898, "s": 10891, "text": " Print" }, { "code": null, "e": 10909, "s": 10898, "text": " Add Notes" } ]
Binding function in Python Tkinter
In python tkinter is a GUI library that can be used for various GUI programming. Such applications are useful to build desktop applications. In this article we will see one aspect of the GUI programming called Binding functions. This is about binding events to functions and methods so that when the event occurs that specific function is executed. In the below example we bind the press of any key from the keyboard with a function that gets executed. Once the Tkinter GUI window is open, we can press any key in the keyboard and we get a message that the keyboard is pressed. from tkinter import * # Press a buton in keyboard def PressAnyKey(label): value = label.char print(value, ' A button is pressed') base = Tk() base.geometry('300x150') base.bind('<Key>', lambda i : PressAnyKey(i)) mainloop() Running the above code gives us the following result − In the below example we see how to bind the mouse click events on a tkinter window to a function call. In the below example we call the events to display the left-button double click, right button click and scroll-button click to display the position in the tkinter canvas where the buttons were clicked. from tkinter import * from tkinter.ttk import * # creates tkinter window or root window base = Tk() base.geometry('300x150') # Press the scroll button in the mouse then function will be called def scroll(label): print('Scroll button clicked at x = % d, y = % d'%(label.x, label.y)) # Press the right button in the mouse then function will be called def right_click(label): print('right button clicked at x = % d, y = % d'%(label.x, label.y)) # Press the left button twice in the mouse then function will be called def left_click(label): print('Double clicked left button at x = % d, y = % d'%(label.x, label.y)) Function = Frame(base, height = 100, width = 200) Function.bind('<Button-2>', scroll) Function.bind('<Button-3>', right_click) Function.bind('<Double 1>', left_click) Function.pack() mainloop() Running the above code gives us the following result −
[ { "code": null, "e": 1411, "s": 1062, "text": "In python tkinter is a GUI library that can be used for various GUI programming. Such applications are useful to build desktop applications. In this article we will see one aspect of the GUI programming called Binding functions. This is about binding events to functions and methods so that when the event occurs that specific function is executed." }, { "code": null, "e": 1640, "s": 1411, "text": "In the below example we bind the press of any key from the keyboard with a function that gets executed. Once the Tkinter GUI window is open, we can press any key in the keyboard and we get a message that the keyboard is pressed." }, { "code": null, "e": 1873, "s": 1640, "text": "from tkinter import *\n\n# Press a buton in keyboard\ndef PressAnyKey(label):\n value = label.char\n print(value, ' A button is pressed')\n\nbase = Tk()\nbase.geometry('300x150')\nbase.bind('<Key>', lambda i : PressAnyKey(i))\nmainloop()\n" }, { "code": null, "e": 1928, "s": 1873, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2233, "s": 1928, "text": "In the below example we see how to bind the mouse click events on a tkinter window to a function call. In the below example we call the events to display the left-button double click, right button click and scroll-button click to display the position in the tkinter canvas where the buttons were clicked." }, { "code": null, "e": 3051, "s": 2233, "text": "from tkinter import *\nfrom tkinter.ttk import *\n\n# creates tkinter window or root window\nbase = Tk()\nbase.geometry('300x150')\n\n# Press the scroll button in the mouse then function will be called\ndef scroll(label):\n print('Scroll button clicked at x = % d, y = % d'%(label.x, label.y))\n# Press the right button in the mouse then function will be called\ndef right_click(label):\n print('right button clicked at x = % d, y = % d'%(label.x, label.y))\n# Press the left button twice in the mouse then function will be called\ndef left_click(label):\n print('Double clicked left button at x = % d, y = % d'%(label.x, label.y))\n\nFunction = Frame(base, height = 100, width = 200)\nFunction.bind('<Button-2>', scroll)\nFunction.bind('<Button-3>', right_click)\nFunction.bind('<Double 1>', left_click)\nFunction.pack()\nmainloop()" }, { "code": null, "e": 3106, "s": 3051, "text": "Running the above code gives us the following result −" } ]
Transform Invoices Into Tabular Data Using Python | by Pranjal Saxena | Towards Data Science
99% of text data is available in unstructured form. And, when we talk about the unstructured data that is hard to interpret and manage — Invoices are one example of unstructured data. When we work in the analytics and data science field, we usually need data in tabular form to analyse them. By analysing, I mean — we can plot the insights, monitoring, forecasting future insights, managing future demands, much more. As per the information on quora, a single large business can generate 33000 invoices in a month and based on a report by bizjournals — there are 16000+ large companies, which mean millions of invoices are being developed in a single day — which is a lot more unstructured data. The good thing with the invoices are — most of them follow the same patterns. So that says — if we can match the pattern of a single invoice, we can deal with all kinds of invoices in any industry. As of today, some of the industries have adopted automated invoice processing methods — the majority of them are still processing them manually, and a few are working on the same process of automating them to save time and money. Let’s have a look at how we can automate this process using python programming. Our end product will be a function that will take the list of pdf files as input and generate an excel sheet where a single row will denote an invoice file in a structured way. We will require a few libraries to read pdf files and applying a regular expression to our text data. pdfplumber — to read pdf files re — to apply regular expression pandas — to create and manipulate our dataset import pdfplumberimport reimport itertoolsimport pandas as pd Here, we have three sections. The first uppermost section gives us the details about date & time, username, program name, and the menu code. The second middle section tells us about the available menu options for this invoice. Finally, the third last bottom section tells us about the authorization code under each menu option. Our first goal is to make a python script that can distinguish between each section. with pdfplumber.open("Menu_Authorizations.pdf") as pdf: next_page_continue=False for pcount in range(len(pdf.pages)): page=pdf.pages[pcount] text=page.extract_text() The above code is helping us to open the pdf file. Here, we only have a single pdf file with 300 menus. Some menus are taking two pages as they have more menu options. We need to manage that case also based on regular expression results. We can use extract_text() function to extract data from the pdf. As we are using a loop so, at a time, an invoice will be entertained. When we iterate over the extracted text, our loop iterates the text, line by line. That means — we have to define regular expression based on lines our loop is executing. Let’s first define the regular expression for each condition. Menu number is present in the line where the line starts with “MENU”. Here, we need a regular expression that can detect that time. menu_re= re.compile(r'^MENU:') This single line of python can do that task for us. As per the menu format — just below the menu code, we can find the list of menu options. Here, we need to make sure our line has respective headers for the menu options table. menu_func_re=re.compile(r'^\s*\d+\s{2}[A-Za-z\s\d\W]+$') The above regular expression can help us if our line starts with space, number, and followed by two spaces. In this way, we can detect this line. The is the final section that we need to extract. We need to check if the line starts with the number followed by the code “APM”. APM_re=re.compile(r'\s*\d+\s+APM')APM_re_internal=re.compile(r"^AUTHORIZED:") The above two lines can do the task for us. Once the regular expression part is done — we can connect all the code sections with the necessary conditions. By running the code — we can get the lists of lists that denotes the documents and their relevant information. Now, we can use pandas to convert the lists of lists to a data frame and then export that data frame to an excel sheet. That’s all for this informative article. We have covered the step by step approach to convert the PDF invoices to an excel sheet. We have also covered the importance of this use case this time. I hope you liked the article. Stay tuned for the upcoming article. Thanks for the reading! Here are some of my best picks: towardsdatascience.com towardsdatascience.com betterprogramming.pub towardsdatascience.com Before you go... If you liked this article and want to stay tuned with more exciting articles on Python & Data Science — do consider becoming a medium member by clicking here https://pranjalai.medium.com/membership. Please do consider signing up using my referral link. In this way, the portion of the membership fee goes to me, which motivates me to write more exciting stuff on Python and Data Science. Also, feel free to subscribe to my free newsletter: Pranjal’s Newsletter.
[ { "code": null, "e": 231, "s": 47, "text": "99% of text data is available in unstructured form. And, when we talk about the unstructured data that is hard to interpret and manage — Invoices are one example of unstructured data." }, { "code": null, "e": 465, "s": 231, "text": "When we work in the analytics and data science field, we usually need data in tabular form to analyse them. By analysing, I mean — we can plot the insights, monitoring, forecasting future insights, managing future demands, much more." }, { "code": null, "e": 743, "s": 465, "text": "As per the information on quora, a single large business can generate 33000 invoices in a month and based on a report by bizjournals — there are 16000+ large companies, which mean millions of invoices are being developed in a single day — which is a lot more unstructured data." }, { "code": null, "e": 941, "s": 743, "text": "The good thing with the invoices are — most of them follow the same patterns. So that says — if we can match the pattern of a single invoice, we can deal with all kinds of invoices in any industry." }, { "code": null, "e": 1171, "s": 941, "text": "As of today, some of the industries have adopted automated invoice processing methods — the majority of them are still processing them manually, and a few are working on the same process of automating them to save time and money." }, { "code": null, "e": 1428, "s": 1171, "text": "Let’s have a look at how we can automate this process using python programming. Our end product will be a function that will take the list of pdf files as input and generate an excel sheet where a single row will denote an invoice file in a structured way." }, { "code": null, "e": 1530, "s": 1428, "text": "We will require a few libraries to read pdf files and applying a regular expression to our text data." }, { "code": null, "e": 1561, "s": 1530, "text": "pdfplumber — to read pdf files" }, { "code": null, "e": 1594, "s": 1561, "text": "re — to apply regular expression" }, { "code": null, "e": 1640, "s": 1594, "text": "pandas — to create and manipulate our dataset" }, { "code": null, "e": 1702, "s": 1640, "text": "import pdfplumberimport reimport itertoolsimport pandas as pd" }, { "code": null, "e": 2030, "s": 1702, "text": "Here, we have three sections. The first uppermost section gives us the details about date & time, username, program name, and the menu code. The second middle section tells us about the available menu options for this invoice. Finally, the third last bottom section tells us about the authorization code under each menu option." }, { "code": null, "e": 2115, "s": 2030, "text": "Our first goal is to make a python script that can distinguish between each section." }, { "code": null, "e": 2301, "s": 2115, "text": "with pdfplumber.open(\"Menu_Authorizations.pdf\") as pdf: next_page_continue=False for pcount in range(len(pdf.pages)): page=pdf.pages[pcount] text=page.extract_text()" }, { "code": null, "e": 2539, "s": 2301, "text": "The above code is helping us to open the pdf file. Here, we only have a single pdf file with 300 menus. Some menus are taking two pages as they have more menu options. We need to manage that case also based on regular expression results." }, { "code": null, "e": 2674, "s": 2539, "text": "We can use extract_text() function to extract data from the pdf. As we are using a loop so, at a time, an invoice will be entertained." }, { "code": null, "e": 2845, "s": 2674, "text": "When we iterate over the extracted text, our loop iterates the text, line by line. That means — we have to define regular expression based on lines our loop is executing." }, { "code": null, "e": 2907, "s": 2845, "text": "Let’s first define the regular expression for each condition." }, { "code": null, "e": 3039, "s": 2907, "text": "Menu number is present in the line where the line starts with “MENU”. Here, we need a regular expression that can detect that time." }, { "code": null, "e": 3070, "s": 3039, "text": "menu_re= re.compile(r'^MENU:')" }, { "code": null, "e": 3122, "s": 3070, "text": "This single line of python can do that task for us." }, { "code": null, "e": 3298, "s": 3122, "text": "As per the menu format — just below the menu code, we can find the list of menu options. Here, we need to make sure our line has respective headers for the menu options table." }, { "code": null, "e": 3355, "s": 3298, "text": "menu_func_re=re.compile(r'^\\s*\\d+\\s{2}[A-Za-z\\s\\d\\W]+$')" }, { "code": null, "e": 3501, "s": 3355, "text": "The above regular expression can help us if our line starts with space, number, and followed by two spaces. In this way, we can detect this line." }, { "code": null, "e": 3631, "s": 3501, "text": "The is the final section that we need to extract. We need to check if the line starts with the number followed by the code “APM”." }, { "code": null, "e": 3709, "s": 3631, "text": "APM_re=re.compile(r'\\s*\\d+\\s+APM')APM_re_internal=re.compile(r\"^AUTHORIZED:\")" }, { "code": null, "e": 3753, "s": 3709, "text": "The above two lines can do the task for us." }, { "code": null, "e": 3864, "s": 3753, "text": "Once the regular expression part is done — we can connect all the code sections with the necessary conditions." }, { "code": null, "e": 3975, "s": 3864, "text": "By running the code — we can get the lists of lists that denotes the documents and their relevant information." }, { "code": null, "e": 4095, "s": 3975, "text": "Now, we can use pandas to convert the lists of lists to a data frame and then export that data frame to an excel sheet." }, { "code": null, "e": 4289, "s": 4095, "text": "That’s all for this informative article. We have covered the step by step approach to convert the PDF invoices to an excel sheet. We have also covered the importance of this use case this time." }, { "code": null, "e": 4356, "s": 4289, "text": "I hope you liked the article. Stay tuned for the upcoming article." }, { "code": null, "e": 4380, "s": 4356, "text": "Thanks for the reading!" }, { "code": null, "e": 4412, "s": 4380, "text": "Here are some of my best picks:" }, { "code": null, "e": 4435, "s": 4412, "text": "towardsdatascience.com" }, { "code": null, "e": 4458, "s": 4435, "text": "towardsdatascience.com" }, { "code": null, "e": 4480, "s": 4458, "text": "betterprogramming.pub" }, { "code": null, "e": 4503, "s": 4480, "text": "towardsdatascience.com" }, { "code": null, "e": 4520, "s": 4503, "text": "Before you go..." }, { "code": null, "e": 4719, "s": 4520, "text": "If you liked this article and want to stay tuned with more exciting articles on Python & Data Science — do consider becoming a medium member by clicking here https://pranjalai.medium.com/membership." }, { "code": null, "e": 4908, "s": 4719, "text": "Please do consider signing up using my referral link. In this way, the portion of the membership fee goes to me, which motivates me to write more exciting stuff on Python and Data Science." } ]
Bubble Sort | Practice | GeeksforGeeks
Given an Integer N and a list arr. Sort the array using bubble sort algorithm. Example 1: Input: N = 5 arr[] = {4, 1, 3, 9, 7} Output: 1 3 4 7 9 Example 2: Input: N = 10 arr[] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1} Output: 1 2 3 4 5 6 7 8 9 10 Constraints: 1 <= N <= 103 1 <= arr[i] <= 103 0 visionsameer392 days ago python class Solution: def bubbleSort(self,arr, n): return arr.sort() 0 harshilrpanchal19984 days ago class Solution{ //Function to sort the array using bubble sort algorithm.public static void bubbleSort(int arr[], int n) { //code here for(int i= 0 ; i < n -1 ; i++){ for(int j=0 ; j < n-i-1 ; j++){ if(arr[j] > arr[j+1]){ int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } }} 0 mitrasouvik1235 days ago class Solution{ //Function to sort the array using bubble sort algorithm.public static void bubbleSort(int arr[], int n) { int temp=0; n=arr.length; for(int i = 0; i<n; i++) { boolean isSwapped = false; for(int j=1; j<(n-i); j++) { if(arr[j-1]>arr[j]) { temp = arr[j-1]; arr[j-1]=arr[j]; arr[j]=temp; isSwapped = true; } } if(!isSwapped) { break; } } }} +1 sangrambachu1 week ago Some cases it'll have O(n) Time complexity because of isSwapped flag. class Solution { //Function to sort the array using bubble sort algorithm. public static void bubbleSort(int arr[], int n) { //code here for(int i=0; i<n; i++) { boolean isSwapped = false; for(int j=0; j<n-i-1; j++) { if(arr[j+1] < arr[j]) { int temp = arr[j+1]; arr[j+1] = arr[j]; arr[j] = temp; isSwapped = true; } } if(!isSwapped) { break; } } } } 0 rohankundu8591 week ago //C++ Solution void swap(int *a,int *b) { int temp=*a; *a=*b; *b=temp; } //Function to sort the array using bubble sort algorithm. void bubbleSort(int arr[], int n) { // Your code here for(int i=0;i<n;i++) { for(int j=0;j<(n-i-1);j++) { if(arr[j]>arr[j+1]) { swap(&arr[j],&arr[j+1]); } } } } 0 haulya2 weeks ago void bubbleSort(int arr[], int n) { // Your code here for(int i=0; i < n; i++){ for(int j = 0; j < n-i-1; j++){ if(arr[j] > arr[j+1]) std::swap(arr[j], arr[j+1]); } } } 0 svidushi16102 weeks ago def bubbleSort(self,arr, n): n = len(arr) for i in range(n-1): for j in range(n-i-1): if arr[j]>arr[j+1]: arr[j],arr[j+1] = arr[j+1],arr[j] 0 sailendrachettri3 weeks ago C++ Solution Total Time Taken: 0.04/1.05 Optimized solution (bubble sort) void bubbleSort(int a[], int n) { for(int i = 0; i < n-1; i++) { bool isSorted = true; for(int j = 0; j < n-1-i; j++){ if(a[j] > a[j+1]){ int temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; isSorted = false; } } if(isSorted) break; } -1 atif836143 weeks ago Bubble sort class Solution { public static void bubbleSort(int arr[], int n) { if(arr.length==0){ return; } Arrays.sort(arr); } } 0 amrit_kumar3 weeks ago void bubbleSort(int arr[], int n) { for(int i=n-1;i>=0;i--) { for(int j=0;j<i;j++) { if(arr[j]>arr[j+1]) swap(&arr[j],&arr[j+1]); } } } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 380, "s": 290, "text": "Given an Integer N and a list arr. Sort the array using bubble sort algorithm.\nExample 1:" }, { "code": null, "e": 438, "s": 380, "text": "Input: \nN = 5\narr[] = {4, 1, 3, 9, 7}\nOutput: \n1 3 4 7 9\n" }, { "code": null, "e": 449, "s": 438, "text": "Example 2:" }, { "code": null, "e": 535, "s": 449, "text": "Input:\nN = 10 \narr[] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1}\nOutput: \n1 2 3 4 5 6 7 8 9 10\n" }, { "code": null, "e": 582, "s": 535, "text": "\nConstraints:\n1 <= N <= 103\n1 <= arr[i] <= 103" }, { "code": null, "e": 584, "s": 582, "text": "0" }, { "code": null, "e": 609, "s": 584, "text": "visionsameer392 days ago" }, { "code": null, "e": 616, "s": 609, "text": "python" }, { "code": null, "e": 693, "s": 618, "text": "class Solution: def bubbleSort(self,arr, n): return arr.sort() " }, { "code": null, "e": 695, "s": 693, "text": "0" }, { "code": null, "e": 725, "s": 695, "text": "harshilrpanchal19984 days ago" }, { "code": null, "e": 1137, "s": 725, "text": "class Solution{ //Function to sort the array using bubble sort algorithm.public static void bubbleSort(int arr[], int n) { //code here for(int i= 0 ; i < n -1 ; i++){ for(int j=0 ; j < n-i-1 ; j++){ if(arr[j] > arr[j+1]){ int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } }}" }, { "code": null, "e": 1139, "s": 1137, "text": "0" }, { "code": null, "e": 1164, "s": 1139, "text": "mitrasouvik1235 days ago" }, { "code": null, "e": 1748, "s": 1164, "text": "class Solution{ //Function to sort the array using bubble sort algorithm.public static void bubbleSort(int arr[], int n) { int temp=0; n=arr.length; for(int i = 0; i<n; i++) { boolean isSwapped = false; for(int j=1; j<(n-i); j++) { if(arr[j-1]>arr[j]) { temp = arr[j-1]; arr[j-1]=arr[j]; arr[j]=temp; isSwapped = true; } } if(!isSwapped) { break; } } }}" }, { "code": null, "e": 1751, "s": 1748, "text": "+1" }, { "code": null, "e": 1774, "s": 1751, "text": "sangrambachu1 week ago" }, { "code": null, "e": 1844, "s": 1774, "text": "Some cases it'll have O(n) Time complexity because of isSwapped flag." }, { "code": null, "e": 2435, "s": 1846, "text": "class Solution\n{\n //Function to sort the array using bubble sort algorithm.\n\tpublic static void bubbleSort(int arr[], int n)\n {\n //code here\n for(int i=0; i<n; i++) {\n boolean isSwapped = false;\n for(int j=0; j<n-i-1; j++) {\n if(arr[j+1] < arr[j]) {\n int temp = arr[j+1];\n arr[j+1] = arr[j];\n arr[j] = temp;\n isSwapped = true;\n }\n }\n \n if(!isSwapped) {\n break;\n }\n }\n }\n}" }, { "code": null, "e": 2437, "s": 2435, "text": "0" }, { "code": null, "e": 2461, "s": 2437, "text": "rohankundu8591 week ago" }, { "code": null, "e": 2476, "s": 2461, "text": "//C++ Solution" }, { "code": null, "e": 2903, "s": 2478, "text": " void swap(int *a,int *b) { int temp=*a; *a=*b; *b=temp; } //Function to sort the array using bubble sort algorithm. void bubbleSort(int arr[], int n) { // Your code here for(int i=0;i<n;i++) { for(int j=0;j<(n-i-1);j++) { if(arr[j]>arr[j+1]) { swap(&arr[j],&arr[j+1]); } } } }" }, { "code": null, "e": 2905, "s": 2903, "text": "0" }, { "code": null, "e": 2923, "s": 2905, "text": "haulya2 weeks ago" }, { "code": null, "e": 3171, "s": 2923, "text": " void bubbleSort(int arr[], int n) { // Your code here for(int i=0; i < n; i++){ for(int j = 0; j < n-i-1; j++){ if(arr[j] > arr[j+1]) std::swap(arr[j], arr[j+1]); } } }" }, { "code": null, "e": 3173, "s": 3171, "text": "0" }, { "code": null, "e": 3197, "s": 3173, "text": "svidushi16102 weeks ago" }, { "code": null, "e": 3398, "s": 3197, "text": "def bubbleSort(self,arr, n): n = len(arr) for i in range(n-1): for j in range(n-i-1): if arr[j]>arr[j+1]: arr[j],arr[j+1] = arr[j+1],arr[j]" }, { "code": null, "e": 3400, "s": 3398, "text": "0" }, { "code": null, "e": 3428, "s": 3400, "text": "sailendrachettri3 weeks ago" }, { "code": null, "e": 3469, "s": 3428, "text": "C++ Solution Total Time Taken: 0.04/1.05" }, { "code": null, "e": 3502, "s": 3469, "text": "Optimized solution (bubble sort)" }, { "code": null, "e": 3937, "s": 3502, "text": "void bubbleSort(int a[], int n)\n {\n for(int i = 0; i < n-1; i++) {\n bool isSorted = true;\n \n for(int j = 0; j < n-1-i; j++){\n if(a[j] > a[j+1]){\n int temp = a[j];\n a[j] = a[j+1];\n a[j+1] = temp;\n isSorted = false;\n }\n }\n \n if(isSorted) break;\n }" }, { "code": null, "e": 3942, "s": 3939, "text": "-1" }, { "code": null, "e": 3963, "s": 3942, "text": "atif836143 weeks ago" }, { "code": null, "e": 3975, "s": 3963, "text": "Bubble sort" }, { "code": null, "e": 4137, "s": 3975, "text": "class Solution\n{\npublic static void bubbleSort(int arr[], int n)\n {\n if(arr.length==0){\n return;\n }\n Arrays.sort(arr);\n }\n}\n" }, { "code": null, "e": 4139, "s": 4137, "text": "0" }, { "code": null, "e": 4162, "s": 4139, "text": "amrit_kumar3 weeks ago" }, { "code": null, "e": 4378, "s": 4162, "text": "void bubbleSort(int arr[], int n) { for(int i=n-1;i>=0;i--) { for(int j=0;j<i;j++) { if(arr[j]>arr[j+1]) swap(&arr[j],&arr[j+1]); } } }" }, { "code": null, "e": 4524, "s": 4378, "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": 4560, "s": 4524, "text": " Login to access your submissions. " }, { "code": null, "e": 4570, "s": 4560, "text": "\nProblem\n" }, { "code": null, "e": 4580, "s": 4570, "text": "\nContest\n" }, { "code": null, "e": 4643, "s": 4580, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 4791, "s": 4643, "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": 4999, "s": 4791, "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": 5105, "s": 4999, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Does C++ compiler create default constructor when we write our own?
In this tutorial, we will be discussing a program to understand if the C++ compiler creates a default constructor when we write our own. Generally, the C++ compiler uses the default constructor when no one is defined, but always uses the one defined by the user if any. Live Demo #include<iostream> using namespace std; class myInteger{ private: int value; //other functions in class }; int main(){ myInteger I1; getchar(); return 0; } Compiles successfully #include<iostream> using namespace std; class myInteger{ private: int value; public: myInteger(int v) //user-defined constructor { value = v; } //other functions in class }; int main(){ myInteger I1; getchar(); return 0; } Gives error about user-defined constructor not being defined
[ { "code": null, "e": 1199, "s": 1062, "text": "In this tutorial, we will be discussing a program to understand if the C++ compiler creates a default constructor when we write our own." }, { "code": null, "e": 1332, "s": 1199, "text": "Generally, the C++ compiler uses the default constructor when no one is defined, but always uses the one defined by the user if any." }, { "code": null, "e": 1343, "s": 1332, "text": " Live Demo" }, { "code": null, "e": 1514, "s": 1343, "text": "#include<iostream>\nusing namespace std;\nclass myInteger{\nprivate:\n int value;\n //other functions in class\n};\nint main(){\n myInteger I1;\n getchar();\n return 0;\n}" }, { "code": null, "e": 1536, "s": 1514, "text": "Compiles successfully" }, { "code": null, "e": 1792, "s": 1536, "text": "#include<iostream>\nusing namespace std;\nclass myInteger{\n private:\n int value;\n public:\n myInteger(int v) //user-defined constructor\n { value = v; }\n //other functions in class\n};\nint main(){\n myInteger I1;\n getchar();\n return 0;\n}" }, { "code": null, "e": 1853, "s": 1792, "text": "Gives error about user-defined constructor not being defined" } ]
Function to find the length of the second smallest word in a string in JavaScript
We are required to write a JavaScript function that takes in a string sentence as first and the only argument. And the function should return the length of the second smallest word from the string. For example: If the string is − const str = 'This is a sample string'; Then the output should be 2. Therefore, let’s write the code for this function − The code for this will be − const str = 'This is a sample string'; const secondSmallest = str => { const strArr = str.split(' '); if(strArr.length < 2){ return false; } for(let i = 0; i < strArr.length; i++){ strArr[i] = strArr[i].length; }; strArr.sort((a, b) => a - b); return strArr[1]; }; console.log(secondSmallest(str)); The output in the console will be − 2
[ { "code": null, "e": 1260, "s": 1062, "text": "We are required to write a JavaScript function that takes in a string sentence as first and the only argument. And the function should return the length of the second smallest word from the\nstring." }, { "code": null, "e": 1292, "s": 1260, "text": "For example: If the string is −" }, { "code": null, "e": 1331, "s": 1292, "text": "const str = 'This is a sample string';" }, { "code": null, "e": 1360, "s": 1331, "text": "Then the output should be 2." }, { "code": null, "e": 1412, "s": 1360, "text": "Therefore, let’s write the code for this function −" }, { "code": null, "e": 1440, "s": 1412, "text": "The code for this will be −" }, { "code": null, "e": 1775, "s": 1440, "text": "const str = 'This is a sample string';\nconst secondSmallest = str => {\n const strArr = str.split(' ');\n if(strArr.length < 2){\n return false;\n }\n for(let i = 0; i < strArr.length; i++){\n strArr[i] = strArr[i].length;\n };\n strArr.sort((a, b) => a - b);\n return strArr[1];\n};\nconsole.log(secondSmallest(str));" }, { "code": null, "e": 1811, "s": 1775, "text": "The output in the console will be −" }, { "code": null, "e": 1813, "s": 1811, "text": "2" } ]
Swing Examples - Creating Radio Button Group
Following example showcase how to use standard radio buttons in a group in a Java Swing application. We are using the following APIs. ButtonGroup − To create a Button group. ButtonGroup − To create a Button group. ButtonGroup.add(); − To add a radio button to a group. ButtonGroup.add(); − To add a radio button to a group. import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.LayoutManager; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import javax.swing.ButtonGroup; import javax.swing.JRadioButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; public class SwingTester { public static void main(String[] args) { createWindow(); } private static void createWindow() { JFrame frame = new JFrame("Swing Tester"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); createUI(frame); frame.setSize(560, 200); frame.setLocationRelativeTo(null); frame.setVisible(true); } private static void createUI(final JFrame frame){ JPanel panel = new JPanel(); LayoutManager layout = new FlowLayout(); panel.setLayout(layout); JRadioButton radioButton1 = new JRadioButton("Radio Button 1"); JRadioButton radioButton2 = new JRadioButton("Radio Button 2"); JRadioButton radioButton3 = new JRadioButton("Radio Button 3"); ButtonGroup group = new ButtonGroup(); group.add(radioButton1); group.add(radioButton2); group.add(radioButton3); panel.add(radioButton1); panel.add(radioButton2); panel.add(radioButton3); frame.getContentPane().add(panel, BorderLayout.CENTER); } } Print Add Notes Bookmark this page
[ { "code": null, "e": 2140, "s": 2039, "text": "Following example showcase how to use standard radio buttons in a group in a Java Swing application." }, { "code": null, "e": 2173, "s": 2140, "text": "We are using the following APIs." }, { "code": null, "e": 2213, "s": 2173, "text": "ButtonGroup − To create a Button group." }, { "code": null, "e": 2253, "s": 2213, "text": "ButtonGroup − To create a Button group." }, { "code": null, "e": 2308, "s": 2253, "text": "ButtonGroup.add(); − To add a radio button to a group." }, { "code": null, "e": 2363, "s": 2308, "text": "ButtonGroup.add(); − To add a radio button to a group." }, { "code": null, "e": 3796, "s": 2363, "text": "import java.awt.BorderLayout;\nimport java.awt.FlowLayout;\nimport java.awt.LayoutManager;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.awt.event.KeyEvent;\n\nimport javax.swing.ButtonGroup;\nimport javax.swing.JRadioButton;\nimport javax.swing.JFrame;\nimport javax.swing.JOptionPane;\nimport javax.swing.JPanel;\n\npublic class SwingTester {\n public static void main(String[] args) {\n createWindow();\n }\n\n private static void createWindow() { \n JFrame frame = new JFrame(\"Swing Tester\");\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\n createUI(frame);\n frame.setSize(560, 200); \n frame.setLocationRelativeTo(null); \n frame.setVisible(true);\n }\n\n private static void createUI(final JFrame frame){ \n JPanel panel = new JPanel();\n LayoutManager layout = new FlowLayout(); \n panel.setLayout(layout); \n\n JRadioButton radioButton1 = new JRadioButton(\"Radio Button 1\");\n JRadioButton radioButton2 = new JRadioButton(\"Radio Button 2\");\n JRadioButton radioButton3 = new JRadioButton(\"Radio Button 3\");\n\n ButtonGroup group = new ButtonGroup();\n group.add(radioButton1);\n group.add(radioButton2);\n group.add(radioButton3);\n\n panel.add(radioButton1);\n panel.add(radioButton2);\n panel.add(radioButton3);\n frame.getContentPane().add(panel, BorderLayout.CENTER); \n }\n}" }, { "code": null, "e": 3803, "s": 3796, "text": " Print" }, { "code": null, "e": 3814, "s": 3803, "text": " Add Notes" } ]
Monte Carlo Simulation and Variants with Python | by Tatev Karen | Towards Data Science
Monte Carlo Simulation is based on repeated random sampling. The underlying concept of Monte Carlo is to use randomness to solve problems that might be deterministic in principle. Monte Carlo simulation is one of the most popular techniques to draw inferences about a population without knowing the true underlying population distribution. This sampling technique becomes handy especially when one doesn’t have the luxury to repeatedly sample from the original population. Applications of Monte Carlo Simulation range from solving problems in theoretical physics to predicting trends in financial investments. Monte Carlo has 3 main usages: estimate parameters or statistical measures, examine the properties of the estimates, approximate integrals This article is about these 3 usages of the Monte Carlo procedures and about 3 Monte Carlo variants, statistical sampling techniques, which can be used to generate independent random samples. The article will cover the following topics: - Introduction to Monte Carlo Simulation- MC Parameter Estimation- MC Examining the Estimate Properties- MC Integrals Approximation- Importance Sampling- Rejection Sampling- Inverse Transform Sampling This article is suited for readers who have prior Statistical knowledge since it will cover medium-level statistical concepts and examples. If you want to learn essential statistical concepts from scratch, you can check my previous article about Fundamentals Of Statistics here. Monte Carlo simulation was initially invented to solve Buffon’s needle problem, in which π, pi, could be estimated by dropping needles on a floor made of parallel equidistant strips. The modern version of Monte Carlo Simulation was invented by Stanislaw Ulam, inventor of the modern version of the Markov Chain Monte Carlo technique during his work on nuclear weapons projects, and John von Neumann who programmed a special computer to perform Monte Carlo calculations. Von Neumann is also known for his famous approach to making unfair dice a fair one by tossing an unfair coin twice and ignoring the differing {Head, Tail} and {Tail, Head} options. Ulam’s proposed approach which was based on a list of truly random numbers was extremely slow, but Von Neumann developed a method to calculate pseudorandom numbers, which was much faster than Ulam’s approach. The name of this approach comes from the Monte Carlo Casino in Monaco where Ulam’s uncle would borrow money from relatives to gamble. Von Neumann is also known for his famous approach to making an unfair dice a fair one by tossing unfair coin twice and ignoring the differing HT and TH options. The idea behind Monte Carlo is that, as we use more samples, our answers should get more and more accurate. Monte Carlo uses the Law of Large Numbers (LLN) to come up with an estimate for a population parameter using simulated values. LLN states: suppose X1, X2, . . . , Xn are all independent random variables with the same underlying distribution, also called independent identically-distributed or i.i.d, where all X’s have the same mean μ and standard deviation σ. As the sample size grows, the probability that the average of all X’s is equal to the mean μ is equal to 1. The LLN can be summarized as follows: Consequently, the idea behind Monte Carlo estimation is that when we obtain an estimate for a parameter a large number of times, let’s say M = 10000 times, then the mean of these estimates will form a Monte Carlo unbiased estimate for that parameter. Let’s say we want to estimate a causal effect between two variables, pair of independent and dependent variables and we have some idea about possible values of intercept alpha and slope parameter beta. What we can do is we can randomly sample from normal distribution to generate error terms, dependent and independent variable values. Then we can estimate the coefficient of beta, beta_hat, and repeat this process M = 10000 times. Then by the LLN, the sample mean of these 10000 beta_hats will be an unbiased estimate for the true beta. That is: Monte Carlo Simulation is a powerful tool t examine the properties of estimators. This might not be very useful when examining the properties of Linear Regression estimates since most of the statistical software packages already provide measures to examine the estimates. However, in the case of other estimates using Monet Carlo Estimation might be the only way to find out whether the estimator is unbiased, efficient, and consistent. Is the Estimate Unbiased? The bias of an estimator is the difference between its expected value and the true value of the parameter being estimated and can be expressed as follows: When we state that the estimator is unbiased what we mean is that the bias is equal to zero, which implies that the expected value of the estimator is equal to the true parameter value, that is: To check whether the estimator is unbiased, we can use the Monte Carlo samples of beta_hats that we obtained in the previous step and draw this sampling distribution. Then, if this sampling distribution is centered around the true parameter value, then the estimator is unbiased. From the figure we can see that, the sampling distribution of beta estimates that we obtained using Monte Carlo simulation with 10000 iterations, is centered around the true parameter beta. So, the Monte Carlo estimate of beta_hat is unbiased. If the estimator converges to the true parameter as the sample size becomes very large, then this estimator is said to be consistent, that is: To check whether the estimator is consistent, we can use the Monte Carlo Samples of beta_hats that we obtained in the previous step and draw its sampling distribution for a small and large number of M simulations. If we see that the sampling distribution gets narrower and more centered around the true parameter values as the sample size increases (number of Monte Carlo Simulation interactions), then the estimate is likely to be consistent. A parameter can have multiple estimators but the one with the lowest variance is called efficient. To check whether the estimator is efficient, we can use the Monte Carlo Samples of beta_hats that we obtained in the previous step and draw this sampling distribution for a small and large number of M simulations. If we see that the width of the sampling distribution gets smaller as the sample size increases, then the estimate is likely to be efficient. Let’s say we run a Monte Carlo simulation with M = 1000 and obtain a Monte Carlo estimate for beta (left histogram). Moreover, we rerun this simulation with M = 10000 (right histogram). We see that as M increases from 1000 to 10000, the sampling distribution of beta_hats gets more centered around true parameter value. So, the Monte Carlo estimate of beta_hat is consistent. We see that as M increases from 1000 to 10000, the width of the sampling distribution of beta_hat decreases. So, the Monte Carlo estimate of beta_hat is efficient. For known functions such as the Normal distribution function, calculating integral might be simple and would not require the usage of MC. However, for more complicated functions computing integrals might be very hard and in those situations using MC could be the only way to calculate this integral. MC for approximating integrals is based on the LLN and the idea behind it is that if we can generate random samples xi from a given distribution P(x), then we can estimate the expected value of a function under this distribution by summation, rather than integration. Stated differently, we can find the value of an integral by determining the average value of its integrand, h(x). The MC is based on this principle, as we saw earlier. Let’s say we want to obtain the probability Pr[X ≥ 3] where X~Norm(10, 2), which can be expressed by the following integral where f(x) is the pdf function of Normal distribution. Then this integral can be obtained using Monte Carlo simulation by calculating this amount 10000 times and taking the mean of these values. Importance sampling is one way to make Monte Carlo simulations converge much faster. Moreover, Importance sampling results also in lower variance compared to the naive Monte Carlo approach. It is used for estimating the expected value of a certain h(x) function from target distribution g(x) while having access to some f(x) function. The idea is to use some proposal distribution f(x) to sample from and using importance weights w = g(x)/f(x) which mitigate this effect of overestimating or underestimating the target distribution g(x). Let’s say we want to estimate the expected value of a random variable X which follows Exponential Distribution. So, our target distribution is exponential , g(x) = Exp(1), and the h(x) = exp(-X + cos(X)). For Importance sampling we need to choose a proposal distribution that is as close as possible to the target distribution, hence we choose f(x) = Exp(2). Given that the pdf of the exponential function is exp(-lambda*x), then we have: where the f(x) is the proposal distribution from which we can sample, h(x) the function for which the expected value needs to be estimated, g(x) is the target distribution from which we can’t sample, w(x) is the importance weights. Then the expectation can of h(x) be expressed as follows: Then using the LLN, we can express this expectation as follows: Following graph visualizes the h(x), the target distribution g(x) and the proposal distribution f(x) plots. As we can see, the proposal distribution is very close to the target distribution. The f(x) is used to randomly sample 1000 observations and calculate each time the expression g(x)/f(x)*h(x), that is to calculate the importance weight and multiply it with h(x). Then, we take the mean of these values which gives us 1.52 which is the Expected Value we were looking for. Rejection Sampling is usually used to generate independent samples from the unnormalized target distribution. The idea behind this Monte Carlo sampling variant is that if we want to generate random samples from target unnormalized distribution P(x) then we can use some proposal distribution Q(x), a normalization constant c such that cQ(x) is an upper bound for some auxiliary distribution P*(x) where P(x) = P*(x) / c to come up with a list of samples from which the accepted values will form independent samples from the target P(X) distribution. 1: Choose a proposal function Q(X) that is close to target distribution P(X) 2: Choose a normalization constant c such that P*(x) ≤ cQ(x) 3: Choose auxiliary distribution P*(X) s.t. P(x) = P*(x)/c 4: Generate random samples, x, from Q(X) 5: Generate random samples, u, from Unif(0 , cQ(x)) 6: Repeat step 1 and 2 M times (e.g. 10000 times) 7: Accept x if u ≤ P*(x) and reject otherwise Important Requirements for Rejection Sampling: Proposal distribution Q(x) to sample from (Uniform or Gaussian) Normalization constant c such that c*Q(x) Auxiliary distribution P*(x) Access to sampling from the proposal distribution Let's say we want to generate independent samples from a mixture of Normal Distributions, which we expect to have a distribution similar to p*(x) = N(30,10) + N(80,20). We have access to Normal and Uniform distributions to sample from to generate these target samples. We can use a proposal function Q(x) = N(50,30), with a normalization constant c = max(P*(x)/Q(x)). We then follow the steps described earlier to generate samples from which a very large amount gets rejected and some get accepted. Following histogram visualizes the set of accepted samples which are independent samples from a Mixture of Normal distribution, while having access only to the Normal and Uniform random generators. Rejection Sampling is highly inefficient given that it rejects very large amount of sample points, which results in very large computation time. Like Rejection sampling, Inverse Transform Sampling is a way to generate independent samples but unlike Rejection Sampling, Inverse Transform Sapling is 100% efficient. The idea behind Inverse Transform Sampling is to use the Inverse Cumulative Distribution Function of a target population distribution to which we have no access to sample from and use a random generator from which we can easily sample, to generate an independent random sample from the target population. 1: Sample value u from Unif(0,1) 2: Use the inverse CDF function of target distribution to get the x value corresponding to the inverse CDF with value u 3: Repeat step 1 and 2 M times (e.g. 10000 times) 4: Collect these x values which follow the desired distribution Important Requirements for ITS: Access to sampling from Unif(0,1) Know the target distribution PDF/CDF Able to determine the inverse CDF of the target distribution Let’s say we want to generate independent samples from Exponential distribution with lambda equal to1 while we can only sample from Uniform distribution. Hence, we can determine the inverse CDF of Exponential distribution as follows: Then, we randomly sample from Unif(0,1) and use this value u to determine the x using the defined inverse CDF of the target distribution, which is -log(1-u). Once this process is repeated M = 10000 times, the stored samples are independent samples from the target distribution. The following histogram visualizes these samples. Unlike Rejection Sampling, Inverse Transform Sapling is 100% efficient. The computational efficiency of the Monte Carlo variant will be the best if the proposal distribution looks a lot like the target distribution. Importance Sampling, Rejection Sampling, and Inverse Transform Sampling methods can all fail badly when the proposal distribution has 0 density in a region where the target distribution has non-negligible density. Thus, the proposal distribution should have heavy tails. towardsdatascience.com https://www.youtube.com/watch?v=kYWHfgkRc9s&ab_channel=BenLambert https://www.youtube.com/watch?v=V8f8ueBc9sY&t=1s&ab_channel=BenLambert https://www.youtube.com/watch?v=rnBbYsysPaU&t=566s&ab_channel=BenLambert github.com towardsdatascience.com towardsdatascience.com towardsdatascience.com towardsdatascience.com tatev-aslanyan.medium.com tatev-aslanyan.medium.com medium.com Thanks for the read I encourage you to join Medium today to have complete access to all of the great locked content published across Medium and on my feed where I publish about various Data Science, Machine Learning, and Deep Learning topics. Follow me up on Medium to read more articles about various Data Science and Data Analytics topics. For more hands-on applications of Machine Learning, Mathematical and Statistical concepts check out my Github account.I welcome feedback and can be reached out on LinkedIn.
[ { "code": null, "e": 782, "s": 172, "text": "Monte Carlo Simulation is based on repeated random sampling. The underlying concept of Monte Carlo is to use randomness to solve problems that might be deterministic in principle. Monte Carlo simulation is one of the most popular techniques to draw inferences about a population without knowing the true underlying population distribution. This sampling technique becomes handy especially when one doesn’t have the luxury to repeatedly sample from the original population. Applications of Monte Carlo Simulation range from solving problems in theoretical physics to predicting trends in financial investments." }, { "code": null, "e": 921, "s": 782, "text": "Monte Carlo has 3 main usages: estimate parameters or statistical measures, examine the properties of the estimates, approximate integrals" }, { "code": null, "e": 1158, "s": 921, "text": "This article is about these 3 usages of the Monte Carlo procedures and about 3 Monte Carlo variants, statistical sampling techniques, which can be used to generate independent random samples. The article will cover the following topics:" }, { "code": null, "e": 1359, "s": 1158, "text": "- Introduction to Monte Carlo Simulation- MC Parameter Estimation- MC Examining the Estimate Properties- MC Integrals Approximation- Importance Sampling- Rejection Sampling- Inverse Transform Sampling" }, { "code": null, "e": 1638, "s": 1359, "text": "This article is suited for readers who have prior Statistical knowledge since it will cover medium-level statistical concepts and examples. If you want to learn essential statistical concepts from scratch, you can check my previous article about Fundamentals Of Statistics here." }, { "code": null, "e": 2289, "s": 1638, "text": "Monte Carlo simulation was initially invented to solve Buffon’s needle problem, in which π, pi, could be estimated by dropping needles on a floor made of parallel equidistant strips. The modern version of Monte Carlo Simulation was invented by Stanislaw Ulam, inventor of the modern version of the Markov Chain Monte Carlo technique during his work on nuclear weapons projects, and John von Neumann who programmed a special computer to perform Monte Carlo calculations. Von Neumann is also known for his famous approach to making unfair dice a fair one by tossing an unfair coin twice and ignoring the differing {Head, Tail} and {Tail, Head} options." }, { "code": null, "e": 2632, "s": 2289, "text": "Ulam’s proposed approach which was based on a list of truly random numbers was extremely slow, but Von Neumann developed a method to calculate pseudorandom numbers, which was much faster than Ulam’s approach. The name of this approach comes from the Monte Carlo Casino in Monaco where Ulam’s uncle would borrow money from relatives to gamble." }, { "code": null, "e": 2793, "s": 2632, "text": "Von Neumann is also known for his famous approach to making an unfair dice a fair one by tossing unfair coin twice and ignoring the differing HT and TH options." }, { "code": null, "e": 2901, "s": 2793, "text": "The idea behind Monte Carlo is that, as we use more samples, our answers should get more and more accurate." }, { "code": null, "e": 3408, "s": 2901, "text": "Monte Carlo uses the Law of Large Numbers (LLN) to come up with an estimate for a population parameter using simulated values. LLN states: suppose X1, X2, . . . , Xn are all independent random variables with the same underlying distribution, also called independent identically-distributed or i.i.d, where all X’s have the same mean μ and standard deviation σ. As the sample size grows, the probability that the average of all X’s is equal to the mean μ is equal to 1. The LLN can be summarized as follows:" }, { "code": null, "e": 3659, "s": 3408, "text": "Consequently, the idea behind Monte Carlo estimation is that when we obtain an estimate for a parameter a large number of times, let’s say M = 10000 times, then the mean of these estimates will form a Monte Carlo unbiased estimate for that parameter." }, { "code": null, "e": 3861, "s": 3659, "text": "Let’s say we want to estimate a causal effect between two variables, pair of independent and dependent variables and we have some idea about possible values of intercept alpha and slope parameter beta." }, { "code": null, "e": 4207, "s": 3861, "text": "What we can do is we can randomly sample from normal distribution to generate error terms, dependent and independent variable values. Then we can estimate the coefficient of beta, beta_hat, and repeat this process M = 10000 times. Then by the LLN, the sample mean of these 10000 beta_hats will be an unbiased estimate for the true beta. That is:" }, { "code": null, "e": 4644, "s": 4207, "text": "Monte Carlo Simulation is a powerful tool t examine the properties of estimators. This might not be very useful when examining the properties of Linear Regression estimates since most of the statistical software packages already provide measures to examine the estimates. However, in the case of other estimates using Monet Carlo Estimation might be the only way to find out whether the estimator is unbiased, efficient, and consistent." }, { "code": null, "e": 4670, "s": 4644, "text": "Is the Estimate Unbiased?" }, { "code": null, "e": 4825, "s": 4670, "text": "The bias of an estimator is the difference between its expected value and the true value of the parameter being estimated and can be expressed as follows:" }, { "code": null, "e": 5020, "s": 4825, "text": "When we state that the estimator is unbiased what we mean is that the bias is equal to zero, which implies that the expected value of the estimator is equal to the true parameter value, that is:" }, { "code": null, "e": 5300, "s": 5020, "text": "To check whether the estimator is unbiased, we can use the Monte Carlo samples of beta_hats that we obtained in the previous step and draw this sampling distribution. Then, if this sampling distribution is centered around the true parameter value, then the estimator is unbiased." }, { "code": null, "e": 5544, "s": 5300, "text": "From the figure we can see that, the sampling distribution of beta estimates that we obtained using Monte Carlo simulation with 10000 iterations, is centered around the true parameter beta. So, the Monte Carlo estimate of beta_hat is unbiased." }, { "code": null, "e": 5687, "s": 5544, "text": "If the estimator converges to the true parameter as the sample size becomes very large, then this estimator is said to be consistent, that is:" }, { "code": null, "e": 6131, "s": 5687, "text": "To check whether the estimator is consistent, we can use the Monte Carlo Samples of beta_hats that we obtained in the previous step and draw its sampling distribution for a small and large number of M simulations. If we see that the sampling distribution gets narrower and more centered around the true parameter values as the sample size increases (number of Monte Carlo Simulation interactions), then the estimate is likely to be consistent." }, { "code": null, "e": 6586, "s": 6131, "text": "A parameter can have multiple estimators but the one with the lowest variance is called efficient. To check whether the estimator is efficient, we can use the Monte Carlo Samples of beta_hats that we obtained in the previous step and draw this sampling distribution for a small and large number of M simulations. If we see that the width of the sampling distribution gets smaller as the sample size increases, then the estimate is likely to be efficient." }, { "code": null, "e": 7126, "s": 6586, "text": "Let’s say we run a Monte Carlo simulation with M = 1000 and obtain a Monte Carlo estimate for beta (left histogram). Moreover, we rerun this simulation with M = 10000 (right histogram). We see that as M increases from 1000 to 10000, the sampling distribution of beta_hats gets more centered around true parameter value. So, the Monte Carlo estimate of beta_hat is consistent. We see that as M increases from 1000 to 10000, the width of the sampling distribution of beta_hat decreases. So, the Monte Carlo estimate of beta_hat is efficient." }, { "code": null, "e": 7426, "s": 7126, "text": "For known functions such as the Normal distribution function, calculating integral might be simple and would not require the usage of MC. However, for more complicated functions computing integrals might be very hard and in those situations using MC could be the only way to calculate this integral." }, { "code": null, "e": 7862, "s": 7426, "text": "MC for approximating integrals is based on the LLN and the idea behind it is that if we can generate random samples xi from a given distribution P(x), then we can estimate the expected value of a function under this distribution by summation, rather than integration. Stated differently, we can find the value of an integral by determining the average value of its integrand, h(x). The MC is based on this principle, as we saw earlier." }, { "code": null, "e": 8041, "s": 7862, "text": "Let’s say we want to obtain the probability Pr[X ≥ 3] where X~Norm(10, 2), which can be expressed by the following integral where f(x) is the pdf function of Normal distribution." }, { "code": null, "e": 8181, "s": 8041, "text": "Then this integral can be obtained using Monte Carlo simulation by calculating this amount 10000 times and taking the mean of these values." }, { "code": null, "e": 8719, "s": 8181, "text": "Importance sampling is one way to make Monte Carlo simulations converge much faster. Moreover, Importance sampling results also in lower variance compared to the naive Monte Carlo approach. It is used for estimating the expected value of a certain h(x) function from target distribution g(x) while having access to some f(x) function. The idea is to use some proposal distribution f(x) to sample from and using importance weights w = g(x)/f(x) which mitigate this effect of overestimating or underestimating the target distribution g(x)." }, { "code": null, "e": 8924, "s": 8719, "text": "Let’s say we want to estimate the expected value of a random variable X which follows Exponential Distribution. So, our target distribution is exponential , g(x) = Exp(1), and the h(x) = exp(-X + cos(X))." }, { "code": null, "e": 9158, "s": 8924, "text": "For Importance sampling we need to choose a proposal distribution that is as close as possible to the target distribution, hence we choose f(x) = Exp(2). Given that the pdf of the exponential function is exp(-lambda*x), then we have:" }, { "code": null, "e": 9448, "s": 9158, "text": "where the f(x) is the proposal distribution from which we can sample, h(x) the function for which the expected value needs to be estimated, g(x) is the target distribution from which we can’t sample, w(x) is the importance weights. Then the expectation can of h(x) be expressed as follows:" }, { "code": null, "e": 9512, "s": 9448, "text": "Then using the LLN, we can express this expectation as follows:" }, { "code": null, "e": 9990, "s": 9512, "text": "Following graph visualizes the h(x), the target distribution g(x) and the proposal distribution f(x) plots. As we can see, the proposal distribution is very close to the target distribution. The f(x) is used to randomly sample 1000 observations and calculate each time the expression g(x)/f(x)*h(x), that is to calculate the importance weight and multiply it with h(x). Then, we take the mean of these values which gives us 1.52 which is the Expected Value we were looking for." }, { "code": null, "e": 10540, "s": 9990, "text": "Rejection Sampling is usually used to generate independent samples from the unnormalized target distribution. The idea behind this Monte Carlo sampling variant is that if we want to generate random samples from target unnormalized distribution P(x) then we can use some proposal distribution Q(x), a normalization constant c such that cQ(x) is an upper bound for some auxiliary distribution P*(x) where P(x) = P*(x) / c to come up with a list of samples from which the accepted values will form independent samples from the target P(X) distribution." }, { "code": null, "e": 10617, "s": 10540, "text": "1: Choose a proposal function Q(X) that is close to target distribution P(X)" }, { "code": null, "e": 10678, "s": 10617, "text": "2: Choose a normalization constant c such that P*(x) ≤ cQ(x)" }, { "code": null, "e": 10737, "s": 10678, "text": "3: Choose auxiliary distribution P*(X) s.t. P(x) = P*(x)/c" }, { "code": null, "e": 10778, "s": 10737, "text": "4: Generate random samples, x, from Q(X)" }, { "code": null, "e": 10830, "s": 10778, "text": "5: Generate random samples, u, from Unif(0 , cQ(x))" }, { "code": null, "e": 10880, "s": 10830, "text": "6: Repeat step 1 and 2 M times (e.g. 10000 times)" }, { "code": null, "e": 10926, "s": 10880, "text": "7: Accept x if u ≤ P*(x) and reject otherwise" }, { "code": null, "e": 10973, "s": 10926, "text": "Important Requirements for Rejection Sampling:" }, { "code": null, "e": 11037, "s": 10973, "text": "Proposal distribution Q(x) to sample from (Uniform or Gaussian)" }, { "code": null, "e": 11079, "s": 11037, "text": "Normalization constant c such that c*Q(x)" }, { "code": null, "e": 11108, "s": 11079, "text": "Auxiliary distribution P*(x)" }, { "code": null, "e": 11158, "s": 11108, "text": "Access to sampling from the proposal distribution" }, { "code": null, "e": 11526, "s": 11158, "text": "Let's say we want to generate independent samples from a mixture of Normal Distributions, which we expect to have a distribution similar to p*(x) = N(30,10) + N(80,20). We have access to Normal and Uniform distributions to sample from to generate these target samples. We can use a proposal function Q(x) = N(50,30), with a normalization constant c = max(P*(x)/Q(x))." }, { "code": null, "e": 11855, "s": 11526, "text": "We then follow the steps described earlier to generate samples from which a very large amount gets rejected and some get accepted. Following histogram visualizes the set of accepted samples which are independent samples from a Mixture of Normal distribution, while having access only to the Normal and Uniform random generators." }, { "code": null, "e": 12000, "s": 11855, "text": "Rejection Sampling is highly inefficient given that it rejects very large amount of sample points, which results in very large computation time." }, { "code": null, "e": 12474, "s": 12000, "text": "Like Rejection sampling, Inverse Transform Sampling is a way to generate independent samples but unlike Rejection Sampling, Inverse Transform Sapling is 100% efficient. The idea behind Inverse Transform Sampling is to use the Inverse Cumulative Distribution Function of a target population distribution to which we have no access to sample from and use a random generator from which we can easily sample, to generate an independent random sample from the target population." }, { "code": null, "e": 12507, "s": 12474, "text": "1: Sample value u from Unif(0,1)" }, { "code": null, "e": 12627, "s": 12507, "text": "2: Use the inverse CDF function of target distribution to get the x value corresponding to the inverse CDF with value u" }, { "code": null, "e": 12677, "s": 12627, "text": "3: Repeat step 1 and 2 M times (e.g. 10000 times)" }, { "code": null, "e": 12741, "s": 12677, "text": "4: Collect these x values which follow the desired distribution" }, { "code": null, "e": 12773, "s": 12741, "text": "Important Requirements for ITS:" }, { "code": null, "e": 12807, "s": 12773, "text": "Access to sampling from Unif(0,1)" }, { "code": null, "e": 12844, "s": 12807, "text": "Know the target distribution PDF/CDF" }, { "code": null, "e": 12905, "s": 12844, "text": "Able to determine the inverse CDF of the target distribution" }, { "code": null, "e": 13139, "s": 12905, "text": "Let’s say we want to generate independent samples from Exponential distribution with lambda equal to1 while we can only sample from Uniform distribution. Hence, we can determine the inverse CDF of Exponential distribution as follows:" }, { "code": null, "e": 13467, "s": 13139, "text": "Then, we randomly sample from Unif(0,1) and use this value u to determine the x using the defined inverse CDF of the target distribution, which is -log(1-u). Once this process is repeated M = 10000 times, the stored samples are independent samples from the target distribution. The following histogram visualizes these samples." }, { "code": null, "e": 13539, "s": 13467, "text": "Unlike Rejection Sampling, Inverse Transform Sapling is 100% efficient." }, { "code": null, "e": 13683, "s": 13539, "text": "The computational efficiency of the Monte Carlo variant will be the best if the proposal distribution looks a lot like the target distribution." }, { "code": null, "e": 13954, "s": 13683, "text": "Importance Sampling, Rejection Sampling, and Inverse Transform Sampling methods can all fail badly when the proposal distribution has 0 density in a region where the target distribution has non-negligible density. Thus, the proposal distribution should have heavy tails." }, { "code": null, "e": 13977, "s": 13954, "text": "towardsdatascience.com" }, { "code": null, "e": 14043, "s": 13977, "text": "https://www.youtube.com/watch?v=kYWHfgkRc9s&ab_channel=BenLambert" }, { "code": null, "e": 14114, "s": 14043, "text": "https://www.youtube.com/watch?v=V8f8ueBc9sY&t=1s&ab_channel=BenLambert" }, { "code": null, "e": 14187, "s": 14114, "text": "https://www.youtube.com/watch?v=rnBbYsysPaU&t=566s&ab_channel=BenLambert" }, { "code": null, "e": 14198, "s": 14187, "text": "github.com" }, { "code": null, "e": 14221, "s": 14198, "text": "towardsdatascience.com" }, { "code": null, "e": 14244, "s": 14221, "text": "towardsdatascience.com" }, { "code": null, "e": 14267, "s": 14244, "text": "towardsdatascience.com" }, { "code": null, "e": 14290, "s": 14267, "text": "towardsdatascience.com" }, { "code": null, "e": 14316, "s": 14290, "text": "tatev-aslanyan.medium.com" }, { "code": null, "e": 14342, "s": 14316, "text": "tatev-aslanyan.medium.com" }, { "code": null, "e": 14353, "s": 14342, "text": "medium.com" }, { "code": null, "e": 14373, "s": 14353, "text": "Thanks for the read" }, { "code": null, "e": 14596, "s": 14373, "text": "I encourage you to join Medium today to have complete access to all of the great locked content published across Medium and on my feed where I publish about various Data Science, Machine Learning, and Deep Learning topics." } ]
Converting degree to radian in JavaScript
The radian is the unit for measuring angles and is the standard unit of angular measure used in many areas of mathematics. We are required to write a JavaScript function that takes in a number that represents some degree and returns its corresponding radian. Following is the code − const deg = 180; const degreeToRadian = (degree) => { const factor = (Math.PI / 180); const rad = degree / factor; return rad; }; console.log(degreeToRadian(deg)); Following is the output on console − 10313.240312354817
[ { "code": null, "e": 1185, "s": 1062, "text": "The radian is the unit for measuring angles and is the standard unit of angular measure used in many areas of mathematics." }, { "code": null, "e": 1321, "s": 1185, "text": "We are required to write a JavaScript function that takes in a number that represents some degree and returns its corresponding radian." }, { "code": null, "e": 1345, "s": 1321, "text": "Following is the code −" }, { "code": null, "e": 1518, "s": 1345, "text": "const deg = 180;\nconst degreeToRadian = (degree) => {\n const factor = (Math.PI / 180);\n const rad = degree / factor;\n return rad;\n};\nconsole.log(degreeToRadian(deg));" }, { "code": null, "e": 1555, "s": 1518, "text": "Following is the output on console −" }, { "code": null, "e": 1574, "s": 1555, "text": "10313.240312354817" } ]
Showing points coordinates in a plot in Python using Matplotlib
To show points coordinate in a plot in Python, we can take the following steps − Set the figure size and adjust the padding between and around the subplots. Create lists of x and y data points. Plot x and y data points with red color and starred marker Set some axis properties. Iterate x and y to show the coordinates on the plot. import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True x = [3, 1, 2, 5] y = [5, 2, 4, 7] plt.plot(x, y, 'r*') plt.axis([0, 6, 0, 20]) for i, j in zip(x, y): plt.text(i, j+0.5, '({}, {})'.format(i, j)) plt.show()
[ { "code": null, "e": 1143, "s": 1062, "text": "To show points coordinate in a plot in Python, we can take the following steps −" }, { "code": null, "e": 1219, "s": 1143, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1256, "s": 1219, "text": "Create lists of x and y data points." }, { "code": null, "e": 1315, "s": 1256, "text": "Plot x and y data points with red color and starred marker" }, { "code": null, "e": 1341, "s": 1315, "text": "Set some axis properties." }, { "code": null, "e": 1394, "s": 1341, "text": "Iterate x and y to show the coordinates on the plot." }, { "code": null, "e": 1678, "s": 1394, "text": "import matplotlib.pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nx = [3, 1, 2, 5]\ny = [5, 2, 4, 7]\n\nplt.plot(x, y, 'r*')\nplt.axis([0, 6, 0, 20])\n\nfor i, j in zip(x, y):\n plt.text(i, j+0.5, '({}, {})'.format(i, j))\n\nplt.show()" } ]
Data Structure and Algorithms Insertion Sort
This is an in-place comparison-based sorting algorithm. Here, a sub-list is maintained which is always sorted. For example, the lower part of an array is maintained to be sorted. An element which is to be 'insert'ed in this sorted sub-list, has to find its appropriate place and then it has to be inserted there. Hence the name, insertion sort. The array is searched sequentially and unsorted items are moved and inserted into the sorted sub-list (in the same array). This algorithm is not suitable for large data sets as its average and worst case complexity are of Ο(n2), where n is the number of items. We take an unsorted array for our example. Insertion sort compares the first two elements. It finds that both 14 and 33 are already in ascending order. For now, 14 is in sorted sub-list. Insertion sort moves ahead and compares 33 with 27. And finds that 33 is not in the correct position. It swaps 33 with 27. It also checks with all the elements of sorted sub-list. Here we see that the sorted sub-list has only one element 14, and 27 is greater than 14. Hence, the sorted sub-list remains sorted after swapping. By now we have 14 and 27 in the sorted sub-list. Next, it compares 33 with 10. These values are not in a sorted order. So we swap them. However, swapping makes 27 and 10 unsorted. Hence, we swap them too. Again we find 14 and 10 in an unsorted order. We swap them again. By the end of third iteration, we have a sorted sub-list of 4 items. This process goes on until all the unsorted values are covered in a sorted sub-list. Now we shall see some programming aspects of insertion sort. Now we have a bigger picture of how this sorting technique works, so we can derive simple steps by which we can achieve insertion sort. Step 1 − If it is the first element, it is already sorted. return 1; Step 2 − Pick next element Step 3 − Compare with all elements in the sorted sub-list Step 4 − Shift all the elements in the sorted sub-list that is greater than the value to be sorted Step 5 − Insert the value Step 6 − Repeat until list is sorted procedure insertionSort( A : array of items ) int holePosition int valueToInsert for i = 1 to length(A) inclusive do: /* select value to be inserted */ valueToInsert = A[i] holePosition = i /*locate hole position for the element to be inserted */ while holePosition > 0 and A[holePosition-1] > valueToInsert do: A[holePosition] = A[holePosition-1] holePosition = holePosition -1 end while /* insert the number at hole position */ A[holePosition] = valueToInsert end for end procedure To know about insertion sort implementation in C programming language, please click here. 42 Lectures 1.5 hours Ravi Kiran 141 Lectures 13 hours Arnab Chakraborty 26 Lectures 8.5 hours Parth Panjabi 65 Lectures 6 hours Arnab Chakraborty 75 Lectures 13 hours Eduonix Learning Solutions 64 Lectures 10.5 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2925, "s": 2580, "text": "This is an in-place comparison-based sorting algorithm. Here, a sub-list is maintained which is always sorted. For example, the lower part of an array is maintained to be sorted. An element which is to be 'insert'ed in this sorted sub-list, has to find its appropriate place and then it has to be inserted there. Hence the name, insertion sort." }, { "code": null, "e": 3186, "s": 2925, "text": "The array is searched sequentially and unsorted items are moved and inserted into the sorted sub-list (in the same array). This algorithm is not suitable for large data sets as its average and worst case complexity are of Ο(n2), where n is the number of items." }, { "code": null, "e": 3229, "s": 3186, "text": "We take an unsorted array for our example." }, { "code": null, "e": 3277, "s": 3229, "text": "Insertion sort compares the first two elements." }, { "code": null, "e": 3373, "s": 3277, "text": "It finds that both 14 and 33 are already in ascending order. For now, 14 is in sorted sub-list." }, { "code": null, "e": 3425, "s": 3373, "text": "Insertion sort moves ahead and compares 33 with 27." }, { "code": null, "e": 3475, "s": 3425, "text": "And finds that 33 is not in the correct position." }, { "code": null, "e": 3700, "s": 3475, "text": "It swaps 33 with 27. It also checks with all the elements of sorted sub-list. Here we see that the sorted sub-list has only one element 14, and 27 is greater than 14. Hence, the sorted sub-list remains sorted after swapping." }, { "code": null, "e": 3779, "s": 3700, "text": "By now we have 14 and 27 in the sorted sub-list. Next, it compares 33 with 10." }, { "code": null, "e": 3819, "s": 3779, "text": "These values are not in a sorted order." }, { "code": null, "e": 3836, "s": 3819, "text": "So we swap them." }, { "code": null, "e": 3880, "s": 3836, "text": "However, swapping makes 27 and 10 unsorted." }, { "code": null, "e": 3905, "s": 3880, "text": "Hence, we swap them too." }, { "code": null, "e": 3951, "s": 3905, "text": "Again we find 14 and 10 in an unsorted order." }, { "code": null, "e": 4040, "s": 3951, "text": "We swap them again. By the end of third iteration, we have a sorted sub-list of 4 items." }, { "code": null, "e": 4186, "s": 4040, "text": "This process goes on until all the unsorted values are covered in a sorted sub-list. Now we shall see some programming aspects of insertion sort." }, { "code": null, "e": 4322, "s": 4186, "text": "Now we have a bigger picture of how this sorting technique works, so we can derive simple steps by which we can achieve insertion sort." }, { "code": null, "e": 4649, "s": 4322, "text": "Step 1 − If it is the first element, it is already sorted. return 1;\nStep 2 − Pick next element\nStep 3 − Compare with all elements in the sorted sub-list\nStep 4 − Shift all the elements in the sorted sub-list that is greater than the \n value to be sorted\nStep 5 − Insert the value\nStep 6 − Repeat until list is sorted\n" }, { "code": null, "e": 5237, "s": 4649, "text": "procedure insertionSort( A : array of items )\n int holePosition\n int valueToInsert\n\t\n for i = 1 to length(A) inclusive do:\n\t\n /* select value to be inserted */\n valueToInsert = A[i]\n holePosition = i\n \n /*locate hole position for the element to be inserted */\n\t\t\n while holePosition > 0 and A[holePosition-1] > valueToInsert do:\n A[holePosition] = A[holePosition-1]\n holePosition = holePosition -1\n end while\n\t\t\n /* insert the number at hole position */\n A[holePosition] = valueToInsert\n \n end for\n\t\nend procedure" }, { "code": null, "e": 5327, "s": 5237, "text": "To know about insertion sort implementation in C programming language, please click here." }, { "code": null, "e": 5362, "s": 5327, "text": "\n 42 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5374, "s": 5362, "text": " Ravi Kiran" }, { "code": null, "e": 5409, "s": 5374, "text": "\n 141 Lectures \n 13 hours \n" }, { "code": null, "e": 5428, "s": 5409, "text": " Arnab Chakraborty" }, { "code": null, "e": 5463, "s": 5428, "text": "\n 26 Lectures \n 8.5 hours \n" }, { "code": null, "e": 5478, "s": 5463, "text": " Parth Panjabi" }, { "code": null, "e": 5511, "s": 5478, "text": "\n 65 Lectures \n 6 hours \n" }, { "code": null, "e": 5530, "s": 5511, "text": " Arnab Chakraborty" }, { "code": null, "e": 5564, "s": 5530, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 5592, "s": 5564, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5628, "s": 5592, "text": "\n 64 Lectures \n 10.5 hours \n" }, { "code": null, "e": 5656, "s": 5628, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5663, "s": 5656, "text": " Print" }, { "code": null, "e": 5674, "s": 5663, "text": " Add Notes" } ]
Align columns to Left in Pandas - Python - GeeksforGeeks
22 Jul, 2021 Pandas library is useful for performing exploratory data analysis in Python. A pandas dataframe represents data in a tabular format. We can perform operations on the data and display it. In this article, we are going to align columns to the Left in Pandas. When we display the dataframe, we can align the data in the columns as left, right, or center. The default is right alignment as we can see in the below example. Python3 # Python code demonstrate creating# DataFrame from dict and left aligningimport pandas as pd # initialise data of lists.data = {'Name' : ['Tania', 'Ravi', 'Surbhi', 'Ganesh'], 'Articles' : [50, 30, 45, 33], 'Location' : ['Kanpur', 'Kolkata', 'Kolkata', 'Bombay']} # Create DataFramedf = pd.DataFrame(data)display(df) Output: In order to align columns to left in pandas dataframe, we use the dataframe.style.set_properties() function. Syntax: Styler.set_properties(subset=None, **kwargs) Parameters: subsetIndexSlice: A valid slice for data to limit the style application to. **kwargsdict: A dictionary of property, value pairs to be set for each cell. Returns: selfStyler Example 1: Python3 # Python code demonstrate creating# DataFrame from dict and left aligningimport pandas as pd # initialise data of lists.data = {'Name' : ['Tania', 'Ravi', 'Surbhi', 'Ganesh'], 'Articles' : [50, 30, 45, 33], 'Location' : ['Kanpur', 'Kolkata', 'Kolkata', 'Bombay']} # Create DataFramedf = pd.DataFrame(data) left_aligned_df = df.style.set_properties(**{'text-align': 'left'})display(left_aligned_df) Output: Example 2: Python3 import pandas as pd # initialise data of lists.data = [['Raghav', 'Jeeva', 'Imon', 'Sandeep'], ['Deloitte', 'Apple', 'Amazon', 'Flipkart'], [2,3,7,8]] # Create DataFramedf = pd.DataFrame(data)left_aligned_df = df.style.set_properties(**{'text-align': 'left'})display(left_aligned_df) Output: In the above example, the content of all columns are left-aligned, except the column headers. The column headers are center-aligned. Example 3: If we want the column headers aligned left, we use the set_table_styles() function. Python3 import pandas as pd # initialise data of lists.data = [['Raghav', 'Jeeva', 'Imon', 'Sandeep'], ['Deloitte', 'Apple', 'Amazon', 'Flipkart'], [2,3,7,8]] # Create DataFramedf = pd.DataFrame(data)left_aligned_df = df.style.set_properties(**{'text-align': 'left'}) left_aligned_df = left_aligned_df.set_table_styles([dict(selector = 'th', props=[('text-align', 'left')])]) display(left_aligned_df) Output: In the above example, both the column headers and the content of all the columns are left-aligned. sweetyty Picked Python Pandas-exercise 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 | 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": 25561, "s": 25533, "text": "\n22 Jul, 2021" }, { "code": null, "e": 25914, "s": 25561, "text": "Pandas library is useful for performing exploratory data analysis in Python. A pandas dataframe represents data in a tabular format. We can perform operations on the data and display it. In this article, we are going to align columns to the Left in Pandas. When we display the dataframe, we can align the data in the columns as left, right, or center. " }, { "code": null, "e": 25981, "s": 25914, "text": "The default is right alignment as we can see in the below example." }, { "code": null, "e": 25989, "s": 25981, "text": "Python3" }, { "code": "# Python code demonstrate creating# DataFrame from dict and left aligningimport pandas as pd # initialise data of lists.data = {'Name' : ['Tania', 'Ravi', 'Surbhi', 'Ganesh'], 'Articles' : [50, 30, 45, 33], 'Location' : ['Kanpur', 'Kolkata', 'Kolkata', 'Bombay']} # Create DataFramedf = pd.DataFrame(data)display(df)", "e": 26376, "s": 25989, "text": null }, { "code": null, "e": 26384, "s": 26376, "text": "Output:" }, { "code": null, "e": 26493, "s": 26384, "text": "In order to align columns to left in pandas dataframe, we use the dataframe.style.set_properties() function." }, { "code": null, "e": 26546, "s": 26493, "text": "Syntax: Styler.set_properties(subset=None, **kwargs)" }, { "code": null, "e": 26558, "s": 26546, "text": "Parameters:" }, { "code": null, "e": 26634, "s": 26558, "text": "subsetIndexSlice: A valid slice for data to limit the style application to." }, { "code": null, "e": 26711, "s": 26634, "text": "**kwargsdict: A dictionary of property, value pairs to be set for each cell." }, { "code": null, "e": 26731, "s": 26711, "text": "Returns: selfStyler" }, { "code": null, "e": 26742, "s": 26731, "text": "Example 1:" }, { "code": null, "e": 26750, "s": 26742, "text": "Python3" }, { "code": "# Python code demonstrate creating# DataFrame from dict and left aligningimport pandas as pd # initialise data of lists.data = {'Name' : ['Tania', 'Ravi', 'Surbhi', 'Ganesh'], 'Articles' : [50, 30, 45, 33], 'Location' : ['Kanpur', 'Kolkata', 'Kolkata', 'Bombay']} # Create DataFramedf = pd.DataFrame(data) left_aligned_df = df.style.set_properties(**{'text-align': 'left'})display(left_aligned_df)", "e": 27218, "s": 26750, "text": null }, { "code": null, "e": 27226, "s": 27218, "text": "Output:" }, { "code": null, "e": 27237, "s": 27226, "text": "Example 2:" }, { "code": null, "e": 27245, "s": 27237, "text": "Python3" }, { "code": "import pandas as pd # initialise data of lists.data = [['Raghav', 'Jeeva', 'Imon', 'Sandeep'], ['Deloitte', 'Apple', 'Amazon', 'Flipkart'], [2,3,7,8]] # Create DataFramedf = pd.DataFrame(data)left_aligned_df = df.style.set_properties(**{'text-align': 'left'})display(left_aligned_df)", "e": 27543, "s": 27245, "text": null }, { "code": null, "e": 27551, "s": 27543, "text": "Output:" }, { "code": null, "e": 27684, "s": 27551, "text": "In the above example, the content of all columns are left-aligned, except the column headers. The column headers are center-aligned." }, { "code": null, "e": 27695, "s": 27684, "text": "Example 3:" }, { "code": null, "e": 27779, "s": 27695, "text": "If we want the column headers aligned left, we use the set_table_styles() function." }, { "code": null, "e": 27787, "s": 27779, "text": "Python3" }, { "code": "import pandas as pd # initialise data of lists.data = [['Raghav', 'Jeeva', 'Imon', 'Sandeep'], ['Deloitte', 'Apple', 'Amazon', 'Flipkart'], [2,3,7,8]] # Create DataFramedf = pd.DataFrame(data)left_aligned_df = df.style.set_properties(**{'text-align': 'left'}) left_aligned_df = left_aligned_df.set_table_styles([dict(selector = 'th', props=[('text-align', 'left')])]) display(left_aligned_df)", "e": 28194, "s": 27787, "text": null }, { "code": null, "e": 28202, "s": 28194, "text": "Output:" }, { "code": null, "e": 28301, "s": 28202, "text": "In the above example, both the column headers and the content of all the columns are left-aligned." }, { "code": null, "e": 28310, "s": 28301, "text": "sweetyty" }, { "code": null, "e": 28317, "s": 28310, "text": "Picked" }, { "code": null, "e": 28340, "s": 28317, "text": "Python Pandas-exercise" }, { "code": null, "e": 28354, "s": 28340, "text": "Python-pandas" }, { "code": null, "e": 28361, "s": 28354, "text": "Python" }, { "code": null, "e": 28459, "s": 28361, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28491, "s": 28459, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28533, "s": 28491, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28575, "s": 28533, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28631, "s": 28575, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28658, "s": 28631, "text": "Python Classes and Objects" }, { "code": null, "e": 28697, "s": 28658, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28728, "s": 28697, "text": "Python | os.path.join() method" }, { "code": null, "e": 28757, "s": 28728, "text": "Create a directory in Python" }, { "code": null, "e": 28779, "s": 28757, "text": "Defaultdict in Python" } ]
ML | Principal Component Analysis(PCA) - GeeksforGeeks
20 Jul, 2021 Principal Component Analysis (PCA) is a statistical procedure that uses an orthogonal transformation that converts a set of correlated variables to a set of uncorrelated variables. PCA is the most widely used tool in exploratory data analysis and in machine learning for predictive models. Moreover, PCA is an unsupervised statistical technique used to examine the interrelations among a set of variables. It is also known as a general factor analysis where regression determines a line of best fit. Module Needed: import pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport seaborn as sns%matplotlib inline Code #1: # Here we are using inbuilt dataset of scikit learnfrom sklearn.datasets import load_breast_cancer # instantiatingcancer = load_breast_cancer() # creating dataframedf = pd.DataFrame(cancer['data'], columns = cancer['feature_names']) # checking head of dataframedf.head() Output: # Importing standardscalar module from sklearn.preprocessing import StandardScaler scalar = StandardScaler() # fittingscalar.fit(df)scaled_data = scalar.transform(df) # Importing PCAfrom sklearn.decomposition import PCA # Let's say, components = 2pca = PCA(n_components = 2)pca.fit(scaled_data)x_pca = pca.transform(scaled_data) x_pca.shape Output: 569, 2 # giving a larger plotplt.figure(figsize =(8, 6)) plt.scatter(x_pca[:, 0], x_pca[:, 1], c = cancer['target'], cmap ='plasma') # labeling x and y axesplt.xlabel('First Principal Component')plt.ylabel('Second Principal Component') Output: # componentspca.components_ Output: df_comp = pd.DataFrame(pca.components_, columns = cancer['feature_names']) plt.figure(figsize =(14, 6)) # plotting heatmapsns.heatmap(df_comp) Output: Advanced Computer Subject Machine Learning Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Decision Tree Decision Tree Introduction with example System Design Tutorial Python | Decision tree implementation Copying Files to and from Docker Containers Decision Tree Agents in Artificial Intelligence Activation functions in Neural Networks Introduction to Recurrent Neural Network Decision Tree Introduction with example
[ { "code": null, "e": 25609, "s": 25581, "text": "\n20 Jul, 2021" }, { "code": null, "e": 26109, "s": 25609, "text": "Principal Component Analysis (PCA) is a statistical procedure that uses an orthogonal transformation that converts a set of correlated variables to a set of uncorrelated variables. PCA is the most widely used tool in exploratory data analysis and in machine learning for predictive models. Moreover, PCA is an unsupervised statistical technique used to examine the interrelations among a set of variables. It is also known as a general factor analysis where regression determines a line of best fit." }, { "code": null, "e": 26124, "s": 26109, "text": "Module Needed:" }, { "code": "import pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport seaborn as sns%matplotlib inline", "e": 26232, "s": 26124, "text": null }, { "code": null, "e": 26241, "s": 26232, "text": "Code #1:" }, { "code": "# Here we are using inbuilt dataset of scikit learnfrom sklearn.datasets import load_breast_cancer # instantiatingcancer = load_breast_cancer() # creating dataframedf = pd.DataFrame(cancer['data'], columns = cancer['feature_names']) # checking head of dataframedf.head()", "e": 26515, "s": 26241, "text": null }, { "code": null, "e": 26523, "s": 26515, "text": "Output:" }, { "code": "# Importing standardscalar module from sklearn.preprocessing import StandardScaler scalar = StandardScaler() # fittingscalar.fit(df)scaled_data = scalar.transform(df) # Importing PCAfrom sklearn.decomposition import PCA # Let's say, components = 2pca = PCA(n_components = 2)pca.fit(scaled_data)x_pca = pca.transform(scaled_data) x_pca.shape", "e": 26869, "s": 26523, "text": null }, { "code": null, "e": 26877, "s": 26869, "text": "Output:" }, { "code": null, "e": 26884, "s": 26877, "text": "569, 2" }, { "code": "# giving a larger plotplt.figure(figsize =(8, 6)) plt.scatter(x_pca[:, 0], x_pca[:, 1], c = cancer['target'], cmap ='plasma') # labeling x and y axesplt.xlabel('First Principal Component')plt.ylabel('Second Principal Component')", "e": 27115, "s": 26884, "text": null }, { "code": null, "e": 27123, "s": 27115, "text": "Output:" }, { "code": "# componentspca.components_", "e": 27151, "s": 27123, "text": null }, { "code": null, "e": 27159, "s": 27151, "text": "Output:" }, { "code": "df_comp = pd.DataFrame(pca.components_, columns = cancer['feature_names']) plt.figure(figsize =(14, 6)) # plotting heatmapsns.heatmap(df_comp)", "e": 27304, "s": 27159, "text": null }, { "code": null, "e": 27312, "s": 27304, "text": "Output:" }, { "code": null, "e": 27338, "s": 27312, "text": "Advanced Computer Subject" }, { "code": null, "e": 27355, "s": 27338, "text": "Machine Learning" }, { "code": null, "e": 27372, "s": 27355, "text": "Machine Learning" }, { "code": null, "e": 27470, "s": 27372, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27484, "s": 27470, "text": "Decision Tree" }, { "code": null, "e": 27524, "s": 27484, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 27547, "s": 27524, "text": "System Design Tutorial" }, { "code": null, "e": 27585, "s": 27547, "text": "Python | Decision tree implementation" }, { "code": null, "e": 27629, "s": 27585, "text": "Copying Files to and from Docker Containers" }, { "code": null, "e": 27643, "s": 27629, "text": "Decision Tree" }, { "code": null, "e": 27677, "s": 27643, "text": "Agents in Artificial Intelligence" }, { "code": null, "e": 27717, "s": 27677, "text": "Activation functions in Neural Networks" }, { "code": null, "e": 27758, "s": 27717, "text": "Introduction to Recurrent Neural Network" } ]
Count numbers from 1 to n that have 4 as a digit - GeeksforGeeks
02 Feb, 2022 Given a number n, find count of all numbers from 1 to n that have 4 as a digit.Examples : Input: n = 5 Output: 1 Only 4 has '4' as digit Input: n = 50 Output: 14 Input: n = 328 Output: 60 This problem is mainly a variation of previous article on Compute sum of digits in all numbers from 1 to n. Naive Solution: A naive solution is to go through every number x from 1 to n, and check if x has 4. To check if x has or not, we can traverse all digits of x. Below is the implementation of above idea : C++ Java Python3 C# PHP Javascript // A Simple C++ program to compute sum of digits in numbers from 1 to n#include<iostream>using namespace std; bool has4(int x); // Returns sum of all digits in numbers from 1 to nint countNumbersWith4(int n){ int result = 0; // initialize result // One by one compute sum of digits in every number from // 1 to n for (int x=1; x<=n; x++) result += has4(x)? 1 : 0; return result;} // A utility function to compute sum of digits in a// given number xbool has4(int x){ while (x != 0) { if (x%10 == 4) return true; x = x /10; } return false;} // Driver Programint main(){ int n = 328; cout << "Count of numbers from 1 to " << n << " that have 4 as a a digit is " << countNumbersWith4(n) << endl; return 0;} // Java program to compute sum of// digits in numbers from 1 to nimport java.io.*; class GFG { // Returns sum of all digits // in numbers from 1 to n static int countNumbersWith4(int n) { // initialize result int result = 0; // One by one compute sum of digits // in every number from 1 to n for (int x=1; x<=n; x++) result += has4(x)? 1 : 0; return result; } // A utility function to compute sum // of digits in a given number x static boolean has4(int x) { while (x != 0) { if (x%10 == 4) return true; x = x /10; } return false; } // Driver Program public static void main(String args[]) { int n = 328; System.out.println("Count of numbers from 1 to " + " that have 4 as a a digit is " + countNumbersWith4(n)) ; }} // This code is contributed by Nikita Tiwari. # A Simple Python 3 program to compute# sum of digits in numbers from 1 to n # Returns sum of all digits in numbers from 1 to ndef countNumbersWith4(n) : result = 0 # initialize result # One by one compute sum of digits # in every number from 1 to n for x in range(1, n + 1) : if(has4(x) == True) : result = result + 1 return result # A utility function to compute sum # of digits in a given number xdef has4(x) : while (x != 0) : if (x%10 == 4) : return True x = x //10 return False # Driver Programn = 328print ("Count of numbers from 1 to ", n, " that have 4 as a a digit is ", countNumbersWith4(n)) # This code is contributed by Nikita Tiwari. // C# program to compute sum of// digits in numbers from 1 to nusing System; public class GFG{ // Returns sum of all digits // in numbers from 1 to n static int countNumbersWith4(int n) { // initialize result int result = 0; // One by one compute sum of digits // in every number from 1 to n for (int x = 1; x <= n; x++) result += has4(x) ? 1 : 0; return result; } // A utility function to compute sum // of digits in a given number x static bool has4(int x) { while (x != 0) { if (x % 10 == 4) return true; x = x / 10; } return false; } // Driver Code public static void Main() { int n = 328; Console.WriteLine("Count of numbers from 1 to " + " that have 4 as a a digit is " + countNumbersWith4(n)) ; }} // This code is contributed by Sam007 <?php// PHP program to compute sum of// digits in numbers from 1 to n // Returns sum of all digits// in numbers from 1 to nfunction countNumbersWith4($n){ $result = 0; // initialize result // One by one compute sum of // digits in every number from 1 to n for ($x = 1; $x <= $n; $x++) $result += has4($x) ? 1 : 0; return $result;} // A utility function to compute// sum of digits in a given number xfunction has4($x){ while ($x != 0) { if ($x % 10 == 4) return true; $x = intval($x / 10); } return false;} // Driver Code$n = 328;echo "Count of numbers from 1 to " . $n . " that have 4 as a a digit is " . countNumbersWith4($n); // This code is contributed by Sam007?> <script> // Javascript program to compute sum of// digits in numbers from 1 to n // Returns sum of all digits// in numbers from 1 to nfunction countNumbersWith4(n){ // Initialize result let result = 0; // One by one compute sum of digits // in every number from 1 to n for(let x = 1; x <= n; x++) result += has4(x) ? 1 : 0; return result;} // A utility function to compute sum// of digits in a given number xfunction has4(x){ while (x != 0) { if (x % 10 == 4) return true; x = Math.floor(x / 10); } return false;} // Driver codelet n = 328;document.write("Count of numbers from 1 to " + n + " that have 4 as a a digit is " + countNumbersWith4(n)) ; // This code is contributed by avanitrachhadiya2155 </script> Output : Count of numbers from 1 to 328 that have 4 as a a digit is 60 An Efficient Solution using DP: We can make above approach more efficient through DP (Dynamic Programming) using memoization technique. We can store the presence of 4 in the previous visited integers so that whenever we need to check those integers we don’t need to check whether it contains 4 or not by checking each digit again. To check we can simply check from the DP array. Below is the code for the same: C++ Java #include <iostream>using namespace std; bool contains(int i); int countNumberswith4(int N){ int count = 0; bool dp[N + 1] = { 0 }; // boolean dp array to store whether // the number contains digit '4' or not for (int i = 1; i <= N; i++) { if (dp[i]) { // if dp[i] is true that means // that number conatins digit '4' count++; continue; // if it contains then no need to // check again hence continue } if (contains(i)) { // check if i contains digit '4' // or not count++; dp[i] = true; // if it contains then mark dp[i] as // true so that it can used later } } return count;} bool contains(int i) // boolean function to check{ // whether i contains digit '4' or not while (i > 0) { if (i % 10 == 4) return true; i /= 10; } return false;} int main(){ int n = 278; cout << "Count of numbers from 1 to " << n << " that have 4 as a a digit is " << countNumberswith4(n) << endl; return 0;} // This code is contributed by Anurag Mishra /*package whatever //do not write package name here */ import java.io.*; class GFG { static int countNumberswith4(int N) { int count = 0; boolean dp[] = new boolean [N + 1]; // boolean dp array to store whether // the number contains digit '4' or not for (int i = 1; i <= N; i++) { if (dp[i]) { // if dp[i] is true that means // that number conatins digit '4' count++; continue; // if it contains then no need to // check again hence continue } if (contains(i)) { // check if i contains digit // '4' or not count++; dp[i] = true; // if it contains then mark // dp[i] as true so that it // can used later } } return count; } static boolean contains(int i) // boolean function to check { // whether i contains digit '4' or not while (i > 0) { if (i % 10 == 4) return true; i /= 10; } return false; } public static void main(String[] args) { int n = 278; System.out.println("Count of numbers from 1 to " + n + " that have 4 as a a digit is " + countNumberswith4(n)); }} // This code is contributed by Anurag Mishra Count of numbers from 1 to 278 that have 4 as a a digit is 55 Another Efficient Solution: Above first solution is a naive solution. We can do it more efficiently by finding a pattern. Let us take few examples. Count of numbers from 0 to 9 = 1 Count of numbers from 0 to 99 = 1*9 + 10 = 19 Count of numbers from 0 to 999 = 19*9 + 100 = 271 In general, we can write count(10d) = 9 * count(10d - 1) + 10d - 1 In below implementation, the above formula is implemented using dynamic programming as there are overlapping subproblems.The above formula is one core step of the idea. Below is complete algorithm. 1) Find number of digits minus one in n. Let this value be 'd'. For 328, d is 2. 2) Compute some of digits in numbers from 1 to 10d - 1. Let this sum be w. For 328, we compute sum of digits from 1 to 99 using above formula. 3) Find Most significant digit (msd) in n. For 328, msd is 3. 4.a) If MSD is 4. For example if n = 428, then count of numbers is sum of following. 1) Count of numbers from 1 to 399 2) Count of numbers from 400 to 428 which is 29. 4.b) IF MSD > 4. For example if n is 728, then count of numbers is sum of following. 1) Count of numbers from 1 to 399 and count of numbers from 500 to 699, i.e., "a[2] * 6" 2) Count of numbers from 400 to 499, i.e. 100 3) Count of numbers from 700 to 728, recur for 28 4.c) IF MSD < 4. For example if n is 328, then count of numbers is sum of following. 1) Count of numbers from 1 to 299 a 2) Count of numbers from 300 to 328, recur for 28 Below is implementation of above algorithm. C++ Java Python3 C# PHP Javascript // C++ program to count numbers having 4 as a digit#include<bits/stdc++.h>using namespace std; // Function to count numbers from 1 to n that have// 4 as a digitint countNumbersWith4(int n){ // Base case if (n < 4) return 0; // d = number of digits minus one in n. For 328, d is 2 int d = log10(n); // computing count of numbers from 1 to 10^d-1, // d=0 a[0] = 0; // d=1 a[1] = count of numbers from 0 to 9 = 1 // d=2 a[2] = count of numbers from 0 to 99 = a[1]*9 + 10 = 19 // d=3 a[3] = count of numbers from 0 to 999 = a[2]*19 + 100 = 171 int *a = new int[d+1]; a[0] = 0, a[1] = 1; for (int i=2; i<=d; i++) a[i] = a[i-1]*9 + ceil(pow(10,i-1)); // Computing 10^d int p = ceil(pow(10, d)); // Most significant digit (msd) of n, // For 328, msd is 3 which can be obtained using 328/100 int msd = n/p; // If MSD is 4. For example if n = 428, then count of // numbers is sum of following. // 1) Count of numbers from 1 to 399 // 2) Count of numbers from 400 to 428 which is 29. if (msd == 4) return (msd)*a[d] + (n%p) + 1; // IF MSD > 4. For example if n is 728, then count of // numbers is sum of following. // 1) Count of numbers from 1 to 399 and count of numbers // from 500 to 699, i.e., "a[2] * 6" // 2) Count of numbers from 400 to 499, i.e. 100 // 3) Count of numbers from 700 to 728, recur for 28 if (msd > 4) return (msd-1)*a[d] + p + countNumbersWith4(n%p); // IF MSD < 4. For example if n is 328, then count of // numbers is sum of following. // 1) Count of numbers from 1 to 299 a // 2) Count of numbers from 300 to 328, recur for 28 return (msd)*a[d] + countNumbersWith4(n%p);} // Driver Programint main(){ int n = 328; cout << "Count of numbers from 1 to " << n << " that have 4 as a a digit is " << countNumbersWith4(n) << endl; return 0;} // Java program to count numbers having 4 as a digitclass GFG{ // Function to count numbers from// 1 to n that have 4 as a digitstatic int countNumbersWith4(int n){ // Base case if (n < 4) return 0; // d = number of digits minus // one in n. For 328, d is 2 int d = (int)Math.log10(n); // computing count of numbers from 1 to 10^d-1, // d=0 a[0] = 0; // d=1 a[1] = count of numbers from // 0 to 9 = 1 // d=2 a[2] = count of numbers from // 0 to 99 = a[1]*9 + 10 = 19 // d=3 a[3] = count of numbers from // 0 to 999 = a[2]*19 + 100 = 171 int[] a = new int[d + 2]; a[0] = 0; a[1] = 1; for (int i = 2; i <= d; i++) a[i] = a[i - 1] * 9 + (int)Math.ceil(Math.pow(10, i - 1)); // Computing 10^d int p = (int)Math.ceil(Math.pow(10, d)); // Most significant digit (msd) of n, // For 328, msd is 3 which can be obtained using 328/100 int msd = n / p; // If MSD is 4. For example if n = 428, then count of // numbers is sum of following. // 1) Count of numbers from 1 to 399 // 2) Count of numbers from 400 to 428 which is 29. if (msd == 4) return (msd) * a[d] + (n % p) + 1; // IF MSD > 4. For example if n // is 728, then count of numbers // is sum of following. // 1) Count of numbers from 1 to // 399 and count of numbers from // 500 to 699, i.e., "a[2] * 6" // 2) Count of numbers from 400 // to 499, i.e. 100 // 3) Count of numbers from 700 to // 728, recur for 28 if (msd > 4) return (msd - 1) * a[d] + p + countNumbersWith4(n % p); // IF MSD < 4. For example if n is 328, then count of // numbers is sum of following. // 1) Count of numbers from 1 to 299 a // 2) Count of numbers from 300 to 328, recur for 28 return (msd) * a[d] + countNumbersWith4(n % p);} // Driver codepublic static void main (String[] args){ int n = 328; System.out.println("Count of numbers from 1 to "+ n + " that have 4 as a digit is " + countNumbersWith4(n));}} // This code is contributed by chandan_jnu # Python3 program to count numbers having 4 as a digitimport math as mt # Function to count numbers from 1 to n# that have 4 as a digitdef countNumbersWith4(n): # Base case if (n < 4): return 0 # d = number of digits minus one in n. # For 328, d is 2 d = int(mt.log10(n)) # computing count of numbers from 1 to 10^d-1, # d=0 a[0] = 0 # d=1 a[1] = count of numbers from 0 to 9 = 1 # d=2 a[2] = count of numbers from # 0 to 99 = a[1]*9 + 10 = 19 # d=3 a[3] = count of numbers from # 0 to 999 = a[2]*19 + 100 = 171 a = [1 for i in range(d + 1)] a[0] = 0 if len(a) > 1: a[1] = 1 for i in range(2, d + 1): a[i] = a[i - 1] * 9 + mt.ceil(pow(10, i - 1)) # Computing 10^d p = mt.ceil(pow(10, d)) # Most significant digit (msd) of n, # For 328, msd is 3 which can be # obtained using 328/100 msd = n // p # If MSD is 4. For example if n = 428, # then count of numbers is sum of following. # 1) Count of numbers from 1 to 399 # 2) Count of numbers from 400 to 428 which is 29. if (msd == 4): return (msd) * a[d] + (n % p) + 1 # IF MSD > 4. For example if n is 728, # then count of numbers is sum of following. # 1) Count of numbers from 1 to 399 and count # of numbers from 500 to 699, i.e., "a[2] * 6" # 2) Count of numbers from 400 to 499, i.e. 100 # 3) Count of numbers from 700 to 728, recur for 28 if (msd > 4): return ((msd - 1) * a[d] + p + countNumbersWith4(n % p)) # IF MSD < 4. For example if n is 328, # then count of numbers is sum of following. # 1) Count of numbers from 1 to 299 a # 2) Count of numbers from 300 to 328, recur for 28 return (msd) * a[d] + countNumbersWith4(n % p) # Driver Coden = 328print("Count of numbers from 1 to", n, "that have 4 as a digit is", countNumbersWith4(n)) # This code is contributed by mohit kumar 29 // C# program to count numbers having 4 as a digitusing System; class GFG{// Function to count numbers from// 1 to n that have 4 as a digitstatic int countNumbersWith4(int n){ // Base case if (n < 4) return 0; // d = number of digits minus // one in n. For 328, d is 2 int d = (int)Math.Log10(n); // computing count of numbers from 1 to 10^d-1, // d=0 a[0] = 0; // d=1 a[1] = count of numbers from // 0 to 9 = 1 // d=2 a[2] = count of numbers from // 0 to 99 = a[1]*9 + 10 = 19 // d=3 a[3] = count of numbers from // 0 to 999 = a[2]*19 + 100 = 171 int[] a = new int[d+2]; a[0] = 0; a[1] = 1; for (int i = 2; i <= d; i++) a[i] = a[i - 1] * 9 + (int)Math.Ceiling(Math.Pow(10, i - 1)); // Computing 10^d int p = (int)Math.Ceiling(Math.Pow(10, d)); // Most significant digit (msd) of n, // For 328, msd is 3 which can be obtained using 328/100 int msd = n / p; // If MSD is 4. For example if n = 428, then count of // numbers is sum of following. // 1) Count of numbers from 1 to 399 // 2) Count of numbers from 400 to 428 which is 29. if (msd == 4) return (msd) * a[d] + (n % p) + 1; // IF MSD > 4. For example if n is 728, then count of // numbers is sum of following. // 1) Count of numbers from 1 to 399 and count of numbers // from 500 to 699, i.e., "a[2] * 6" // 2) Count of numbers from 400 to 499, i.e. 100 // 3) Count of numbers from 700 to 728, recur for 28 if (msd > 4) return (msd - 1) * a[d] + p + countNumbersWith4(n % p); // IF MSD < 4. For example if n is 328, then count of // numbers is sum of following. // 1) Count of numbers from 1 to 299 a // 2) Count of numbers from 300 to 328, recur for 28 return (msd) * a[d] + countNumbersWith4(n % p);} // Driver codestatic void Main(){ int n = 328; Console.WriteLine("Count of numbers from 1 to "+ n + " that have 4 as a digit is " + countNumbersWith4(n));}} // This code is contributed by chandan_jnu <?php// PHP program to count numbers having// 4 as a digit // Function to count numbers from 1 to n// that have 4 as a digitfunction countNumbersWith4($n){ // Base case if ($n < 4) return 0; // d = number of digits minus one in n. // For 328, d is 2 $d = (int)log10($n); // computing count of numbers from 1 to 10^d-1, // d=0 a[0] = 0; // d=1 a[1] = count of numbers from 0 to 9 is 1 // d=2 a[2] = count of numbers from 0 to 99 is // a[1]*9 + 10 = 19 // d=3 a[3] = count of numbers from 0 to 999 is // a[2]*19 + 100 = 171 $a = array_fill(0, $d + 1, NULL); $a[0] = 0; $a[1] = 1; for ($i = 2; $i <= $d; $i++) $a[$i] = $a[$i - 1] * 9 + ceil(pow(10, $i - 1)); // Computing 10^d $p = ceil(pow(10, $d)); // Most significant digit (msd) of n, // For 328, msd is 3 which can be // obtained using 328/100 $msd = intval($n / $p); // If MSD is 4. For example if n = 428, // then count of numbers is sum of following. // 1) Count of numbers from 1 to 399 // 2) Count of numbers from 400 to 428 which is 29. if ($msd == 4) return ($msd) * $a[$d] + ($n % $p) + 1; // IF MSD > 4. For example if n is 728, // then count of numbers is sum of following. // 1) Count of numbers from 1 to 399 and // count of numbers from 500 to 699, i.e., "a[2] * 6" // 2) Count of numbers from 400 to 499, i.e. 100 // 3) Count of numbers from 700 to 728, recur for 28 if ($msd > 4) return ($msd - 1) * $a[$d] + $p + countNumbersWith4($n % $p); // IF MSD < 4. For example if n is 328, then // count of numbers is sum of following. // 1) Count of numbers from 1 to 299 a // 2) Count of numbers from 300 to 328, recur for 28 return ($msd) * $a[$d] + countNumbersWith4($n % $p);} // Driver Code$n = 328;echo "Count of numbers from 1 to " . $n . " that have 4 as a digit is " . countNumbersWith4($n) . "\n"; // This code is contributed by ita_c?> <script> // Javascript program to count numbers having 4 as a digit // Function to count numbers from // 1 to n that have 4 as a digit function countNumbersWith4(n) { // Base case if (n < 4) return 0; // d = number of digits minus // one in n. For 328, d is 2 let d = Math.floor(Math.log10(n)); // computing count of numbers from 1 to 10^d-1, // d=0 a[0] = 0; // d=1 a[1] = count of numbers from // 0 to 9 = 1 // d=2 a[2] = count of numbers from // 0 to 99 = a[1]*9 + 10 = 19 // d=3 a[3] = count of numbers from // 0 to 999 = a[2]*19 + 100 = 171 let a = new Array(d + 2); for(let i=0;i<d+2;i++) { a[i]=0; } a[0] = 0; a[1] = 1; for (let i = 2; i <= d; i++) a[i] = a[i - 1] * 9 + Math.floor(Math.ceil(Math.pow(10, i - 1))); // Computing 10^d let p = Math.floor(Math.ceil(Math.pow(10, d))); // Most significant digit (msd) of n, // For 328, msd is 3 which can be obtained using 328/100 let msd = Math.floor(n / p); // If MSD is 4. For example if n = 428, then count of // numbers is sum of following. // 1) Count of numbers from 1 to 399 // 2) Count of numbers from 400 to 428 which is 29. if (msd == 4) return (msd) * a[d] + (n % p) + 1; // IF MSD > 4. For example if n // is 728, then count of numbers // is sum of following. // 1) Count of numbers from 1 to // 399 and count of numbers from // 500 to 699, i.e., "a[2] * 6" // 2) Count of numbers from 400 // to 499, i.e. 100 // 3) Count of numbers from 700 to // 728, recur for 28 if (msd > 4) return (msd - 1) * a[d] + p + countNumbersWith4(n % p); // IF MSD < 4. For example if n is 328, then count of // numbers is sum of following. // 1) Count of numbers from 1 to 299 a // 2) Count of numbers from 300 to 328, recur for 28 return (msd) * a[d] + countNumbersWith4(n % p); } // Driver code let n = 328; document.write("Count of numbers from 1 to "+ n + " that have 4 as a digit is " + countNumbersWith4(n)); // This code is contributed by rag2127</script> Output: Count of numbers from 1 to 328 that have 4 as a a digit is 60 This article is contributed by Shivam. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Sam007 mohit kumar 29 ukasp Chandan_Kumar avanitrachhadiya2155 rag2127 anuragayu Drishti-Soft Morgan Stanley Arrays Dynamic Programming Mathematical Morgan Stanley Drishti-Soft Arrays Dynamic Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Chocolate Distribution Problem Window Sliding Technique Reversal algorithm for array rotation Next Greater Element Find duplicates in O(n) time and O(1) extra space | Set 1 0-1 Knapsack Problem | DP-10 Program for Fibonacci numbers Longest Common Subsequence | DP-4 Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16
[ { "code": null, "e": 26065, "s": 26037, "text": "\n02 Feb, 2022" }, { "code": null, "e": 26156, "s": 26065, "text": "Given a number n, find count of all numbers from 1 to n that have 4 as a digit.Examples : " }, { "code": null, "e": 26265, "s": 26156, "text": "Input: n = 5\nOutput: 1\nOnly 4 has '4' as digit\n\nInput: n = 50\nOutput: 14\n\nInput: n = 328\nOutput: 60" }, { "code": null, "e": 26373, "s": 26265, "text": "This problem is mainly a variation of previous article on Compute sum of digits in all numbers from 1 to n." }, { "code": null, "e": 26577, "s": 26373, "text": "Naive Solution: A naive solution is to go through every number x from 1 to n, and check if x has 4. To check if x has or not, we can traverse all digits of x. Below is the implementation of above idea : " }, { "code": null, "e": 26581, "s": 26577, "text": "C++" }, { "code": null, "e": 26586, "s": 26581, "text": "Java" }, { "code": null, "e": 26594, "s": 26586, "text": "Python3" }, { "code": null, "e": 26597, "s": 26594, "text": "C#" }, { "code": null, "e": 26601, "s": 26597, "text": "PHP" }, { "code": null, "e": 26612, "s": 26601, "text": "Javascript" }, { "code": "// A Simple C++ program to compute sum of digits in numbers from 1 to n#include<iostream>using namespace std; bool has4(int x); // Returns sum of all digits in numbers from 1 to nint countNumbersWith4(int n){ int result = 0; // initialize result // One by one compute sum of digits in every number from // 1 to n for (int x=1; x<=n; x++) result += has4(x)? 1 : 0; return result;} // A utility function to compute sum of digits in a// given number xbool has4(int x){ while (x != 0) { if (x%10 == 4) return true; x = x /10; } return false;} // Driver Programint main(){ int n = 328; cout << \"Count of numbers from 1 to \" << n << \" that have 4 as a a digit is \" << countNumbersWith4(n) << endl; return 0;}", "e": 27397, "s": 26612, "text": null }, { "code": "// Java program to compute sum of// digits in numbers from 1 to nimport java.io.*; class GFG { // Returns sum of all digits // in numbers from 1 to n static int countNumbersWith4(int n) { // initialize result int result = 0; // One by one compute sum of digits // in every number from 1 to n for (int x=1; x<=n; x++) result += has4(x)? 1 : 0; return result; } // A utility function to compute sum // of digits in a given number x static boolean has4(int x) { while (x != 0) { if (x%10 == 4) return true; x = x /10; } return false; } // Driver Program public static void main(String args[]) { int n = 328; System.out.println(\"Count of numbers from 1 to \" + \" that have 4 as a a digit is \" + countNumbersWith4(n)) ; }} // This code is contributed by Nikita Tiwari.", "e": 28411, "s": 27397, "text": null }, { "code": "# A Simple Python 3 program to compute# sum of digits in numbers from 1 to n # Returns sum of all digits in numbers from 1 to ndef countNumbersWith4(n) : result = 0 # initialize result # One by one compute sum of digits # in every number from 1 to n for x in range(1, n + 1) : if(has4(x) == True) : result = result + 1 return result # A utility function to compute sum # of digits in a given number xdef has4(x) : while (x != 0) : if (x%10 == 4) : return True x = x //10 return False # Driver Programn = 328print (\"Count of numbers from 1 to \", n, \" that have 4 as a a digit is \", countNumbersWith4(n)) # This code is contributed by Nikita Tiwari.", "e": 29161, "s": 28411, "text": null }, { "code": "// C# program to compute sum of// digits in numbers from 1 to nusing System; public class GFG{ // Returns sum of all digits // in numbers from 1 to n static int countNumbersWith4(int n) { // initialize result int result = 0; // One by one compute sum of digits // in every number from 1 to n for (int x = 1; x <= n; x++) result += has4(x) ? 1 : 0; return result; } // A utility function to compute sum // of digits in a given number x static bool has4(int x) { while (x != 0) { if (x % 10 == 4) return true; x = x / 10; } return false; } // Driver Code public static void Main() { int n = 328; Console.WriteLine(\"Count of numbers from 1 to \" + \" that have 4 as a a digit is \" + countNumbersWith4(n)) ; }} // This code is contributed by Sam007", "e": 30154, "s": 29161, "text": null }, { "code": "<?php// PHP program to compute sum of// digits in numbers from 1 to n // Returns sum of all digits// in numbers from 1 to nfunction countNumbersWith4($n){ $result = 0; // initialize result // One by one compute sum of // digits in every number from 1 to n for ($x = 1; $x <= $n; $x++) $result += has4($x) ? 1 : 0; return $result;} // A utility function to compute// sum of digits in a given number xfunction has4($x){ while ($x != 0) { if ($x % 10 == 4) return true; $x = intval($x / 10); } return false;} // Driver Code$n = 328;echo \"Count of numbers from 1 to \" . $n . \" that have 4 as a a digit is \" . countNumbersWith4($n); // This code is contributed by Sam007?>", "e": 30908, "s": 30154, "text": null }, { "code": "<script> // Javascript program to compute sum of// digits in numbers from 1 to n // Returns sum of all digits// in numbers from 1 to nfunction countNumbersWith4(n){ // Initialize result let result = 0; // One by one compute sum of digits // in every number from 1 to n for(let x = 1; x <= n; x++) result += has4(x) ? 1 : 0; return result;} // A utility function to compute sum// of digits in a given number xfunction has4(x){ while (x != 0) { if (x % 10 == 4) return true; x = Math.floor(x / 10); } return false;} // Driver codelet n = 328;document.write(\"Count of numbers from 1 to \" + n + \" that have 4 as a a digit is \" + countNumbersWith4(n)) ; // This code is contributed by avanitrachhadiya2155 </script>", "e": 31737, "s": 30908, "text": null }, { "code": null, "e": 31747, "s": 31737, "text": "Output : " }, { "code": null, "e": 31809, "s": 31747, "text": "Count of numbers from 1 to 328 that have 4 as a a digit is 60" }, { "code": null, "e": 31841, "s": 31809, "text": "An Efficient Solution using DP:" }, { "code": null, "e": 32189, "s": 31841, "text": "We can make above approach more efficient through DP (Dynamic Programming) using memoization technique. We can store the presence of 4 in the previous visited integers so that whenever we need to check those integers we don’t need to check whether it contains 4 or not by checking each digit again. To check we can simply check from the DP array. " }, { "code": null, "e": 32221, "s": 32189, "text": "Below is the code for the same:" }, { "code": null, "e": 32225, "s": 32221, "text": "C++" }, { "code": null, "e": 32230, "s": 32225, "text": "Java" }, { "code": "#include <iostream>using namespace std; bool contains(int i); int countNumberswith4(int N){ int count = 0; bool dp[N + 1] = { 0 }; // boolean dp array to store whether // the number contains digit '4' or not for (int i = 1; i <= N; i++) { if (dp[i]) { // if dp[i] is true that means // that number conatins digit '4' count++; continue; // if it contains then no need to // check again hence continue } if (contains(i)) { // check if i contains digit '4' // or not count++; dp[i] = true; // if it contains then mark dp[i] as // true so that it can used later } } return count;} bool contains(int i) // boolean function to check{ // whether i contains digit '4' or not while (i > 0) { if (i % 10 == 4) return true; i /= 10; } return false;} int main(){ int n = 278; cout << \"Count of numbers from 1 to \" << n << \" that have 4 as a a digit is \" << countNumberswith4(n) << endl; return 0;} // This code is contributed by Anurag Mishra", "e": 33441, "s": 32230, "text": null }, { "code": "/*package whatever //do not write package name here */ import java.io.*; class GFG { static int countNumberswith4(int N) { int count = 0; boolean dp[] = new boolean [N + 1]; // boolean dp array to store whether // the number contains digit '4' or not for (int i = 1; i <= N; i++) { if (dp[i]) { // if dp[i] is true that means // that number conatins digit '4' count++; continue; // if it contains then no need to // check again hence continue } if (contains(i)) { // check if i contains digit // '4' or not count++; dp[i] = true; // if it contains then mark // dp[i] as true so that it // can used later } } return count; } static boolean contains(int i) // boolean function to check { // whether i contains digit '4' or not while (i > 0) { if (i % 10 == 4) return true; i /= 10; } return false; } public static void main(String[] args) { int n = 278; System.out.println(\"Count of numbers from 1 to \" + n + \" that have 4 as a a digit is \" + countNumberswith4(n)); }} // This code is contributed by Anurag Mishra", "e": 34922, "s": 33441, "text": null }, { "code": null, "e": 34984, "s": 34922, "text": "Count of numbers from 1 to 278 that have 4 as a a digit is 55" }, { "code": null, "e": 35013, "s": 34984, "text": "Another Efficient Solution: " }, { "code": null, "e": 35134, "s": 35013, "text": "Above first solution is a naive solution. We can do it more efficiently by finding a pattern. Let us take few examples. " }, { "code": null, "e": 35341, "s": 35134, "text": "Count of numbers from 0 to 9 = 1\nCount of numbers from 0 to 99 = 1*9 + 10 = 19\nCount of numbers from 0 to 999 = 19*9 + 100 = 271 \n\nIn general, we can write \n count(10d) = 9 * count(10d - 1) + 10d - 1" }, { "code": null, "e": 35540, "s": 35341, "text": "In below implementation, the above formula is implemented using dynamic programming as there are overlapping subproblems.The above formula is one core step of the idea. Below is complete algorithm. " }, { "code": null, "e": 36512, "s": 35540, "text": "1) Find number of digits minus one in n. Let this value be 'd'. \n For 328, d is 2.\n\n2) Compute some of digits in numbers from 1 to 10d - 1. \n Let this sum be w. For 328, we compute sum of digits from 1 to \n 99 using above formula.\n\n3) Find Most significant digit (msd) in n. For 328, msd is 3.\n\n4.a) If MSD is 4. For example if n = 428, then count of\n numbers is sum of following.\n 1) Count of numbers from 1 to 399\n 2) Count of numbers from 400 to 428 which is 29.\n\n4.b) IF MSD > 4. For example if n is 728, then count of\n numbers is sum of following.\n 1) Count of numbers from 1 to 399 and count of numbers\n from 500 to 699, i.e., \"a[2] * 6\"\n 2) Count of numbers from 400 to 499, i.e. 100\n 3) Count of numbers from 700 to 728, recur for 28\n4.c) IF MSD < 4. For example if n is 328, then count of\n numbers is sum of following.\n 1) Count of numbers from 1 to 299 a\n 2) Count of numbers from 300 to 328, recur for 28 " }, { "code": null, "e": 36556, "s": 36512, "text": "Below is implementation of above algorithm." }, { "code": null, "e": 36560, "s": 36556, "text": "C++" }, { "code": null, "e": 36565, "s": 36560, "text": "Java" }, { "code": null, "e": 36573, "s": 36565, "text": "Python3" }, { "code": null, "e": 36576, "s": 36573, "text": "C#" }, { "code": null, "e": 36580, "s": 36576, "text": "PHP" }, { "code": null, "e": 36591, "s": 36580, "text": "Javascript" }, { "code": "// C++ program to count numbers having 4 as a digit#include<bits/stdc++.h>using namespace std; // Function to count numbers from 1 to n that have// 4 as a digitint countNumbersWith4(int n){ // Base case if (n < 4) return 0; // d = number of digits minus one in n. For 328, d is 2 int d = log10(n); // computing count of numbers from 1 to 10^d-1, // d=0 a[0] = 0; // d=1 a[1] = count of numbers from 0 to 9 = 1 // d=2 a[2] = count of numbers from 0 to 99 = a[1]*9 + 10 = 19 // d=3 a[3] = count of numbers from 0 to 999 = a[2]*19 + 100 = 171 int *a = new int[d+1]; a[0] = 0, a[1] = 1; for (int i=2; i<=d; i++) a[i] = a[i-1]*9 + ceil(pow(10,i-1)); // Computing 10^d int p = ceil(pow(10, d)); // Most significant digit (msd) of n, // For 328, msd is 3 which can be obtained using 328/100 int msd = n/p; // If MSD is 4. For example if n = 428, then count of // numbers is sum of following. // 1) Count of numbers from 1 to 399 // 2) Count of numbers from 400 to 428 which is 29. if (msd == 4) return (msd)*a[d] + (n%p) + 1; // IF MSD > 4. For example if n is 728, then count of // numbers is sum of following. // 1) Count of numbers from 1 to 399 and count of numbers // from 500 to 699, i.e., \"a[2] * 6\" // 2) Count of numbers from 400 to 499, i.e. 100 // 3) Count of numbers from 700 to 728, recur for 28 if (msd > 4) return (msd-1)*a[d] + p + countNumbersWith4(n%p); // IF MSD < 4. For example if n is 328, then count of // numbers is sum of following. // 1) Count of numbers from 1 to 299 a // 2) Count of numbers from 300 to 328, recur for 28 return (msd)*a[d] + countNumbersWith4(n%p);} // Driver Programint main(){ int n = 328; cout << \"Count of numbers from 1 to \" << n << \" that have 4 as a a digit is \" << countNumbersWith4(n) << endl; return 0;}", "e": 38464, "s": 36591, "text": null }, { "code": "// Java program to count numbers having 4 as a digitclass GFG{ // Function to count numbers from// 1 to n that have 4 as a digitstatic int countNumbersWith4(int n){ // Base case if (n < 4) return 0; // d = number of digits minus // one in n. For 328, d is 2 int d = (int)Math.log10(n); // computing count of numbers from 1 to 10^d-1, // d=0 a[0] = 0; // d=1 a[1] = count of numbers from // 0 to 9 = 1 // d=2 a[2] = count of numbers from // 0 to 99 = a[1]*9 + 10 = 19 // d=3 a[3] = count of numbers from // 0 to 999 = a[2]*19 + 100 = 171 int[] a = new int[d + 2]; a[0] = 0; a[1] = 1; for (int i = 2; i <= d; i++) a[i] = a[i - 1] * 9 + (int)Math.ceil(Math.pow(10, i - 1)); // Computing 10^d int p = (int)Math.ceil(Math.pow(10, d)); // Most significant digit (msd) of n, // For 328, msd is 3 which can be obtained using 328/100 int msd = n / p; // If MSD is 4. For example if n = 428, then count of // numbers is sum of following. // 1) Count of numbers from 1 to 399 // 2) Count of numbers from 400 to 428 which is 29. if (msd == 4) return (msd) * a[d] + (n % p) + 1; // IF MSD > 4. For example if n // is 728, then count of numbers // is sum of following. // 1) Count of numbers from 1 to // 399 and count of numbers from // 500 to 699, i.e., \"a[2] * 6\" // 2) Count of numbers from 400 // to 499, i.e. 100 // 3) Count of numbers from 700 to // 728, recur for 28 if (msd > 4) return (msd - 1) * a[d] + p + countNumbersWith4(n % p); // IF MSD < 4. For example if n is 328, then count of // numbers is sum of following. // 1) Count of numbers from 1 to 299 a // 2) Count of numbers from 300 to 328, recur for 28 return (msd) * a[d] + countNumbersWith4(n % p);} // Driver codepublic static void main (String[] args){ int n = 328; System.out.println(\"Count of numbers from 1 to \"+ n + \" that have 4 as a digit is \" + countNumbersWith4(n));}} // This code is contributed by chandan_jnu", "e": 40548, "s": 38464, "text": null }, { "code": "# Python3 program to count numbers having 4 as a digitimport math as mt # Function to count numbers from 1 to n# that have 4 as a digitdef countNumbersWith4(n): # Base case if (n < 4): return 0 # d = number of digits minus one in n. # For 328, d is 2 d = int(mt.log10(n)) # computing count of numbers from 1 to 10^d-1, # d=0 a[0] = 0 # d=1 a[1] = count of numbers from 0 to 9 = 1 # d=2 a[2] = count of numbers from # 0 to 99 = a[1]*9 + 10 = 19 # d=3 a[3] = count of numbers from # 0 to 999 = a[2]*19 + 100 = 171 a = [1 for i in range(d + 1)] a[0] = 0 if len(a) > 1: a[1] = 1 for i in range(2, d + 1): a[i] = a[i - 1] * 9 + mt.ceil(pow(10, i - 1)) # Computing 10^d p = mt.ceil(pow(10, d)) # Most significant digit (msd) of n, # For 328, msd is 3 which can be # obtained using 328/100 msd = n // p # If MSD is 4. For example if n = 428, # then count of numbers is sum of following. # 1) Count of numbers from 1 to 399 # 2) Count of numbers from 400 to 428 which is 29. if (msd == 4): return (msd) * a[d] + (n % p) + 1 # IF MSD > 4. For example if n is 728, # then count of numbers is sum of following. # 1) Count of numbers from 1 to 399 and count # of numbers from 500 to 699, i.e., \"a[2] * 6\" # 2) Count of numbers from 400 to 499, i.e. 100 # 3) Count of numbers from 700 to 728, recur for 28 if (msd > 4): return ((msd - 1) * a[d] + p + countNumbersWith4(n % p)) # IF MSD < 4. For example if n is 328, # then count of numbers is sum of following. # 1) Count of numbers from 1 to 299 a # 2) Count of numbers from 300 to 328, recur for 28 return (msd) * a[d] + countNumbersWith4(n % p) # Driver Coden = 328print(\"Count of numbers from 1 to\", n, \"that have 4 as a digit is\", countNumbersWith4(n)) # This code is contributed by mohit kumar 29", "e": 42498, "s": 40548, "text": null }, { "code": "// C# program to count numbers having 4 as a digitusing System; class GFG{// Function to count numbers from// 1 to n that have 4 as a digitstatic int countNumbersWith4(int n){ // Base case if (n < 4) return 0; // d = number of digits minus // one in n. For 328, d is 2 int d = (int)Math.Log10(n); // computing count of numbers from 1 to 10^d-1, // d=0 a[0] = 0; // d=1 a[1] = count of numbers from // 0 to 9 = 1 // d=2 a[2] = count of numbers from // 0 to 99 = a[1]*9 + 10 = 19 // d=3 a[3] = count of numbers from // 0 to 999 = a[2]*19 + 100 = 171 int[] a = new int[d+2]; a[0] = 0; a[1] = 1; for (int i = 2; i <= d; i++) a[i] = a[i - 1] * 9 + (int)Math.Ceiling(Math.Pow(10, i - 1)); // Computing 10^d int p = (int)Math.Ceiling(Math.Pow(10, d)); // Most significant digit (msd) of n, // For 328, msd is 3 which can be obtained using 328/100 int msd = n / p; // If MSD is 4. For example if n = 428, then count of // numbers is sum of following. // 1) Count of numbers from 1 to 399 // 2) Count of numbers from 400 to 428 which is 29. if (msd == 4) return (msd) * a[d] + (n % p) + 1; // IF MSD > 4. For example if n is 728, then count of // numbers is sum of following. // 1) Count of numbers from 1 to 399 and count of numbers // from 500 to 699, i.e., \"a[2] * 6\" // 2) Count of numbers from 400 to 499, i.e. 100 // 3) Count of numbers from 700 to 728, recur for 28 if (msd > 4) return (msd - 1) * a[d] + p + countNumbersWith4(n % p); // IF MSD < 4. For example if n is 328, then count of // numbers is sum of following. // 1) Count of numbers from 1 to 299 a // 2) Count of numbers from 300 to 328, recur for 28 return (msd) * a[d] + countNumbersWith4(n % p);} // Driver codestatic void Main(){ int n = 328; Console.WriteLine(\"Count of numbers from 1 to \"+ n + \" that have 4 as a digit is \" + countNumbersWith4(n));}} // This code is contributed by chandan_jnu", "e": 44533, "s": 42498, "text": null }, { "code": "<?php// PHP program to count numbers having// 4 as a digit // Function to count numbers from 1 to n// that have 4 as a digitfunction countNumbersWith4($n){ // Base case if ($n < 4) return 0; // d = number of digits minus one in n. // For 328, d is 2 $d = (int)log10($n); // computing count of numbers from 1 to 10^d-1, // d=0 a[0] = 0; // d=1 a[1] = count of numbers from 0 to 9 is 1 // d=2 a[2] = count of numbers from 0 to 99 is // a[1]*9 + 10 = 19 // d=3 a[3] = count of numbers from 0 to 999 is // a[2]*19 + 100 = 171 $a = array_fill(0, $d + 1, NULL); $a[0] = 0; $a[1] = 1; for ($i = 2; $i <= $d; $i++) $a[$i] = $a[$i - 1] * 9 + ceil(pow(10, $i - 1)); // Computing 10^d $p = ceil(pow(10, $d)); // Most significant digit (msd) of n, // For 328, msd is 3 which can be // obtained using 328/100 $msd = intval($n / $p); // If MSD is 4. For example if n = 428, // then count of numbers is sum of following. // 1) Count of numbers from 1 to 399 // 2) Count of numbers from 400 to 428 which is 29. if ($msd == 4) return ($msd) * $a[$d] + ($n % $p) + 1; // IF MSD > 4. For example if n is 728, // then count of numbers is sum of following. // 1) Count of numbers from 1 to 399 and // count of numbers from 500 to 699, i.e., \"a[2] * 6\" // 2) Count of numbers from 400 to 499, i.e. 100 // 3) Count of numbers from 700 to 728, recur for 28 if ($msd > 4) return ($msd - 1) * $a[$d] + $p + countNumbersWith4($n % $p); // IF MSD < 4. For example if n is 328, then // count of numbers is sum of following. // 1) Count of numbers from 1 to 299 a // 2) Count of numbers from 300 to 328, recur for 28 return ($msd) * $a[$d] + countNumbersWith4($n % $p);} // Driver Code$n = 328;echo \"Count of numbers from 1 to \" . $n . \" that have 4 as a digit is \" . countNumbersWith4($n) . \"\\n\"; // This code is contributed by ita_c?>", "e": 46619, "s": 44533, "text": null }, { "code": "<script> // Javascript program to count numbers having 4 as a digit // Function to count numbers from // 1 to n that have 4 as a digit function countNumbersWith4(n) { // Base case if (n < 4) return 0; // d = number of digits minus // one in n. For 328, d is 2 let d = Math.floor(Math.log10(n)); // computing count of numbers from 1 to 10^d-1, // d=0 a[0] = 0; // d=1 a[1] = count of numbers from // 0 to 9 = 1 // d=2 a[2] = count of numbers from // 0 to 99 = a[1]*9 + 10 = 19 // d=3 a[3] = count of numbers from // 0 to 999 = a[2]*19 + 100 = 171 let a = new Array(d + 2); for(let i=0;i<d+2;i++) { a[i]=0; } a[0] = 0; a[1] = 1; for (let i = 2; i <= d; i++) a[i] = a[i - 1] * 9 + Math.floor(Math.ceil(Math.pow(10, i - 1))); // Computing 10^d let p = Math.floor(Math.ceil(Math.pow(10, d))); // Most significant digit (msd) of n, // For 328, msd is 3 which can be obtained using 328/100 let msd = Math.floor(n / p); // If MSD is 4. For example if n = 428, then count of // numbers is sum of following. // 1) Count of numbers from 1 to 399 // 2) Count of numbers from 400 to 428 which is 29. if (msd == 4) return (msd) * a[d] + (n % p) + 1; // IF MSD > 4. For example if n // is 728, then count of numbers // is sum of following. // 1) Count of numbers from 1 to // 399 and count of numbers from // 500 to 699, i.e., \"a[2] * 6\" // 2) Count of numbers from 400 // to 499, i.e. 100 // 3) Count of numbers from 700 to // 728, recur for 28 if (msd > 4) return (msd - 1) * a[d] + p + countNumbersWith4(n % p); // IF MSD < 4. For example if n is 328, then count of // numbers is sum of following. // 1) Count of numbers from 1 to 299 a // 2) Count of numbers from 300 to 328, recur for 28 return (msd) * a[d] + countNumbersWith4(n % p); } // Driver code let n = 328; document.write(\"Count of numbers from 1 to \"+ n + \" that have 4 as a digit is \" + countNumbersWith4(n)); // This code is contributed by rag2127</script>", "e": 49035, "s": 46619, "text": null }, { "code": null, "e": 49044, "s": 49035, "text": "Output: " }, { "code": null, "e": 49106, "s": 49044, "text": "Count of numbers from 1 to 328 that have 4 as a a digit is 60" }, { "code": null, "e": 49270, "s": 49106, "text": "This article is contributed by Shivam. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 49277, "s": 49270, "text": "Sam007" }, { "code": null, "e": 49292, "s": 49277, "text": "mohit kumar 29" }, { "code": null, "e": 49298, "s": 49292, "text": "ukasp" }, { "code": null, "e": 49312, "s": 49298, "text": "Chandan_Kumar" }, { "code": null, "e": 49333, "s": 49312, "text": "avanitrachhadiya2155" }, { "code": null, "e": 49341, "s": 49333, "text": "rag2127" }, { "code": null, "e": 49351, "s": 49341, "text": "anuragayu" }, { "code": null, "e": 49364, "s": 49351, "text": "Drishti-Soft" }, { "code": null, "e": 49379, "s": 49364, "text": "Morgan Stanley" }, { "code": null, "e": 49386, "s": 49379, "text": "Arrays" }, { "code": null, "e": 49406, "s": 49386, "text": "Dynamic Programming" }, { "code": null, "e": 49419, "s": 49406, "text": "Mathematical" }, { "code": null, "e": 49434, "s": 49419, "text": "Morgan Stanley" }, { "code": null, "e": 49447, "s": 49434, "text": "Drishti-Soft" }, { "code": null, "e": 49454, "s": 49447, "text": "Arrays" }, { "code": null, "e": 49474, "s": 49454, "text": "Dynamic Programming" }, { "code": null, "e": 49487, "s": 49474, "text": "Mathematical" }, { "code": null, "e": 49585, "s": 49487, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 49616, "s": 49585, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 49641, "s": 49616, "text": "Window Sliding Technique" }, { "code": null, "e": 49679, "s": 49641, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 49700, "s": 49679, "text": "Next Greater Element" }, { "code": null, "e": 49758, "s": 49700, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 49787, "s": 49758, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 49817, "s": 49787, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 49851, "s": 49817, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 49882, "s": 49851, "text": "Bellman–Ford Algorithm | DP-23" } ]
How order of classes work in CSS ? - GeeksforGeeks
06 Sep, 2021 Many developers are aware of the concept of class overwriting in CSS. Well, is true but when it comes to how these classes are overwritten, most of them get confused. Classes are among the important assets of front-end development. Therefore, it is very important to have clarity about them. The attributes of style that are required to be included in the HTML elements are defined within the classes and then could be invoked using the “style” attribute within the tag. The style attribute supports as many values(classes) that you provide, and the confusion starts from here! Whether you talk about defining classes in the same file within the block or invoking classes from the different CSS files. This rule remains consistent. “The order of the classes in which they would work does not depend upon the order, in which they are written in the class attribute. Rather, it is decided by the order in which they appear in the block or the .css file” In case multiple classes consist of similar attributes and they are used in the same HTML element. Then, the class modified the latest would be used to style the element. Below example illustrates the concept of order of classes: Example HTML <!DOCTYPE html><html> <head> <title>Specify the order of classes in CSS</title> <style type="text/css"> h1 { color: green; } .container { width: 600px; padding: 5px; border: 2px solid black; } .box1 { width: 300px; height: 50px; background-color: purple; } .box2 { width: 595px; height: 50px; background-color: yellow; } </style></head> <body> <h1>Geeksforgeeks</h1> <b>A Computer Science Portal for Geeks</b> <br> <br> <div class="container"> <div> <input type="text" class="box1" value= "How is it going everyone, this is box number 1"> </div> <div> <input type="text" class="box2" value= "This is box number 2"> </div> <div> <input type="text" class="box1 box2" value="Here we are trying to combine box1 and box2, let us name it box3"> </div> <div> <input type="text" class="box2 box1" value="This is similar to box number 3, only difference is precedence of classes, let us name it box4"> </div> </div></body> </html> Output: Now if you notice div1 and div2 representing classes box1 and box2 respectively would give you the result as expected. However, in the case of div3 with the style attribute as box1 box2, it invokes multiple CSS classes. Now one might easily confuse that since box1 is written first in the style attribute of div3 and therefore is called prior and then as soon as box2 is invoked it should overwrite box1. But that is not the case. If you look carefully in styling.css file, box1{} is defined prior to box2{} and that is why box1 is overwritten by box2. In case of div4, when we are calling box2 prior to box1. This same mechanism works and provides the style of box2 in the div4 block. Note: Remember the inline CSS always have more priority than the external and internal CSS. Therefore if you use inline styling in the HTML elements, then the properties defined in the inline styling would overwrite predefined classes. YOu can ignore all these things if you are aware of !important keyword. Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. singghakshay CSS-Misc CSS HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to create footer to stay at the bottom of a Web page? How to apply style to parent if it has child with CSS? How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property
[ { "code": null, "e": 29291, "s": 29263, "text": "\n06 Sep, 2021" }, { "code": null, "e": 29869, "s": 29291, "text": "Many developers are aware of the concept of class overwriting in CSS. Well, is true but when it comes to how these classes are overwritten, most of them get confused. Classes are among the important assets of front-end development. Therefore, it is very important to have clarity about them. The attributes of style that are required to be included in the HTML elements are defined within the classes and then could be invoked using the “style” attribute within the tag. The style attribute supports as many values(classes) that you provide, and the confusion starts from here!" }, { "code": null, "e": 30024, "s": 29869, "text": "Whether you talk about defining classes in the same file within the block or invoking classes from the different CSS files. This rule remains consistent. " }, { "code": null, "e": 30244, "s": 30024, "text": "“The order of the classes in which they would work does not depend upon the order, in which they are written in the class attribute. Rather, it is decided by the order in which they appear in the block or the .css file”" }, { "code": null, "e": 30415, "s": 30244, "text": "In case multiple classes consist of similar attributes and they are used in the same HTML element. Then, the class modified the latest would be used to style the element." }, { "code": null, "e": 30475, "s": 30415, "text": "Below example illustrates the concept of order of classes: " }, { "code": null, "e": 30485, "s": 30475, "text": "Example " }, { "code": null, "e": 30490, "s": 30485, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Specify the order of classes in CSS</title> <style type=\"text/css\"> h1 { color: green; } .container { width: 600px; padding: 5px; border: 2px solid black; } .box1 { width: 300px; height: 50px; background-color: purple; } .box2 { width: 595px; height: 50px; background-color: yellow; } </style></head> <body> <h1>Geeksforgeeks</h1> <b>A Computer Science Portal for Geeks</b> <br> <br> <div class=\"container\"> <div> <input type=\"text\" class=\"box1\" value= \"How is it going everyone, this is box number 1\"> </div> <div> <input type=\"text\" class=\"box2\" value= \"This is box number 2\"> </div> <div> <input type=\"text\" class=\"box1 box2\" value=\"Here we are trying to combine box1 and box2, let us name it box3\"> </div> <div> <input type=\"text\" class=\"box2 box1\" value=\"This is similar to box number 3, only difference is precedence of classes, let us name it box4\"> </div> </div></body> </html>", "e": 31757, "s": 30490, "text": null }, { "code": null, "e": 31766, "s": 31757, "text": "Output: " }, { "code": null, "e": 31886, "s": 31766, "text": "Now if you notice div1 and div2 representing classes box1 and box2 respectively would give you the result as expected. " }, { "code": null, "e": 32453, "s": 31886, "text": "However, in the case of div3 with the style attribute as box1 box2, it invokes multiple CSS classes. Now one might easily confuse that since box1 is written first in the style attribute of div3 and therefore is called prior and then as soon as box2 is invoked it should overwrite box1. But that is not the case. If you look carefully in styling.css file, box1{} is defined prior to box2{} and that is why box1 is overwritten by box2. In case of div4, when we are calling box2 prior to box1. This same mechanism works and provides the style of box2 in the div4 block." }, { "code": null, "e": 32762, "s": 32453, "text": "Note: Remember the inline CSS always have more priority than the external and internal CSS. Therefore if you use inline styling in the HTML elements, then the properties defined in the inline styling would overwrite predefined classes. YOu can ignore all these things if you are aware of !important keyword. " }, { "code": null, "e": 32899, "s": 32762, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 32912, "s": 32899, "text": "singghakshay" }, { "code": null, "e": 32921, "s": 32912, "text": "CSS-Misc" }, { "code": null, "e": 32925, "s": 32921, "text": "CSS" }, { "code": null, "e": 32930, "s": 32925, "text": "HTML" }, { "code": null, "e": 32947, "s": 32930, "text": "Web Technologies" }, { "code": null, "e": 32974, "s": 32947, "text": "Web technologies Questions" }, { "code": null, "e": 32979, "s": 32974, "text": "HTML" }, { "code": null, "e": 33077, "s": 32979, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33127, "s": 33077, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 33189, "s": 33127, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 33237, "s": 33189, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 33295, "s": 33237, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 33350, "s": 33295, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 33400, "s": 33350, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 33462, "s": 33400, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 33510, "s": 33462, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 33570, "s": 33510, "text": "How to set the default value for an HTML <select> element ?" } ]
Find the average of first N natural numbers - GeeksforGeeks
19 Mar, 2021 Write a program to find the Average of first N natural number. Examples: Input : 10 Output : 5.5 1+2+3+4+5+6+7+8+9+10 = 5.5 Input : 7 Output : 4.0 1+2+3+4+5+6+7 = 4 Prerequisite : Sum of first n natural numbers.As discussed in previous post, sum of n natural number n(n+1)/2, we find the Average of n natural number so divide by n is n(n+1)/2*n = (n+1)/2. Here 1 if first term and n is last term. C++ Java Python3 C# PHP Javascript // CPP Program to find the Average of first// n natural numbers#include <bits/stdc++.h>using namespace std; // Return the average of first n natural numbersfloat avgOfFirstN(int n){ return (float)(1 + n)/2;} // Driven Programint main(){ int n = 20; cout << avgOfFirstN(n) << endl; return 0;} // Java Program to find the Average of first// n natural numbersimport java.io.*; class GFG { // Return the average of first n // natural numbers static float avgOfFirstN(int n) { return (float)(1 + n) / 2; } // Driven Program public static void main(String args[]) { int n = 20; System.out.println(avgOfFirstN(n)); }} /*This code is contributed by Nikita tiwari.*/ # Python 3 Program to find the Average# of first n natural numbers # Return the average of first n# natural numbersdef avgOfFirstN(n) : return (float)(1 + n) / 2; # Driven Programn = 20print(avgOfFirstN(n)) # This code is contributed by Nikita Tiwari. // C#Program to find the Average of first// n natural numbersusing System; class GFG { // Return the average of first n // natural numbers static float avgOfFirstN(int n) { return (float)(1 + n) / 2; } // Driven Program public static void Main() { int n = 20; Console.WriteLine(avgOfFirstN(n)); }} /*This code is contributed by vt_m.*/ <?php// PHP Program to find// the Average of first// n natural numbers // Return the average// of first n natural// numbersfunction avgOfFirstN($n){ return (float)(1 + $n) / 2;} // Driver Code$n = 20;echo(avgOfFirstN($n)); // This code is contributed by Ajit.?> <script> // javascript Program to find the Average of first// n natural numbers // Return the average of first n natural numbersfunction avgOfFirstN( n){ return (1 + n)/2;} // Driven Program let n = 20; document.write(avgOfFirstN(n)); // This code is contributed by todaysgaurav </script> Output: 10.5 Time Complexity : O(1) jit_t todaysgaurav Mathematical School Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Program to find GCD or HCF of two numbers Print all possible combinations of r elements in a given array of size n Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java C++ Classes and Objects
[ { "code": null, "e": 26684, "s": 26656, "text": "\n19 Mar, 2021" }, { "code": null, "e": 26759, "s": 26684, "text": "Write a program to find the Average of first N natural number. Examples: " }, { "code": null, "e": 26854, "s": 26759, "text": "Input : 10\nOutput : 5.5\n1+2+3+4+5+6+7+8+9+10 = 5.5\n\nInput : 7\nOutput : 4.0\n1+2+3+4+5+6+7 = 4" }, { "code": null, "e": 27090, "s": 26856, "text": "Prerequisite : Sum of first n natural numbers.As discussed in previous post, sum of n natural number n(n+1)/2, we find the Average of n natural number so divide by n is n(n+1)/2*n = (n+1)/2. Here 1 if first term and n is last term. " }, { "code": null, "e": 27094, "s": 27090, "text": "C++" }, { "code": null, "e": 27099, "s": 27094, "text": "Java" }, { "code": null, "e": 27107, "s": 27099, "text": "Python3" }, { "code": null, "e": 27110, "s": 27107, "text": "C#" }, { "code": null, "e": 27114, "s": 27110, "text": "PHP" }, { "code": null, "e": 27125, "s": 27114, "text": "Javascript" }, { "code": "// CPP Program to find the Average of first// n natural numbers#include <bits/stdc++.h>using namespace std; // Return the average of first n natural numbersfloat avgOfFirstN(int n){ return (float)(1 + n)/2;} // Driven Programint main(){ int n = 20; cout << avgOfFirstN(n) << endl; return 0;}", "e": 27429, "s": 27125, "text": null }, { "code": "// Java Program to find the Average of first// n natural numbersimport java.io.*; class GFG { // Return the average of first n // natural numbers static float avgOfFirstN(int n) { return (float)(1 + n) / 2; } // Driven Program public static void main(String args[]) { int n = 20; System.out.println(avgOfFirstN(n)); }} /*This code is contributed by Nikita tiwari.*/", "e": 27845, "s": 27429, "text": null }, { "code": "# Python 3 Program to find the Average# of first n natural numbers # Return the average of first n# natural numbersdef avgOfFirstN(n) : return (float)(1 + n) / 2; # Driven Programn = 20print(avgOfFirstN(n)) # This code is contributed by Nikita Tiwari.", "e": 28100, "s": 27845, "text": null }, { "code": "// C#Program to find the Average of first// n natural numbersusing System; class GFG { // Return the average of first n // natural numbers static float avgOfFirstN(int n) { return (float)(1 + n) / 2; } // Driven Program public static void Main() { int n = 20; Console.WriteLine(avgOfFirstN(n)); }} /*This code is contributed by vt_m.*/", "e": 28486, "s": 28100, "text": null }, { "code": "<?php// PHP Program to find// the Average of first// n natural numbers // Return the average// of first n natural// numbersfunction avgOfFirstN($n){ return (float)(1 + $n) / 2;} // Driver Code$n = 20;echo(avgOfFirstN($n)); // This code is contributed by Ajit.?>", "e": 28751, "s": 28486, "text": null }, { "code": "<script> // javascript Program to find the Average of first// n natural numbers // Return the average of first n natural numbersfunction avgOfFirstN( n){ return (1 + n)/2;} // Driven Program let n = 20; document.write(avgOfFirstN(n)); // This code is contributed by todaysgaurav </script>", "e": 29050, "s": 28751, "text": null }, { "code": null, "e": 29059, "s": 29050, "text": "Output: " }, { "code": null, "e": 29064, "s": 29059, "text": "10.5" }, { "code": null, "e": 29089, "s": 29064, "text": "Time Complexity : O(1) " }, { "code": null, "e": 29095, "s": 29089, "text": "jit_t" }, { "code": null, "e": 29108, "s": 29095, "text": "todaysgaurav" }, { "code": null, "e": 29121, "s": 29108, "text": "Mathematical" }, { "code": null, "e": 29140, "s": 29121, "text": "School Programming" }, { "code": null, "e": 29153, "s": 29140, "text": "Mathematical" }, { "code": null, "e": 29251, "s": 29153, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29275, "s": 29251, "text": "Merge two sorted arrays" }, { "code": null, "e": 29318, "s": 29275, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 29332, "s": 29318, "text": "Prime Numbers" }, { "code": null, "e": 29374, "s": 29332, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 29447, "s": 29374, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 29465, "s": 29447, "text": "Python Dictionary" }, { "code": null, "e": 29481, "s": 29465, "text": "Arrays in C/C++" }, { "code": null, "e": 29500, "s": 29481, "text": "Inheritance in C++" }, { "code": null, "e": 29525, "s": 29500, "text": "Reverse a string in Java" } ]