title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
JavaScript Date getYear() Method | Javascript date getYear() method returns the year in the specified date according to universal time. The getYear is no longer used and has been replaced by the getYear method.
The value returned by getYear is the current year minus 1900. JavaScript 1.2 and earlier versions return either a 2-digit or 4-digit year. For example, if the year is 2026, the value returned is 2026. So before testing this function, you need to be sure of the javascript version you are using.
Its syntax is as follows −
Date.getYear()
Returns the year in the specified date according to universal time.
Try the following example.
<html>
<head>
<title>JavaScript getYear Method</title>
</head>
<body>
<script type = "text/javascript">
var dt = new Date();
document.write("getYear() : " + dt.getYear() );
</script>
</body>
</html>
getYear() : 208
25 Lectures
2.5 hours
Anadi Sharma
74 Lectures
10 hours
Lets Kode It
72 Lectures
4.5 hours
Frahaan Hussain
70 Lectures
4.5 hours
Frahaan Hussain
46 Lectures
6 hours
Eduonix Learning Solutions
88 Lectures
14 hours
Eduonix Learning Solutions
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2642,
"s": 2466,
"text": "Javascript date getYear() method returns the year in the specified date according to universal time. The getYear is no longer used and has been replaced by the getYear method."
},
{
"code": null,
"e": 2937,
"s": 2642,
"text": "The value returned by getYear is the current year minus 1900. JavaScript 1.2 and earlier versions return either a 2-digit or 4-digit year. For example, if the year is 2026, the value returned is 2026. So before testing this function, you need to be sure of the javascript version you are using."
},
{
"code": null,
"e": 2964,
"s": 2937,
"text": "Its syntax is as follows −"
},
{
"code": null,
"e": 2980,
"s": 2964,
"text": "Date.getYear()\n"
},
{
"code": null,
"e": 3048,
"s": 2980,
"text": "Returns the year in the specified date according to universal time."
},
{
"code": null,
"e": 3075,
"s": 3048,
"text": "Try the following example."
},
{
"code": null,
"e": 3339,
"s": 3075,
"text": "<html>\n <head>\n <title>JavaScript getYear Method</title>\n </head>\n \n <body> \n <script type = \"text/javascript\">\n var dt = new Date();\n document.write(\"getYear() : \" + dt.getYear() ); \n </script> \n </body>\n</html>"
},
{
"code": null,
"e": 3356,
"s": 3339,
"text": "getYear() : 208\n"
},
{
"code": null,
"e": 3391,
"s": 3356,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3405,
"s": 3391,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3439,
"s": 3405,
"text": "\n 74 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 3453,
"s": 3439,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3488,
"s": 3453,
"text": "\n 72 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3505,
"s": 3488,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3540,
"s": 3505,
"text": "\n 70 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3557,
"s": 3540,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3590,
"s": 3557,
"text": "\n 46 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3618,
"s": 3590,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3652,
"s": 3618,
"text": "\n 88 Lectures \n 14 hours \n"
},
{
"code": null,
"e": 3680,
"s": 3652,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3687,
"s": 3680,
"text": " Print"
},
{
"code": null,
"e": 3698,
"s": 3687,
"text": " Add Notes"
}
] |
Check if a jquery has been loaded or not - GeeksforGeeks | 06 Dec, 2019
Given a document, The task is to determine whether JQuery has been loaded or not, If not then load it dynamically using JavaScript. Below are the examples to check:Approach:
First check if it is loaded.
If not loaded then load it dynamically, create a script element and add properties like(type, src) to it and then finally append it at the end, inside of the head element.
Example 1: In this example, the JQuery is already loaded so message ‘Script already loaded!’ prints on screen.
<!DOCTYPE HTML><html> <head> <title> JavaScript | Check if jquery has been loaded, If not then load. </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 19px; font-weight: bold;"> </p> <button onClick="GFG_Fun()"> click here </button> <p id="GFG_DOWN" style="color: green; font-size: 24px; font-weight: bold;"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); up.innerHTML = "Click on button to check whether JQuery is loaded"; function GFG_Fun() { if (!window.jQuery) { var el = document.createElement('script'); el.type = "text/javascript"; el.src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"; document.getElementsByTagName( 'head')[0].appendChild(el); down.innerHTML = "Script loaded successfully!"; } else { down.innerHTML = "Script already loaded!"; } } </script></body> </html>
Output:
Before clicking on the button:
After clicking on the button:
Example 2: The src attribute of script element is changed to sc. In this example, the JQuery is not loaded so message ‘Script loaded successfully!’ prints on screen after successful loading.
<!DOCTYPE HTML><html> <head> <title> JavaScript | Check if jquery has been loaded, If not then load. </title> <script sc="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 19px; font-weight: bold;"> </p> <button onClick="GFG_Fun()"> click here </button> <p id="GFG_DOWN" style="color: green; font-size: 24px; font-weight: bold;"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); up.innerHTML = "Click on button to check whether JQuery is loaded"; function GFG_Fun() { if (!window.jQuery) { var el = document.createElement('script'); el.type = "text/javascript"; el.src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"; document.getElementsByTagName( 'head')[0].appendChild(el); down.innerHTML = "Script loaded successfully!"; } else { down.innerHTML = "Script already loaded!"; } } </script></body> </html>
Output:
Before clicking on the button:
After clicking on the button:
nidhi_biet
JavaScript-Misc
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to Open URL in New Tab using JavaScript ?
Difference Between PUT and PATCH Request
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 24213,
"s": 24185,
"text": "\n06 Dec, 2019"
},
{
"code": null,
"e": 24387,
"s": 24213,
"text": "Given a document, The task is to determine whether JQuery has been loaded or not, If not then load it dynamically using JavaScript. Below are the examples to check:Approach:"
},
{
"code": null,
"e": 24416,
"s": 24387,
"text": "First check if it is loaded."
},
{
"code": null,
"e": 24588,
"s": 24416,
"text": "If not loaded then load it dynamically, create a script element and add properties like(type, src) to it and then finally append it at the end, inside of the head element."
},
{
"code": null,
"e": 24699,
"s": 24588,
"text": "Example 1: In this example, the JQuery is already loaded so message ‘Script already loaded!’ prints on screen."
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> JavaScript | Check if jquery has been loaded, If not then load. </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 19px; font-weight: bold;\"> </p> <button onClick=\"GFG_Fun()\"> click here </button> <p id=\"GFG_DOWN\" style=\"color: green; font-size: 24px; font-weight: bold;\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); up.innerHTML = \"Click on button to check whether JQuery is loaded\"; function GFG_Fun() { if (!window.jQuery) { var el = document.createElement('script'); el.type = \"text/javascript\"; el.src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"; document.getElementsByTagName( 'head')[0].appendChild(el); down.innerHTML = \"Script loaded successfully!\"; } else { down.innerHTML = \"Script already loaded!\"; } } </script></body> </html>",
"e": 26098,
"s": 24699,
"text": null
},
{
"code": null,
"e": 26106,
"s": 26098,
"text": "Output:"
},
{
"code": null,
"e": 26137,
"s": 26106,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 26167,
"s": 26137,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 26358,
"s": 26167,
"text": "Example 2: The src attribute of script element is changed to sc. In this example, the JQuery is not loaded so message ‘Script loaded successfully!’ prints on screen after successful loading."
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> JavaScript | Check if jquery has been loaded, If not then load. </title> <script sc=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 19px; font-weight: bold;\"> </p> <button onClick=\"GFG_Fun()\"> click here </button> <p id=\"GFG_DOWN\" style=\"color: green; font-size: 24px; font-weight: bold;\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); up.innerHTML = \"Click on button to check whether JQuery is loaded\"; function GFG_Fun() { if (!window.jQuery) { var el = document.createElement('script'); el.type = \"text/javascript\"; el.src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"; document.getElementsByTagName( 'head')[0].appendChild(el); down.innerHTML = \"Script loaded successfully!\"; } else { down.innerHTML = \"Script already loaded!\"; } } </script></body> </html>",
"e": 27773,
"s": 26358,
"text": null
},
{
"code": null,
"e": 27781,
"s": 27773,
"text": "Output:"
},
{
"code": null,
"e": 27812,
"s": 27781,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 27842,
"s": 27812,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 27853,
"s": 27842,
"text": "nidhi_biet"
},
{
"code": null,
"e": 27869,
"s": 27853,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 27880,
"s": 27869,
"text": "JavaScript"
},
{
"code": null,
"e": 27897,
"s": 27880,
"text": "Web Technologies"
},
{
"code": null,
"e": 27995,
"s": 27897,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28004,
"s": 27995,
"text": "Comments"
},
{
"code": null,
"e": 28017,
"s": 28004,
"text": "Old Comments"
},
{
"code": null,
"e": 28078,
"s": 28017,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28123,
"s": 28078,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28195,
"s": 28123,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 28241,
"s": 28195,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 28282,
"s": 28241,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 28338,
"s": 28282,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 28371,
"s": 28338,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28433,
"s": 28371,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28476,
"s": 28433,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Python program to reverse each word in a sentence? | Here we use python built in function. First we split the sentence into a list of word. Then reverse each word and creating a new list ,here we use python list comprehension technique and last joining the new list of words and create an new sentence.
Input :: PYTHON PROGRAM
Output :: NOHTYP MARGORP
Step 1 : input a sentence. And store this in a variable s.
Step 2 : Then splitting the sentence into a list of words.
w=s.split(“”)
Step 3 : Reversing each word and creating a new list of words nw.
Step 4 : Joining the new list of words and make a new sentence ns.
# Reverse each word of a Sentence
# Function to Reverse words
def reverseword(s):
w = s.split(" ") # Splitting the Sentence into list of words.
# reversing each word and creating a new list of words
# apply List Comprehension Technique
nw = [i[::-1] for i in w]
# Join the new list of words to for a new Sentence
ns = " ".join(nw)
return ns
# Driver's Code
s = input("ENTER A SENTENCE PROPERLY ::")
print(reverseword(s))
ENTER A SENTENCE PROPERLY :: PYTHON PROGRAM
NOHTYP MARGORP | [
{
"code": null,
"e": 1312,
"s": 1062,
"text": "Here we use python built in function. First we split the sentence into a list of word. Then reverse each word and creating a new list ,here we use python list comprehension technique and last joining the new list of words and create an new sentence."
},
{
"code": null,
"e": 1362,
"s": 1312,
"text": "Input :: PYTHON PROGRAM\nOutput :: NOHTYP MARGORP\n"
},
{
"code": null,
"e": 1631,
"s": 1362,
"text": "Step 1 : input a sentence. And store this in a variable s.\nStep 2 : Then splitting the sentence into a list of words.\n w=s.split(“”)\nStep 3 : Reversing each word and creating a new list of words nw.\nStep 4 : Joining the new list of words and make a new sentence ns.\n"
},
{
"code": null,
"e": 2160,
"s": 1631,
"text": "# Reverse each word of a Sentence\n # Function to Reverse words\ndef reverseword(s): \n \n w = s.split(\" \") # Splitting the Sentence into list of words.\n # reversing each word and creating a new list of words\n # apply List Comprehension Technique\n nw = [i[::-1] for i in w]\n # Join the new list of words to for a new Sentence\n ns = \" \".join(nw)\n return ns\n# Driver's Code \ns = input(\"ENTER A SENTENCE PROPERLY ::\")\nprint(reverseword(s))"
},
{
"code": null,
"e": 2220,
"s": 2160,
"text": "ENTER A SENTENCE PROPERLY :: PYTHON PROGRAM\nNOHTYP MARGORP\n"
}
] |
Dog Breed prediction using CNNs and transfer learning | by Jesse Fredrickson | Towards Data Science | In this article, I will demonstrate how to use keras and tensorflow to build, train, and test a Convolutional Neural Network capable of identifying the breed of a dog in a supplied image. Success will be defined by high validation and test accuracy, with precision and recall scores differentiating between models with similar accuracy.
This is a supervised learning problem, specifically a multiclass classification problem, and as such the solution may be approached with the following steps:
Amass labelled data. In this case, that means compiling a repository of images with dogs of known breeds.Construct a model capable of extracting data from training images, which outputs data which may be interpreted to discern a breed of dog.Train the model on training data, validate performance during training with validation dataEvaluate performance metrics, potentially return to step 2 with edits to improve performanceTest the model on test data
Amass labelled data. In this case, that means compiling a repository of images with dogs of known breeds.
Construct a model capable of extracting data from training images, which outputs data which may be interpreted to discern a breed of dog.
Train the model on training data, validate performance during training with validation data
Evaluate performance metrics, potentially return to step 2 with edits to improve performance
Test the model on test data
Each step of course has a number of sub-steps which I will detail as I go.
The act of training a neural network, even a relatively simple one, can be extremely computationally expensive. Many companies use server racks of GPUs dedicated to this kind of task; I will be working on my local PC which is equipped with a GTX 1070 graphics card which I will recruit for this exercise. In order to perform this task on your local computer, there are a few steps you must take in order to define a proper programming environment, and I will detail them here. If you are not interested in the backend setup, skip to the next section.
First, I created a new environment in Anaconda, and installed the following packages:
tensorflow-gpu
jupyter
glob2
scikit-learn
keras
matplotlib
opencv (This is for identifying human faces in image pipeline — not a necessary capability, but useful in some applications)
tqdm
pillow
seaborn
Next, I updated my graphics drivers. This is important because driver updates are pushed out fairly regularly, even for a card like mine which is 3 years old, and if you are using a modern version of tensorflow is it necessary to use up-to-date drivers for compatibility. In my case, drivers that were only 5 months old were incompatible with the newest version of tensorflow.
Finally, open a jupyter notebook from an anaconda prompt in the new environment in order to perform your work, and ensure jupyter is using the correct environment for the kernel. Tensorflow may encounter issues if you don’t do this.
As a sanity check, post module imports I can call the following to show available CPUs and GPUs.
from tensorflow.python.client import device_libprint(device_lib.list_local_devices())
Success! There’s my GTX 1070.
Finally, I execute the following code block which edits some configuration parameters of the tensorflow backend and prevents some runtime errors in the future.
# tensorflow local GPU configurationgpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.8)config = tf.ConfigProto()config.gpu_options.allow_growth = Truesession = tf.Session(config=config)
In my case, this was trivial, as Udacity provided me with 1.08Gb of dog images spanning 133 breeds, already in a proper file structure. Proper file structure, in the case of a classification CNN built with keras, means files are segregated by training, validation, and testing, and further segregated within these folders by dog breed. The names of each folder should be the names of the classes which you plan to identify.
Obviously, there are more than 133 dog breeds in the world — the American authority, the AKC, lists 190 breeds, and the world authority, the FCI, lists 360 breeds. If I wanted to increase the size of my training dataset to include more breeds or just more images of each breed, one avenue I could pursue would be to install the python Flickr API and query it for images tagged with the names of whatever breed I desired. However for the purposes of this project, I continue with this basic dataset.
As an initial step, I will load all of the filenames into memory for easier processing down the road.
# define function to load train, test, and validation datasetsdef load_dataset(path): data = load_files(path) dog_files = np.array(data['filenames']) dog_targets = np_utils.to_categorical(np.array(data['target']))#, 133) return dog_files, dog_targets# load train, test, and validation datasetstrain_files, train_targets = load_dataset('dogImages/train')valid_files, valid_targets = load_dataset('dogImages/valid')test_files, test_targets = load_dataset('dogImages/test')# load list of dog names# the [20:-1] portion simply removes the filepath and folder numberdog_names = [item[20:-1] for item in sorted(glob("dogImages/train/*/"))]# print statistics about the datasetprint('There are %d total dog categories.' % len(dog_names))print('There are %s total dog images.\n' % len(np.hstack([train_files, valid_files, test_files])))print('There are %d training dog images.' % len(train_files))print('There are %d validation dog images.' % len(valid_files))print('There are %d test dog images.'% len(test_files))
which outputs the following stats:
There are 133 total dog categories.There are 8351 total dog images.There are 6680 training dog images.There are 835 validation dog images.There are 836 test dog images.
Next, I perform a step to normalize the data by dividing every pixel in the image by 255 and format the output as a tensor — a vector which can be used by keras. Note: the following code loads thousands of files into memory as tensors. Although this is possible with a relatively small dataset, it is better practice to use a batch loading system which only loads in a small number of tensors at a time. I do this in a later step, for the last model I design.
# define functions for reading in image files as tensorsdef path_to_tensor(img_path, target_size=(224, 224)): # loads RGB image as PIL.Image.Image type # 299 is for xception, 224 for the other models img = image.load_img(img_path, target_size=target_size) # convert PIL.Image.Image type to 3D tensor with shape (224, 224, 3) x = image.img_to_array(img) # convert 3D tensor to 4D tensor with shape (1, (target_size,) 3) and return 4D tensor return np.expand_dims(x, axis=0)def paths_to_tensor(img_paths, target_size = (224, 224)): list_of_tensors = [path_to_tensor(img_path, target_size) for img_path in tqdm(img_paths)] return np.vstack(list_of_tensors)# run above functionsfrom PIL import ImageFile ImageFile.LOAD_TRUNCATED_IMAGES = True# pre-process the data for Kerastrain_tensors = paths_to_tensor(train_files).astype('float32')/255valid_tensors = paths_to_tensor(valid_files).astype('float32')/255test_tensors = paths_to_tensor(test_files).astype('float32')/255
There are an infinite number of ways do this, some of which will work much better than others. I am going to explore 3 unique approaches, and follow them from construction through to testing and evaluation. The approaches I take are as follows:
Trivial solution. I will construct and train a very simple CNN on the dataset and evaluate its performance.Transfer learning with bottleneck features. I will make use of an existing CNN which has been trained on a massive image library, and adapt it to my application by using it to transform my input images into “bottleneck features”: abstract feature representations of the images.Transfer learning with image augmentation. Similar to the bottleneck features approach, but I will attempt to get better model generalization by creating a model which is a stack of a pretrained bottleneck feature CNN with a custom output layer for my application, and I will feed it input images which are randomly augmented by pictographic transformations.
Trivial solution. I will construct and train a very simple CNN on the dataset and evaluate its performance.
Transfer learning with bottleneck features. I will make use of an existing CNN which has been trained on a massive image library, and adapt it to my application by using it to transform my input images into “bottleneck features”: abstract feature representations of the images.
Transfer learning with image augmentation. Similar to the bottleneck features approach, but I will attempt to get better model generalization by creating a model which is a stack of a pretrained bottleneck feature CNN with a custom output layer for my application, and I will feed it input images which are randomly augmented by pictographic transformations.
To start with, I will demonstrate the trivial approach of creating a basic CNN and training it on the dataset.
I create a simple CNN with the following code, using keras with a tensorflow backend.
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2Dfrom keras.layers import Dropout, Flatten, Densefrom keras.models import Sequentialmodel = Sequential()# Define model architecture.model.add(Conv2D(16, kernel_size=2, activation='relu', input_shape=(224,224,3))) # activation nonlinearity typically performed before poolingmodel.add(MaxPooling2D()) # defaults to pool_size = (2,2), stride = None = pool_sizemodel.add(Conv2D(32, kernel_size=2, activation='relu'))model.add(MaxPooling2D())model.add(Conv2D(64, kernel_size=2, activation='relu'))model.add(MaxPooling2D())model.add(GlobalAveragePooling2D())model.add(Dense(133, activation='softmax'))model.summary()
The model.summary() method prints out the following model structure:
Here I have created an 8 layer sequential neural network utilizing 3 convolutional layers paired with max pooling layers, and terminating in a fully connected layer with 133 nodes — one for each class I am trying to predict. Note in the dense layer I use a softmax activation function; the reason for this is that it has a range from 0–1, and it forces the sum of all nodes in the output layer to be 1. This allows us to interpret the output of a single node to be the model’s predicted probability that the input was of the class corresponding tot that node. In other words, if the second node in the layer has an activation value of 0.8 for a particular image, we can say that the model has predicted that the input has an 80% chance of being from the second class. Note the 19,000 model parameters — these are the weights, biases, and kernels (convolution filters) that my network is going to attempt to optimize. Now it should be evident why this process is intensely computationally demanding.
Finally, I compile this model so that it can be trained. Note that there are many loss functions and optimizers I could use here, but current common convention for multiclass image label prediction uses Adam for the optimizer, and categorical crossentropy as the loss function. I tested Adam against SGD and RMSProp, and found Adam trained much faster.
model.compile(optimizer=’adam’, loss=’categorical_crossentropy’, metrics=[‘accuracy’])
Now I have a list of tensors on which to train, validate, and test a model, and I have a fully compiled CNN. Before I begin training, I define a ModelCheckpoint object, which will serve as a hook I can use to save my model weights as I go for easy loading in the future without retraining. To train the model, I call the .fit() method of the model with my keyword arguments.
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.from_scratch.hdf5', verbose=1, save_best_only=True)model.fit(train_tensors, train_targets, validation_data=(valid_tensors, valid_targets), epochs=3, batch_size=20, callbacks=[checkpointer], verbose=2)
As you can see, I am only running this model for 3 epochs as I know it will not be a high performer due to its simplicity — this model is purely for demonstration purposes. The model training gives the following output:
The model finished training with a training accuracy of 1.77%, and a validation accuracy of 1.68%. Although it’s better than random guessing, it’s nothing to write home about.
As a side note, when training this model, we can see an immediate jump in my GPU usage! This is great — it means that the tensorflow backend is indeed using my graphics card.
The model did not achieve a reasonable accuracy on the training or validation data, evidence that it underfit the data considerably. Here I show a confusion matrix for the model’s predictions, as well as a classification report.
The model predicted one of two classes for almost every input image. It seems to be partial to basset hounds and border collies. Unfortunately, I have not created sentient AI that has a favorite dog; there are just a few more pictures in the training set of basset hounds and border collies than most other categories, and the model learned this. Due to the drastic underfitting of the model, it is not worth exploring the precision or recall it achieved at this time.
Finally, I test the model on the test dataset.
# get index of predicted dog breed for each image in test setdog_breed_predictions = [np.argmax(model.predict(np.expand_dims(tensor, axis=0))) for tensor in test_tensors]# report test accuracytest_accuracy = 100*np.sum(np.array(dog_breed_predictions)==np.argmax(test_targets, axis=1))/len(dog_breed_predictions)print('Test accuracy: %.4f%%' % test_accuracy)
This yields a test accuracy of 1.6746% — in line with what I was expecting. If I were to train the model on more epochs, it is likely that I could achieve a higher accuracy, but this model is highly simplistic, and it would be a better idea to revise my architecture. Soon I will demonstrate better methods of model building using transfer learning which can achieve much higher accuracy.
One way that I can dramatically improve performance is to utilize transfer learning — that is, I can leverage an existing CNN which has been pretrained to recognize features of general image data, and adapt it for my own purposes. Keras has a number of such pretrained models available for download and use. Each is a model which has been trained on a repository of images known as imagenet which contains millions of images distributed across 1000 categories. Models trained on imagenet are typically deep CNNs with a number of fully connected output layers which have been trained to categorize the hidden features exposed by the convolution layers into 1 of those 1000 categories. I can take one of those pretrained models and simply replace the output layers with my own fully connected layers, which I can then train to categorize each input image as one of my 133 dog breeds. It is important to note here that I am no longer training a CNN at all — I am going to freeze the weights and kernels of the convolution layers, which are already trained to recognize abstract features of an image, and only train my own custom output network. This saves an immense amount of time.
There are at least two ways I can go about this. One way would be to stitch together the pretrained network and my custom network, as outlined above. Another, even simpler way, is to feed every image in my dataset through the pretrained network, and save the outputs as arrays to then feed through my network later. The benefit of the latter method is that it saves computing time, because each training epoch I am only doing a forward pass and backprop through my own model, instead of the imagenet model and my model together. Conveniently, Udacity already fed all of their supplied training images through a few built-in CNNs, and provided the raw output, or bottleneck features, for me to simply read in.
Here I define my own fully connected network to accept bottleneck features and output 133 nodes, one for each breed. This one is for the VGG16 network, used as an example. I use different networks for my actual training which will be seen in the next section.
VGG16_model = Sequential()VGG16_model.add(GlobalAveragePooling2D(input_shape=train_VGG16.shape[1:]))VGG16_model.add(Dense(133, activation='softmax'))
A few things to note here:
I start with a GlobalAveragePooling layer — this is because the last layer of the VGG16, and in fact all of the imagenet models I test, is a convolution/pooling sequence. Global Pooling layers reduce the dimensionality of this output, and greatly reduce the training time when feeding into a Dense layer.
The input shape of the first layer in my network must be tailored to the model for which it is designed. I can do this by simply getting the shape of the bottleneck data. The first dimension is cut off of the bottleneck feature shape to allow keras to add a dimension for batch processing.
I use a softmax activation function again, for the same reasons outlined for the trivial model.
Udacity provided the bottleneck features for 4 networks: VGG19, ResNet50, InceptionV3, and Xception. The following code block reads in the bottleneck features for each model, creates a fully connected output network, and trains that network over 20 epochs. Finally, it outputs the accuracy of each model.
As is evident from the last line, all 4 models performed much better than my own trivial CNN, with the Xception model achieving a validation accuracy of 85%!
The best performers — Xception and ResNet50 — both achieved remarkable validation accuracy, but digging through the logs, we can see that their accuracy on the training data was nearly 100%. This is the trademark of overfitting. This isn’t too surprising, Xception has 22 million parameters, and ResNet50 has 23 million, meaning both models have an enormous entropic capacity and are capable of just memorizing the training data images. To combat this, I will implement some changes to my fully connected model and retrain.
I’ve added a second dense layer in the hopes that the model will be able to rely a little less on the pretrained parameters, and I’ve also augmented both fully dense layers with L2 regularization and dropout. L2 regularization penalizes the network for high individual parameter weights, and dropout randomly drops network nodes during training. Both fight overfitting by requiring the network to generalize more during training. Also note I’ve changed optimization strategies; in a real research environment, this would be done with GridSearch, which accepts lists of hyperparameters (such as optimizers with ranges of hyperparameters) but in the interest of time I experimented with a few on their own. Note that I’ve switched back to using SGD — through experimentation I’ve found that although Adam trains extremely quickly, given enough training epochs, SGD consistently surpasses Adam (a finding hinted at by this paper).
After training for 100 epochs (5 minutes):
The model achieved comparable validation accuracy to before, but the training accuracy is much lower. The low training accuracy is due to the dropout, because it is never using the full model to evaluate training inputs. I’m satisfied that this model is no longer overfitting to the same degree as before. It appears that the validation accuracy and loss have both roughly leveled out — it’s possible over another 100 epochs I could squeeze out another 1–2% accuracy, but there are more training techniques I can employ first.
Almost 83% accuracy on the testing dataset. Very similar to the validation set as hoped. Looking at the confusion matrix:
Much better than the previous one. We can see here that there are a few breeds of dogs that the model performs quite well on, and a few where it really struggles. Looking at an example of this, it becomes quite clear why.
Let’s zoom in on the outlier halfway up the y axis and at about 1/4 of the x axis.
The model consistently thinks that the 66th class is actually the 35th class. That is, it thinks that a field spaniel is actually a boykin spaniel. Here are those two breeds side by side.
Notice any similarities? Clearly, distinguishing these two breeds is an incredibly difficult task. I suspect that tweaking my model parameters would not result in a meaningful improvement in classification in this case, and in a real scenario I would train a binary classifier to differentiate between these breeds, and employ it in a classification prediction pipeline if the primary model predicted either class. But for now, I’m interested in attempting to get better performance by augmenting my training data.
In models trained on image data, there is a form of bootstrapping the training data called image augmentation, where during training I can apply random rotations, zooms, and translations to the training images. This has the effect of artificially increasing the size of the training data by altering the pixels of the training images while maintaining the integrity of the content; e.g. if I rotate the image of a corgi by 15 degrees and flip it horizontally, the image should still be recognizable as a corgi, but the model will never have seen that exact image during training. The hope is that this technique will both improve model accuracy over a great number of epochs, and also fight overfitting. In order to do this, I can no longer use the bottleneck features I was using before, and I must compile the entire model together for forward and back propagation. Also note since I still do not want to edit the parameters of the imagenet pretrained model, I will freeze those layers before training.
First, I define my dataloading pipeline:
Next, I load the imagenet model, define a custom fully connected output model, and combine them into one sequential model. I switched back to using Adam here due to the time involved in training. If I had more computational resources, it would probably be worth using SGD as before.
This model takes significantly longer to train than any of my previous models simply because each forward pass has to traverse all of the nodes of the imagenet model. Each epoch takes around 3.5 minutes to train on my GPU, as opposed to the mere seconds it took with the bottleneck features model. This exposes the computational gain we got from using bottleneck features previously.
The model achieved relatively high accuracy on the training and validation datasets extremely quickly — this is thanks to my switch to the Adam optimizer. Note the training accuracy is still below the validation accuracy — this is because I am still using dropout. Another thing to notice is the high variation in validation accuracy. This can be a symptom of a high learning rate (looking at you, Adam), or a high entropic capacity (too many parameters). It does seem to level out over time, so I am not concerned.
Looking at the classification reports for this model and the previous one, both scored .80 on both precision and recall during validation. Both also ended up with validation loss around 1, further suggesting there was no improvement. I was hoping to see a jump in accuracy due to the augmented training data, but I think that it would simply require an order of magnitude more training epochs before that improvement became evident. I suspect that changing to the SGD classifier and running for a lot more epochs would help.
I can feed the augmented model testing data in the same way that I fed it training and validation data, with a keras ImageDataGenerator:
The test accuracy is in the same ballpark as the bottleneck features model, albiet a few percent lower.
To drill into precision and recall, I perform the same analysis as before, with a confusion matrix:
What’s really interesting here is that we see the same outlier as before, though it is dimmer, suggesting this model did slightly better differentiating between the spaniels. However, there’s another bright outlier near the center of the matrix now — zooming in reveals that this model can’t differentiate between a Doberman Pinscher and a German Pinscher.
Go figure.
The last step for me is to write a function that will load a given model from scratch and accept image data as an input, and output a breed prediction. I will proceed with my augmented image model, because I believe in the future I can improve it with more training.
During the training of each of the models I tested here, I saved the parameters to .hdf5 files. Therefore, once training is complete, given that I know how to compile the model I am interested in using, I can load the best weights from my last training run on command. Then in my prediction function, I simply need to recreate the image processing steps I performed during training.
Since I have stored the model weights in an external file and I know how to recreate the model architecture, I can package said model for use anywhere, including in web or mobile applications. In fact, on the Play Store at the time of writing this post I saw that there is a dog breed identification app, which I suspect utilizes a similar model to the one I ended up with here.
github repo: https://github.com/jfreds91/DSND_t2_capstone | [
{
"code": null,
"e": 508,
"s": 171,
"text": "In this article, I will demonstrate how to use keras and tensorflow to build, train, and test a Convolutional Neural Network capable of identifying the breed of a dog in a supplied image. Success will be defined by high validation and test accuracy, with precision and recall scores differentiating between models with similar accuracy."
},
{
"code": null,
"e": 666,
"s": 508,
"text": "This is a supervised learning problem, specifically a multiclass classification problem, and as such the solution may be approached with the following steps:"
},
{
"code": null,
"e": 1119,
"s": 666,
"text": "Amass labelled data. In this case, that means compiling a repository of images with dogs of known breeds.Construct a model capable of extracting data from training images, which outputs data which may be interpreted to discern a breed of dog.Train the model on training data, validate performance during training with validation dataEvaluate performance metrics, potentially return to step 2 with edits to improve performanceTest the model on test data"
},
{
"code": null,
"e": 1225,
"s": 1119,
"text": "Amass labelled data. In this case, that means compiling a repository of images with dogs of known breeds."
},
{
"code": null,
"e": 1363,
"s": 1225,
"text": "Construct a model capable of extracting data from training images, which outputs data which may be interpreted to discern a breed of dog."
},
{
"code": null,
"e": 1455,
"s": 1363,
"text": "Train the model on training data, validate performance during training with validation data"
},
{
"code": null,
"e": 1548,
"s": 1455,
"text": "Evaluate performance metrics, potentially return to step 2 with edits to improve performance"
},
{
"code": null,
"e": 1576,
"s": 1548,
"text": "Test the model on test data"
},
{
"code": null,
"e": 1651,
"s": 1576,
"text": "Each step of course has a number of sub-steps which I will detail as I go."
},
{
"code": null,
"e": 2202,
"s": 1651,
"text": "The act of training a neural network, even a relatively simple one, can be extremely computationally expensive. Many companies use server racks of GPUs dedicated to this kind of task; I will be working on my local PC which is equipped with a GTX 1070 graphics card which I will recruit for this exercise. In order to perform this task on your local computer, there are a few steps you must take in order to define a proper programming environment, and I will detail them here. If you are not interested in the backend setup, skip to the next section."
},
{
"code": null,
"e": 2288,
"s": 2202,
"text": "First, I created a new environment in Anaconda, and installed the following packages:"
},
{
"code": null,
"e": 2303,
"s": 2288,
"text": "tensorflow-gpu"
},
{
"code": null,
"e": 2311,
"s": 2303,
"text": "jupyter"
},
{
"code": null,
"e": 2317,
"s": 2311,
"text": "glob2"
},
{
"code": null,
"e": 2330,
"s": 2317,
"text": "scikit-learn"
},
{
"code": null,
"e": 2336,
"s": 2330,
"text": "keras"
},
{
"code": null,
"e": 2347,
"s": 2336,
"text": "matplotlib"
},
{
"code": null,
"e": 2472,
"s": 2347,
"text": "opencv (This is for identifying human faces in image pipeline — not a necessary capability, but useful in some applications)"
},
{
"code": null,
"e": 2477,
"s": 2472,
"text": "tqdm"
},
{
"code": null,
"e": 2484,
"s": 2477,
"text": "pillow"
},
{
"code": null,
"e": 2492,
"s": 2484,
"text": "seaborn"
},
{
"code": null,
"e": 2869,
"s": 2492,
"text": "Next, I updated my graphics drivers. This is important because driver updates are pushed out fairly regularly, even for a card like mine which is 3 years old, and if you are using a modern version of tensorflow is it necessary to use up-to-date drivers for compatibility. In my case, drivers that were only 5 months old were incompatible with the newest version of tensorflow."
},
{
"code": null,
"e": 3102,
"s": 2869,
"text": "Finally, open a jupyter notebook from an anaconda prompt in the new environment in order to perform your work, and ensure jupyter is using the correct environment for the kernel. Tensorflow may encounter issues if you don’t do this."
},
{
"code": null,
"e": 3199,
"s": 3102,
"text": "As a sanity check, post module imports I can call the following to show available CPUs and GPUs."
},
{
"code": null,
"e": 3285,
"s": 3199,
"text": "from tensorflow.python.client import device_libprint(device_lib.list_local_devices())"
},
{
"code": null,
"e": 3315,
"s": 3285,
"text": "Success! There’s my GTX 1070."
},
{
"code": null,
"e": 3475,
"s": 3315,
"text": "Finally, I execute the following code block which edits some configuration parameters of the tensorflow backend and prevents some runtime errors in the future."
},
{
"code": null,
"e": 3674,
"s": 3475,
"text": "# tensorflow local GPU configurationgpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.8)config = tf.ConfigProto()config.gpu_options.allow_growth = Truesession = tf.Session(config=config)"
},
{
"code": null,
"e": 4098,
"s": 3674,
"text": "In my case, this was trivial, as Udacity provided me with 1.08Gb of dog images spanning 133 breeds, already in a proper file structure. Proper file structure, in the case of a classification CNN built with keras, means files are segregated by training, validation, and testing, and further segregated within these folders by dog breed. The names of each folder should be the names of the classes which you plan to identify."
},
{
"code": null,
"e": 4597,
"s": 4098,
"text": "Obviously, there are more than 133 dog breeds in the world — the American authority, the AKC, lists 190 breeds, and the world authority, the FCI, lists 360 breeds. If I wanted to increase the size of my training dataset to include more breeds or just more images of each breed, one avenue I could pursue would be to install the python Flickr API and query it for images tagged with the names of whatever breed I desired. However for the purposes of this project, I continue with this basic dataset."
},
{
"code": null,
"e": 4699,
"s": 4597,
"text": "As an initial step, I will load all of the filenames into memory for easier processing down the road."
},
{
"code": null,
"e": 5718,
"s": 4699,
"text": "# define function to load train, test, and validation datasetsdef load_dataset(path): data = load_files(path) dog_files = np.array(data['filenames']) dog_targets = np_utils.to_categorical(np.array(data['target']))#, 133) return dog_files, dog_targets# load train, test, and validation datasetstrain_files, train_targets = load_dataset('dogImages/train')valid_files, valid_targets = load_dataset('dogImages/valid')test_files, test_targets = load_dataset('dogImages/test')# load list of dog names# the [20:-1] portion simply removes the filepath and folder numberdog_names = [item[20:-1] for item in sorted(glob(\"dogImages/train/*/\"))]# print statistics about the datasetprint('There are %d total dog categories.' % len(dog_names))print('There are %s total dog images.\\n' % len(np.hstack([train_files, valid_files, test_files])))print('There are %d training dog images.' % len(train_files))print('There are %d validation dog images.' % len(valid_files))print('There are %d test dog images.'% len(test_files))"
},
{
"code": null,
"e": 5753,
"s": 5718,
"text": "which outputs the following stats:"
},
{
"code": null,
"e": 5922,
"s": 5753,
"text": "There are 133 total dog categories.There are 8351 total dog images.There are 6680 training dog images.There are 835 validation dog images.There are 836 test dog images."
},
{
"code": null,
"e": 6382,
"s": 5922,
"text": "Next, I perform a step to normalize the data by dividing every pixel in the image by 255 and format the output as a tensor — a vector which can be used by keras. Note: the following code loads thousands of files into memory as tensors. Although this is possible with a relatively small dataset, it is better practice to use a batch loading system which only loads in a small number of tensors at a time. I do this in a later step, for the last model I design."
},
{
"code": null,
"e": 7403,
"s": 6382,
"text": "# define functions for reading in image files as tensorsdef path_to_tensor(img_path, target_size=(224, 224)): # loads RGB image as PIL.Image.Image type # 299 is for xception, 224 for the other models img = image.load_img(img_path, target_size=target_size) # convert PIL.Image.Image type to 3D tensor with shape (224, 224, 3) x = image.img_to_array(img) # convert 3D tensor to 4D tensor with shape (1, (target_size,) 3) and return 4D tensor return np.expand_dims(x, axis=0)def paths_to_tensor(img_paths, target_size = (224, 224)): list_of_tensors = [path_to_tensor(img_path, target_size) for img_path in tqdm(img_paths)] return np.vstack(list_of_tensors)# run above functionsfrom PIL import ImageFile ImageFile.LOAD_TRUNCATED_IMAGES = True# pre-process the data for Kerastrain_tensors = paths_to_tensor(train_files).astype('float32')/255valid_tensors = paths_to_tensor(valid_files).astype('float32')/255test_tensors = paths_to_tensor(test_files).astype('float32')/255"
},
{
"code": null,
"e": 7648,
"s": 7403,
"text": "There are an infinite number of ways do this, some of which will work much better than others. I am going to explore 3 unique approaches, and follow them from construction through to testing and evaluation. The approaches I take are as follows:"
},
{
"code": null,
"e": 8391,
"s": 7648,
"text": "Trivial solution. I will construct and train a very simple CNN on the dataset and evaluate its performance.Transfer learning with bottleneck features. I will make use of an existing CNN which has been trained on a massive image library, and adapt it to my application by using it to transform my input images into “bottleneck features”: abstract feature representations of the images.Transfer learning with image augmentation. Similar to the bottleneck features approach, but I will attempt to get better model generalization by creating a model which is a stack of a pretrained bottleneck feature CNN with a custom output layer for my application, and I will feed it input images which are randomly augmented by pictographic transformations."
},
{
"code": null,
"e": 8499,
"s": 8391,
"text": "Trivial solution. I will construct and train a very simple CNN on the dataset and evaluate its performance."
},
{
"code": null,
"e": 8777,
"s": 8499,
"text": "Transfer learning with bottleneck features. I will make use of an existing CNN which has been trained on a massive image library, and adapt it to my application by using it to transform my input images into “bottleneck features”: abstract feature representations of the images."
},
{
"code": null,
"e": 9136,
"s": 8777,
"text": "Transfer learning with image augmentation. Similar to the bottleneck features approach, but I will attempt to get better model generalization by creating a model which is a stack of a pretrained bottleneck feature CNN with a custom output layer for my application, and I will feed it input images which are randomly augmented by pictographic transformations."
},
{
"code": null,
"e": 9247,
"s": 9136,
"text": "To start with, I will demonstrate the trivial approach of creating a basic CNN and training it on the dataset."
},
{
"code": null,
"e": 9333,
"s": 9247,
"text": "I create a simple CNN with the following code, using keras with a tensorflow backend."
},
{
"code": null,
"e": 10012,
"s": 9333,
"text": "from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2Dfrom keras.layers import Dropout, Flatten, Densefrom keras.models import Sequentialmodel = Sequential()# Define model architecture.model.add(Conv2D(16, kernel_size=2, activation='relu', input_shape=(224,224,3))) # activation nonlinearity typically performed before poolingmodel.add(MaxPooling2D()) # defaults to pool_size = (2,2), stride = None = pool_sizemodel.add(Conv2D(32, kernel_size=2, activation='relu'))model.add(MaxPooling2D())model.add(Conv2D(64, kernel_size=2, activation='relu'))model.add(MaxPooling2D())model.add(GlobalAveragePooling2D())model.add(Dense(133, activation='softmax'))model.summary()"
},
{
"code": null,
"e": 10081,
"s": 10012,
"text": "The model.summary() method prints out the following model structure:"
},
{
"code": null,
"e": 11080,
"s": 10081,
"text": "Here I have created an 8 layer sequential neural network utilizing 3 convolutional layers paired with max pooling layers, and terminating in a fully connected layer with 133 nodes — one for each class I am trying to predict. Note in the dense layer I use a softmax activation function; the reason for this is that it has a range from 0–1, and it forces the sum of all nodes in the output layer to be 1. This allows us to interpret the output of a single node to be the model’s predicted probability that the input was of the class corresponding tot that node. In other words, if the second node in the layer has an activation value of 0.8 for a particular image, we can say that the model has predicted that the input has an 80% chance of being from the second class. Note the 19,000 model parameters — these are the weights, biases, and kernels (convolution filters) that my network is going to attempt to optimize. Now it should be evident why this process is intensely computationally demanding."
},
{
"code": null,
"e": 11433,
"s": 11080,
"text": "Finally, I compile this model so that it can be trained. Note that there are many loss functions and optimizers I could use here, but current common convention for multiclass image label prediction uses Adam for the optimizer, and categorical crossentropy as the loss function. I tested Adam against SGD and RMSProp, and found Adam trained much faster."
},
{
"code": null,
"e": 11520,
"s": 11433,
"text": "model.compile(optimizer=’adam’, loss=’categorical_crossentropy’, metrics=[‘accuracy’])"
},
{
"code": null,
"e": 11895,
"s": 11520,
"text": "Now I have a list of tensors on which to train, validate, and test a model, and I have a fully compiled CNN. Before I begin training, I define a ModelCheckpoint object, which will serve as a hook I can use to save my model weights as I go for easy loading in the future without retraining. To train the model, I call the .fit() method of the model with my keyword arguments."
},
{
"code": null,
"e": 12182,
"s": 11895,
"text": "checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.from_scratch.hdf5', verbose=1, save_best_only=True)model.fit(train_tensors, train_targets, validation_data=(valid_tensors, valid_targets), epochs=3, batch_size=20, callbacks=[checkpointer], verbose=2)"
},
{
"code": null,
"e": 12402,
"s": 12182,
"text": "As you can see, I am only running this model for 3 epochs as I know it will not be a high performer due to its simplicity — this model is purely for demonstration purposes. The model training gives the following output:"
},
{
"code": null,
"e": 12578,
"s": 12402,
"text": "The model finished training with a training accuracy of 1.77%, and a validation accuracy of 1.68%. Although it’s better than random guessing, it’s nothing to write home about."
},
{
"code": null,
"e": 12753,
"s": 12578,
"text": "As a side note, when training this model, we can see an immediate jump in my GPU usage! This is great — it means that the tensorflow backend is indeed using my graphics card."
},
{
"code": null,
"e": 12982,
"s": 12753,
"text": "The model did not achieve a reasonable accuracy on the training or validation data, evidence that it underfit the data considerably. Here I show a confusion matrix for the model’s predictions, as well as a classification report."
},
{
"code": null,
"e": 13451,
"s": 12982,
"text": "The model predicted one of two classes for almost every input image. It seems to be partial to basset hounds and border collies. Unfortunately, I have not created sentient AI that has a favorite dog; there are just a few more pictures in the training set of basset hounds and border collies than most other categories, and the model learned this. Due to the drastic underfitting of the model, it is not worth exploring the precision or recall it achieved at this time."
},
{
"code": null,
"e": 13498,
"s": 13451,
"text": "Finally, I test the model on the test dataset."
},
{
"code": null,
"e": 13856,
"s": 13498,
"text": "# get index of predicted dog breed for each image in test setdog_breed_predictions = [np.argmax(model.predict(np.expand_dims(tensor, axis=0))) for tensor in test_tensors]# report test accuracytest_accuracy = 100*np.sum(np.array(dog_breed_predictions)==np.argmax(test_targets, axis=1))/len(dog_breed_predictions)print('Test accuracy: %.4f%%' % test_accuracy)"
},
{
"code": null,
"e": 14245,
"s": 13856,
"text": "This yields a test accuracy of 1.6746% — in line with what I was expecting. If I were to train the model on more epochs, it is likely that I could achieve a higher accuracy, but this model is highly simplistic, and it would be a better idea to revise my architecture. Soon I will demonstrate better methods of model building using transfer learning which can achieve much higher accuracy."
},
{
"code": null,
"e": 15425,
"s": 14245,
"text": "One way that I can dramatically improve performance is to utilize transfer learning — that is, I can leverage an existing CNN which has been pretrained to recognize features of general image data, and adapt it for my own purposes. Keras has a number of such pretrained models available for download and use. Each is a model which has been trained on a repository of images known as imagenet which contains millions of images distributed across 1000 categories. Models trained on imagenet are typically deep CNNs with a number of fully connected output layers which have been trained to categorize the hidden features exposed by the convolution layers into 1 of those 1000 categories. I can take one of those pretrained models and simply replace the output layers with my own fully connected layers, which I can then train to categorize each input image as one of my 133 dog breeds. It is important to note here that I am no longer training a CNN at all — I am going to freeze the weights and kernels of the convolution layers, which are already trained to recognize abstract features of an image, and only train my own custom output network. This saves an immense amount of time."
},
{
"code": null,
"e": 16134,
"s": 15425,
"text": "There are at least two ways I can go about this. One way would be to stitch together the pretrained network and my custom network, as outlined above. Another, even simpler way, is to feed every image in my dataset through the pretrained network, and save the outputs as arrays to then feed through my network later. The benefit of the latter method is that it saves computing time, because each training epoch I am only doing a forward pass and backprop through my own model, instead of the imagenet model and my model together. Conveniently, Udacity already fed all of their supplied training images through a few built-in CNNs, and provided the raw output, or bottleneck features, for me to simply read in."
},
{
"code": null,
"e": 16394,
"s": 16134,
"text": "Here I define my own fully connected network to accept bottleneck features and output 133 nodes, one for each breed. This one is for the VGG16 network, used as an example. I use different networks for my actual training which will be seen in the next section."
},
{
"code": null,
"e": 16544,
"s": 16394,
"text": "VGG16_model = Sequential()VGG16_model.add(GlobalAveragePooling2D(input_shape=train_VGG16.shape[1:]))VGG16_model.add(Dense(133, activation='softmax'))"
},
{
"code": null,
"e": 16571,
"s": 16544,
"text": "A few things to note here:"
},
{
"code": null,
"e": 16876,
"s": 16571,
"text": "I start with a GlobalAveragePooling layer — this is because the last layer of the VGG16, and in fact all of the imagenet models I test, is a convolution/pooling sequence. Global Pooling layers reduce the dimensionality of this output, and greatly reduce the training time when feeding into a Dense layer."
},
{
"code": null,
"e": 17166,
"s": 16876,
"text": "The input shape of the first layer in my network must be tailored to the model for which it is designed. I can do this by simply getting the shape of the bottleneck data. The first dimension is cut off of the bottleneck feature shape to allow keras to add a dimension for batch processing."
},
{
"code": null,
"e": 17262,
"s": 17166,
"text": "I use a softmax activation function again, for the same reasons outlined for the trivial model."
},
{
"code": null,
"e": 17567,
"s": 17262,
"text": "Udacity provided the bottleneck features for 4 networks: VGG19, ResNet50, InceptionV3, and Xception. The following code block reads in the bottleneck features for each model, creates a fully connected output network, and trains that network over 20 epochs. Finally, it outputs the accuracy of each model."
},
{
"code": null,
"e": 17725,
"s": 17567,
"text": "As is evident from the last line, all 4 models performed much better than my own trivial CNN, with the Xception model achieving a validation accuracy of 85%!"
},
{
"code": null,
"e": 18249,
"s": 17725,
"text": "The best performers — Xception and ResNet50 — both achieved remarkable validation accuracy, but digging through the logs, we can see that their accuracy on the training data was nearly 100%. This is the trademark of overfitting. This isn’t too surprising, Xception has 22 million parameters, and ResNet50 has 23 million, meaning both models have an enormous entropic capacity and are capable of just memorizing the training data images. To combat this, I will implement some changes to my fully connected model and retrain."
},
{
"code": null,
"e": 19177,
"s": 18249,
"text": "I’ve added a second dense layer in the hopes that the model will be able to rely a little less on the pretrained parameters, and I’ve also augmented both fully dense layers with L2 regularization and dropout. L2 regularization penalizes the network for high individual parameter weights, and dropout randomly drops network nodes during training. Both fight overfitting by requiring the network to generalize more during training. Also note I’ve changed optimization strategies; in a real research environment, this would be done with GridSearch, which accepts lists of hyperparameters (such as optimizers with ranges of hyperparameters) but in the interest of time I experimented with a few on their own. Note that I’ve switched back to using SGD — through experimentation I’ve found that although Adam trains extremely quickly, given enough training epochs, SGD consistently surpasses Adam (a finding hinted at by this paper)."
},
{
"code": null,
"e": 19220,
"s": 19177,
"text": "After training for 100 epochs (5 minutes):"
},
{
"code": null,
"e": 19747,
"s": 19220,
"text": "The model achieved comparable validation accuracy to before, but the training accuracy is much lower. The low training accuracy is due to the dropout, because it is never using the full model to evaluate training inputs. I’m satisfied that this model is no longer overfitting to the same degree as before. It appears that the validation accuracy and loss have both roughly leveled out — it’s possible over another 100 epochs I could squeeze out another 1–2% accuracy, but there are more training techniques I can employ first."
},
{
"code": null,
"e": 19869,
"s": 19747,
"text": "Almost 83% accuracy on the testing dataset. Very similar to the validation set as hoped. Looking at the confusion matrix:"
},
{
"code": null,
"e": 20091,
"s": 19869,
"text": "Much better than the previous one. We can see here that there are a few breeds of dogs that the model performs quite well on, and a few where it really struggles. Looking at an example of this, it becomes quite clear why."
},
{
"code": null,
"e": 20174,
"s": 20091,
"text": "Let’s zoom in on the outlier halfway up the y axis and at about 1/4 of the x axis."
},
{
"code": null,
"e": 20362,
"s": 20174,
"text": "The model consistently thinks that the 66th class is actually the 35th class. That is, it thinks that a field spaniel is actually a boykin spaniel. Here are those two breeds side by side."
},
{
"code": null,
"e": 20877,
"s": 20362,
"text": "Notice any similarities? Clearly, distinguishing these two breeds is an incredibly difficult task. I suspect that tweaking my model parameters would not result in a meaningful improvement in classification in this case, and in a real scenario I would train a binary classifier to differentiate between these breeds, and employ it in a classification prediction pipeline if the primary model predicted either class. But for now, I’m interested in attempting to get better performance by augmenting my training data."
},
{
"code": null,
"e": 21882,
"s": 20877,
"text": "In models trained on image data, there is a form of bootstrapping the training data called image augmentation, where during training I can apply random rotations, zooms, and translations to the training images. This has the effect of artificially increasing the size of the training data by altering the pixels of the training images while maintaining the integrity of the content; e.g. if I rotate the image of a corgi by 15 degrees and flip it horizontally, the image should still be recognizable as a corgi, but the model will never have seen that exact image during training. The hope is that this technique will both improve model accuracy over a great number of epochs, and also fight overfitting. In order to do this, I can no longer use the bottleneck features I was using before, and I must compile the entire model together for forward and back propagation. Also note since I still do not want to edit the parameters of the imagenet pretrained model, I will freeze those layers before training."
},
{
"code": null,
"e": 21923,
"s": 21882,
"text": "First, I define my dataloading pipeline:"
},
{
"code": null,
"e": 22206,
"s": 21923,
"text": "Next, I load the imagenet model, define a custom fully connected output model, and combine them into one sequential model. I switched back to using Adam here due to the time involved in training. If I had more computational resources, it would probably be worth using SGD as before."
},
{
"code": null,
"e": 22590,
"s": 22206,
"text": "This model takes significantly longer to train than any of my previous models simply because each forward pass has to traverse all of the nodes of the imagenet model. Each epoch takes around 3.5 minutes to train on my GPU, as opposed to the mere seconds it took with the bottleneck features model. This exposes the computational gain we got from using bottleneck features previously."
},
{
"code": null,
"e": 23106,
"s": 22590,
"text": "The model achieved relatively high accuracy on the training and validation datasets extremely quickly — this is thanks to my switch to the Adam optimizer. Note the training accuracy is still below the validation accuracy — this is because I am still using dropout. Another thing to notice is the high variation in validation accuracy. This can be a symptom of a high learning rate (looking at you, Adam), or a high entropic capacity (too many parameters). It does seem to level out over time, so I am not concerned."
},
{
"code": null,
"e": 23631,
"s": 23106,
"text": "Looking at the classification reports for this model and the previous one, both scored .80 on both precision and recall during validation. Both also ended up with validation loss around 1, further suggesting there was no improvement. I was hoping to see a jump in accuracy due to the augmented training data, but I think that it would simply require an order of magnitude more training epochs before that improvement became evident. I suspect that changing to the SGD classifier and running for a lot more epochs would help."
},
{
"code": null,
"e": 23768,
"s": 23631,
"text": "I can feed the augmented model testing data in the same way that I fed it training and validation data, with a keras ImageDataGenerator:"
},
{
"code": null,
"e": 23872,
"s": 23768,
"text": "The test accuracy is in the same ballpark as the bottleneck features model, albiet a few percent lower."
},
{
"code": null,
"e": 23972,
"s": 23872,
"text": "To drill into precision and recall, I perform the same analysis as before, with a confusion matrix:"
},
{
"code": null,
"e": 24329,
"s": 23972,
"text": "What’s really interesting here is that we see the same outlier as before, though it is dimmer, suggesting this model did slightly better differentiating between the spaniels. However, there’s another bright outlier near the center of the matrix now — zooming in reveals that this model can’t differentiate between a Doberman Pinscher and a German Pinscher."
},
{
"code": null,
"e": 24340,
"s": 24329,
"text": "Go figure."
},
{
"code": null,
"e": 24607,
"s": 24340,
"text": "The last step for me is to write a function that will load a given model from scratch and accept image data as an input, and output a breed prediction. I will proceed with my augmented image model, because I believe in the future I can improve it with more training."
},
{
"code": null,
"e": 24990,
"s": 24607,
"text": "During the training of each of the models I tested here, I saved the parameters to .hdf5 files. Therefore, once training is complete, given that I know how to compile the model I am interested in using, I can load the best weights from my last training run on command. Then in my prediction function, I simply need to recreate the image processing steps I performed during training."
},
{
"code": null,
"e": 25369,
"s": 24990,
"text": "Since I have stored the model weights in an external file and I know how to recreate the model architecture, I can package said model for use anywhere, including in web or mobile applications. In fact, on the Play Store at the time of writing this post I saw that there is a dog breed identification app, which I suspect utilizes a similar model to the one I ended up with here."
}
] |
Creating a Transparent window in Python Tkinter | Python is the most popular language for developing and creating functional and
desktop applications. It has a rich library of different modules and functions which
provides extensibility and accessibility to create and develop applications.
Tkinter is the most commonly used library for creating GUI-based applications. It
has features like adding widgets and other necessary attributes.
Let us suppose that we want to create a transparent window using tkinter. To create the transparent window, we can use the attributes property and define the opacity value.
#Importing the tkinter library
from tkinter import *
#Create an instance of tkinter frame
win= Tk()
#Define the size of the window or frame
win.geometry("700x400")
#To Make it transparent use alpha property to define the opacity of
the frame
win.attributes('-alpha', 0.3)
win.mainloop()
Running the above code will generate the output and will show a transparent
window. | [
{
"code": null,
"e": 1303,
"s": 1062,
"text": "Python is the most popular language for developing and creating functional and\ndesktop applications. It has a rich library of different modules and functions which\nprovides extensibility and accessibility to create and develop applications."
},
{
"code": null,
"e": 1450,
"s": 1303,
"text": "Tkinter is the most commonly used library for creating GUI-based applications. It\nhas features like adding widgets and other necessary attributes."
},
{
"code": null,
"e": 1623,
"s": 1450,
"text": "Let us suppose that we want to create a transparent window using tkinter. To create the transparent window, we can use the attributes property and define the opacity value."
},
{
"code": null,
"e": 1913,
"s": 1623,
"text": "#Importing the tkinter library\nfrom tkinter import *\n\n#Create an instance of tkinter frame\nwin= Tk()\n\n#Define the size of the window or frame\nwin.geometry(\"700x400\")\n\n#To Make it transparent use alpha property to define the opacity of\nthe frame\nwin.attributes('-alpha', 0.3)\nwin.mainloop()"
},
{
"code": null,
"e": 1997,
"s": 1913,
"text": "Running the above code will generate the output and will show a transparent\nwindow."
}
] |
Deploy a machine learning model using flask | by Hemang Vyas | Towards Data Science | As a beginner in machine learning, it might be easy for anyone to get enough resources about all the algorithms for machine learning and deep learning but when I started to look for references to deploy ML model to production I did not find really any good resources which could help me to deploy my model as I am very new to this field. So, when I succeeded to deploy my model using Flask as an API, I decided to write an article to help others to simply deploy their model. I hope it helps:)
In this article, we are going to use simple linear regression algorithm with scikit-learn for simplicity, we will use Flask as it is a very light web framework. We will create three files,
model.pyserver.pyrequest.py
model.py
server.py
request.py
In a model.py file, we will develop and train our model, in a server.py, we will code to handle POST requests and return the results and finally in the request.py, we will send requests with the features to the server and receive the results.
model.py
model.py
As I mentioned above, in this file we will develop our ML model and train it. We will predict the salary of an employee based on his/her experience in the field. You can find the dataset here.
import numpy as npimport pandas as pdfrom sklearn.model_selection import train_test_splitfrom sklearn.linear_model import LinearRegressionimport pickleimport requestsimport json
Importing the libraries that we are going to use to develop our model. numpy and pandas to manipulate the matrices and data respectively, sklearn.model_selection for splitting data into train and test set and sklearn.linear_model to train our model using LinearRegression. pickle to save our trained model to the disk, requests to send requests to the server and json to print the result in our terminal.
dataset = pd.read_csv('Salary_Data.csv')X = dataset.iloc[:, :-1].valuesy = dataset.iloc[:, 1].values
We have imported the dataset using pandas and separated the features and label from the dataset.
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.33, random_state = 0)
In this section, we have split our data into train and test size of 0.67 and 0.33 respectively using train_test_split from sklearn.
regressor = LinearRegression()regressor.fit(X_train, y_train)y_pred = regressor.predict(X_test)
The object is instantiated as a regressor of the class LinearRegression() and trained using X_train and y_train. Latter the predicted results are stored in the y_pred.
pickle.dump(regressor, open('model.pkl','wb'))
We will save our trained model to the disk using the pickle library. Pickle is used to serializing and de-serializing a Python object structure. In which python object is converted into the byte stream. dump() method dumps the object into the file specified in the arguments.
In our case, we want to save our model so that it can be used by the server. So we will save our object regressor to the file named model.pkl.
We can again load the model by the following method,
model = pickle.load(open('model.pkl','rb'))print(model.predict([[1.8]]))
pickle.load() method loads the method and saves the deserialized bytes to model. Predictions can be done using model.predict().
For example, we can predict the salary of the employee who has experience of 1.8 years.
Here, our model.py is ready to train and save the model. The whole code of model.py is as follows.
# Importing the librariesimport numpy as npimport pandas as pdfrom sklearn.model_selection import train_test_splitfrom sklearn.linear_model import LinearRegressionimport pickleimport requestsimport json# Importing the datasetdataset = pd.read_csv('Salary_Data.csv')X = dataset.iloc[:, :-1].valuesy = dataset.iloc[:, 1].values# Splitting the dataset into the Training set and Test setX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 1/3, random_state = 0)# Fitting Simple Linear Regression to the Training setregressor = LinearRegression()regressor.fit(X_train, y_train)# Predicting the Test set resultsy_pred = regressor.predict(X_test)# Saving model to diskpickle.dump(regressor, open('model.pkl','wb'))# Loading model to compare the resultsmodel = pickle.load(open('model.pkl','rb'))print(model.predict([[1.8]]))
2. server.py
In this file, we will use the flask web framework to handle the POST requests that we will get from the request.py.
Importing the methods and libraries that we are going to use in the code.
import numpy as npfrom flask import Flask, request, jsonifyimport pickle
Here we have imported numpy to create the array of requested data, pickle to load our trained model to predict.
In the following section of the code, we have created the instance of the Flask() and loaded the model into the model.
app = Flask(__name__)model = pickle.load(open('model.pkl','rb'))
Here, we have bounded /api with the method predict(). In which predict method gets the data from the json passed by the requestor. model.predict() method takes input from the json and converts it into 2D numpy array the results are stored into the variable named output and we return this variable after converting it into the json object using flasks jsonify() method.
@app.route('/api',methods=['POST'])def predict(): data = request.get_json(force=True) prediction = model.predict([[np.array(data['exp'])]]) output = prediction[0] return jsonify(output)
Finally, we will run our server by following code section. Here I have used port 5000 and have set debug=True since if we get any error we can debug it and solve it.
if __name__ == '__main__': app.run(port=5000, debug=True)
Here, our server is ready to serve the requests. Here is the whole code of the server.py.
# Import librariesimport numpy as npfrom flask import Flask, request, jsonifyimport pickleapp = Flask(__name__)# Load the modelmodel = pickle.load(open('model.pkl','rb'))@app.route('/api',methods=['POST'])def predict(): # Get the data from the POST request. data = request.get_json(force=True) # Make prediction using model loaded from disk as per the data. prediction = model.predict([[np.array(data['exp'])]]) # Take the first value of prediction output = prediction[0] return jsonify(output)if __name__ == '__main__': app.run(port=5000, debug=True)
3. request.py
As I mentioned earlier that request.py is going to request the server for the predictions.
Here is the whole code to make a request to the server.
import requestsurl = 'http://localhost:5000/api'r = requests.post(url,json={'exp':1.8,})print(r.json())
We have used requests library to make post requests. requests.post() takes URL and the data to be passed in the POST request and the returned results from the servers are stored into the variable r and printed by r.json().
We have created three files model.py, server.py and request.py to train and save a model, to handle the request, to make a request to the server respectively.
After coding all of these files, the sequence to execute the files should be model.py, server.py(in a separate terminal) and at the end request.py.
You can compare the results of prediction with a model.py as we printing the result at the end of the file.
You can find all the coding in my Github repository, flask-salary-predictor.
Don’t hesitate to flow your ideas in the comment section below.
Thank you :) | [
{
"code": null,
"e": 666,
"s": 172,
"text": "As a beginner in machine learning, it might be easy for anyone to get enough resources about all the algorithms for machine learning and deep learning but when I started to look for references to deploy ML model to production I did not find really any good resources which could help me to deploy my model as I am very new to this field. So, when I succeeded to deploy my model using Flask as an API, I decided to write an article to help others to simply deploy their model. I hope it helps:)"
},
{
"code": null,
"e": 855,
"s": 666,
"text": "In this article, we are going to use simple linear regression algorithm with scikit-learn for simplicity, we will use Flask as it is a very light web framework. We will create three files,"
},
{
"code": null,
"e": 883,
"s": 855,
"text": "model.pyserver.pyrequest.py"
},
{
"code": null,
"e": 892,
"s": 883,
"text": "model.py"
},
{
"code": null,
"e": 902,
"s": 892,
"text": "server.py"
},
{
"code": null,
"e": 913,
"s": 902,
"text": "request.py"
},
{
"code": null,
"e": 1156,
"s": 913,
"text": "In a model.py file, we will develop and train our model, in a server.py, we will code to handle POST requests and return the results and finally in the request.py, we will send requests with the features to the server and receive the results."
},
{
"code": null,
"e": 1165,
"s": 1156,
"text": "model.py"
},
{
"code": null,
"e": 1174,
"s": 1165,
"text": "model.py"
},
{
"code": null,
"e": 1367,
"s": 1174,
"text": "As I mentioned above, in this file we will develop our ML model and train it. We will predict the salary of an employee based on his/her experience in the field. You can find the dataset here."
},
{
"code": null,
"e": 1545,
"s": 1367,
"text": "import numpy as npimport pandas as pdfrom sklearn.model_selection import train_test_splitfrom sklearn.linear_model import LinearRegressionimport pickleimport requestsimport json"
},
{
"code": null,
"e": 1950,
"s": 1545,
"text": "Importing the libraries that we are going to use to develop our model. numpy and pandas to manipulate the matrices and data respectively, sklearn.model_selection for splitting data into train and test set and sklearn.linear_model to train our model using LinearRegression. pickle to save our trained model to the disk, requests to send requests to the server and json to print the result in our terminal."
},
{
"code": null,
"e": 2051,
"s": 1950,
"text": "dataset = pd.read_csv('Salary_Data.csv')X = dataset.iloc[:, :-1].valuesy = dataset.iloc[:, 1].values"
},
{
"code": null,
"e": 2148,
"s": 2051,
"text": "We have imported the dataset using pandas and separated the features and label from the dataset."
},
{
"code": null,
"e": 2242,
"s": 2148,
"text": "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.33, random_state = 0)"
},
{
"code": null,
"e": 2374,
"s": 2242,
"text": "In this section, we have split our data into train and test size of 0.67 and 0.33 respectively using train_test_split from sklearn."
},
{
"code": null,
"e": 2470,
"s": 2374,
"text": "regressor = LinearRegression()regressor.fit(X_train, y_train)y_pred = regressor.predict(X_test)"
},
{
"code": null,
"e": 2638,
"s": 2470,
"text": "The object is instantiated as a regressor of the class LinearRegression() and trained using X_train and y_train. Latter the predicted results are stored in the y_pred."
},
{
"code": null,
"e": 2685,
"s": 2638,
"text": "pickle.dump(regressor, open('model.pkl','wb'))"
},
{
"code": null,
"e": 2961,
"s": 2685,
"text": "We will save our trained model to the disk using the pickle library. Pickle is used to serializing and de-serializing a Python object structure. In which python object is converted into the byte stream. dump() method dumps the object into the file specified in the arguments."
},
{
"code": null,
"e": 3104,
"s": 2961,
"text": "In our case, we want to save our model so that it can be used by the server. So we will save our object regressor to the file named model.pkl."
},
{
"code": null,
"e": 3157,
"s": 3104,
"text": "We can again load the model by the following method,"
},
{
"code": null,
"e": 3230,
"s": 3157,
"text": "model = pickle.load(open('model.pkl','rb'))print(model.predict([[1.8]]))"
},
{
"code": null,
"e": 3358,
"s": 3230,
"text": "pickle.load() method loads the method and saves the deserialized bytes to model. Predictions can be done using model.predict()."
},
{
"code": null,
"e": 3446,
"s": 3358,
"text": "For example, we can predict the salary of the employee who has experience of 1.8 years."
},
{
"code": null,
"e": 3545,
"s": 3446,
"text": "Here, our model.py is ready to train and save the model. The whole code of model.py is as follows."
},
{
"code": null,
"e": 4381,
"s": 3545,
"text": "# Importing the librariesimport numpy as npimport pandas as pdfrom sklearn.model_selection import train_test_splitfrom sklearn.linear_model import LinearRegressionimport pickleimport requestsimport json# Importing the datasetdataset = pd.read_csv('Salary_Data.csv')X = dataset.iloc[:, :-1].valuesy = dataset.iloc[:, 1].values# Splitting the dataset into the Training set and Test setX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 1/3, random_state = 0)# Fitting Simple Linear Regression to the Training setregressor = LinearRegression()regressor.fit(X_train, y_train)# Predicting the Test set resultsy_pred = regressor.predict(X_test)# Saving model to diskpickle.dump(regressor, open('model.pkl','wb'))# Loading model to compare the resultsmodel = pickle.load(open('model.pkl','rb'))print(model.predict([[1.8]]))"
},
{
"code": null,
"e": 4394,
"s": 4381,
"text": "2. server.py"
},
{
"code": null,
"e": 4510,
"s": 4394,
"text": "In this file, we will use the flask web framework to handle the POST requests that we will get from the request.py."
},
{
"code": null,
"e": 4584,
"s": 4510,
"text": "Importing the methods and libraries that we are going to use in the code."
},
{
"code": null,
"e": 4657,
"s": 4584,
"text": "import numpy as npfrom flask import Flask, request, jsonifyimport pickle"
},
{
"code": null,
"e": 4769,
"s": 4657,
"text": "Here we have imported numpy to create the array of requested data, pickle to load our trained model to predict."
},
{
"code": null,
"e": 4888,
"s": 4769,
"text": "In the following section of the code, we have created the instance of the Flask() and loaded the model into the model."
},
{
"code": null,
"e": 4953,
"s": 4888,
"text": "app = Flask(__name__)model = pickle.load(open('model.pkl','rb'))"
},
{
"code": null,
"e": 5323,
"s": 4953,
"text": "Here, we have bounded /api with the method predict(). In which predict method gets the data from the json passed by the requestor. model.predict() method takes input from the json and converts it into 2D numpy array the results are stored into the variable named output and we return this variable after converting it into the json object using flasks jsonify() method."
},
{
"code": null,
"e": 5521,
"s": 5323,
"text": "@app.route('/api',methods=['POST'])def predict(): data = request.get_json(force=True) prediction = model.predict([[np.array(data['exp'])]]) output = prediction[0] return jsonify(output)"
},
{
"code": null,
"e": 5687,
"s": 5521,
"text": "Finally, we will run our server by following code section. Here I have used port 5000 and have set debug=True since if we get any error we can debug it and solve it."
},
{
"code": null,
"e": 5748,
"s": 5687,
"text": "if __name__ == '__main__': app.run(port=5000, debug=True)"
},
{
"code": null,
"e": 5838,
"s": 5748,
"text": "Here, our server is ready to serve the requests. Here is the whole code of the server.py."
},
{
"code": null,
"e": 6414,
"s": 5838,
"text": "# Import librariesimport numpy as npfrom flask import Flask, request, jsonifyimport pickleapp = Flask(__name__)# Load the modelmodel = pickle.load(open('model.pkl','rb'))@app.route('/api',methods=['POST'])def predict(): # Get the data from the POST request. data = request.get_json(force=True) # Make prediction using model loaded from disk as per the data. prediction = model.predict([[np.array(data['exp'])]]) # Take the first value of prediction output = prediction[0] return jsonify(output)if __name__ == '__main__': app.run(port=5000, debug=True)"
},
{
"code": null,
"e": 6428,
"s": 6414,
"text": "3. request.py"
},
{
"code": null,
"e": 6519,
"s": 6428,
"text": "As I mentioned earlier that request.py is going to request the server for the predictions."
},
{
"code": null,
"e": 6575,
"s": 6519,
"text": "Here is the whole code to make a request to the server."
},
{
"code": null,
"e": 6679,
"s": 6575,
"text": "import requestsurl = 'http://localhost:5000/api'r = requests.post(url,json={'exp':1.8,})print(r.json())"
},
{
"code": null,
"e": 6902,
"s": 6679,
"text": "We have used requests library to make post requests. requests.post() takes URL and the data to be passed in the POST request and the returned results from the servers are stored into the variable r and printed by r.json()."
},
{
"code": null,
"e": 7061,
"s": 6902,
"text": "We have created three files model.py, server.py and request.py to train and save a model, to handle the request, to make a request to the server respectively."
},
{
"code": null,
"e": 7209,
"s": 7061,
"text": "After coding all of these files, the sequence to execute the files should be model.py, server.py(in a separate terminal) and at the end request.py."
},
{
"code": null,
"e": 7317,
"s": 7209,
"text": "You can compare the results of prediction with a model.py as we printing the result at the end of the file."
},
{
"code": null,
"e": 7394,
"s": 7317,
"text": "You can find all the coding in my Github repository, flask-salary-predictor."
},
{
"code": null,
"e": 7458,
"s": 7394,
"text": "Don’t hesitate to flow your ideas in the comment section below."
}
] |
Distance of nearest cell having 1 | Practice | GeeksforGeeks | Given a binary grid. Find the distance of nearest 1 in the grid for each cell.
The distance is calculated as |i1 – i2| + |j1 – j2|, where i1, j1 are the row number and column number of the current cell and i2, j2 are the row number and column number of the nearest cell having value 1.
Example 1:
Input: grid = {{0,1,1,0},{1,1,0,0},{0,0,1,1}}
Output: {{1,0,0,1},{0,0,1,1},{1,1,0,0}}
Explanation: The grid is-
0 1 1 0
1 1 0 0
0 0 1 1
0's at (0,0), (0,3), (1,2), (1,3), (2,0) and
(2,1) are at a distance of 1 from 1's at (0,1),
(0,2), (0,2), (2,3), (1,0) and (1,1)
respectively.
Example 2:
Input: grid = {{1,0,1},{1,1,0},{1,0,0}}
Output: {{0,1,0},{0,0,1},{0,1,2}}
Explanation: The grid is-
1 0 1
1 1 0
1 0 0
0's at (0,1), (1,2), (2,1) and (2,2) are at a
distance of 1, 1, 1 and 2 from 1's at (0,0),
(0,2), (2,0) and (1,1) respectively.
Yout Task:
You don't need to read or print anything, Your task is to complete the function nearest() which takes grid as input parameter and returns a matrix of same dimensions where the value at index (i, j) in the resultant matrix signifies the minimum distance of 1 in the matrix from grid[i][j].
Expected Time Complexity: O(n*m)
Expected Auxiliary Space: O(n*m)
Constraints:
1 ≤ n, m ≤ 500
0
shilsoumyadip1 week ago
vector<vector<int>>nearest(vector<vector<int>>grid){ // Code here int row = grid.size(); int column = grid[0].size(); queue<pair<int,int>> q ; vector<vector<int>>ans(row,vector<int>(column,INT_MAX)); for(int i=0;i<row;i++) { for(int j=0;j<column;j++) { if(grid[i][j] == 1) { q.push({i,j}); ans[i][j] = 0; } } } while(!q.empty()) { int i = q.front().first; int j = q.front().second; if( (i - 1) >= 0 and ans[i][j] + 1 < ans[i-1][j]) { ans[i-1][j] = ans[i][j] + 1 ; q.push({i-1,j}); } if((j - 1) >= 0 and ans[i][j] + 1 < ans[i][j-1]) { ans[i][j-1] = ans[i][j] + 1 ; q.push({i,j-1}); } if((i + 1) < row and ans[i][j] + 1 < ans[i+1][j]) { ans[i+1][j] = ans[i][j] + 1 ; q.push({i+1,j}); } if((j + 1) < column and ans[i][j] + 1 < ans[i][j+1]) { ans[i][j+1] = ans[i][j] + 1 ; q.push({i,j+1}); } q.pop(); } return ans;}};
+2
saurabhsathe12341 month ago
C++ : 0.6ms
Watch this video for concept ,
https://www.youtube.com/watch?v=wtRT9G42g4g
bool check(int i , int j ,int n , int m)
{
if(i < 0 || j < 0 || i >= n || j >= m )
return false ;
return true;
}
vector<vector<int>>nearest(vector<vector<int>>grid)
{
int n = grid.size();
int m = grid[0].size();
queue<pair<int,int>> q ;
vector<vector<int>>ans(n,vector<int>(m,-1));
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(grid[i][j] == 1)
{
q.push({i,j});
ans[i][j] = 0;
}
}
}
while(!q.empty())
{
int i = q.front().first;
int j = q.front().second;
q.pop();
if(check(i-1,j,n,m) && ans[i-1][j] == -1)
{
ans[i-1][j] = ans[i][j] + 1 ;
q.push({i-1,j});
}
if(check(i,j-1,n,m) && ans[i][j-1] == -1)
{
ans[i][j-1] = ans[i][j] + 1 ;
q.push({i,j-1});
}
if(check(i,j+1,n,m) && ans[i][j+1] == -1)
{
ans[i][j+1] = ans[i][j] + 1 ;
q.push({i,j+1});
}
if(check(i+1,j,n,m) && ans[i+1][j] == -1)
{
ans[i+1][j] = ans[i][j] + 1 ;
q.push({i+1,j});
}
}
return ans;
}
0
milindprajapatmst191 month ago
HELP!! Why segmentation fault?? I tried to ran it in my local machine via visual studio community, which uses microsoft c++. Also, I tried at some random online ide, which uses gcc compiler. On both the platforms, it is working fine!!
int dx[] = {-1, 0, 1, 0};
int dy[] = { 0, -1, 0, 1};
# define pi pair<int, int>
# define mp make_pair
# define f first
# define s second
class Solution {
public:
// multi-source bfs
vector<vector<int>> nearest(vector<vector<int>>& grid) {
int n = grid.size(), m = grid[0].size();
vector<vector<int>> dist(n, vector<int>(m, -1));
queue<pi> q;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (grid[i][j] == 1) {
dist[i][j] = 0;
q.push(mp(i, j));
}
}
}
while (!q.empty()) {
int sz = q.size();
while(sz--) {
pi& p = q.front();
q.pop();
for (int k = 0; k < 4; k++) {
int i = p.f + dx[k], j = p.s + dy[k];
if (0 <= i && i < n && 0 <= j && j < m && dist[i][j] == -1) {
q.push(mp(i, j));
dist[i][j] = dist[p.f][p.s] + 1;
}
}
}
}
return dist;
}
};
+1
himanshukug19cs1 month ago
java solution
class pair{ int x; int y; pair(int x,int y){ this.x=x; this.y=y; } } boolean[][] vis; boolean isValid(pair p,int[][] grid){ int i=grid.length; int j=grid[0].length; if(p.x<0||p.y<0||p.x>=i||p.y>=j||vis[p.x][p.y]==true||grid[p.x][p.y]==1) return false; return true; } public int[][] nearest(int[][] grid) { // Code here vis= new boolean[grid.length][grid[0].length]; int[][] ans = new int[grid.length][grid[0].length]; ArrayDeque<pair> dq = new ArrayDeque<>(); for(int i=0;i<grid.length;i++){ for(int j=0;j<grid[0].length;j++){ if(grid[i][j]==1){ ans[i][j]=0; dq.add(new pair(i,j)); vis[i][j]=true; } } } int[] xarr={-1,0,1,0}; int[] yarr={-0,1,0,-1}; while(!dq.isEmpty()){ pair re = dq.remove(); for(int i=0;i<4;i++){ pair p = new pair(re.x+xarr[i],re.y+yarr[i]); if(isValid(p,grid)){ vis[p.x][p.y]=true; ans[p.x][p.y]=Math.abs(re.x-p.x)+Math.abs(re.y-p.y)+ans[re.x][re.y]; dq.add(p); } } } return ans; }
0
tthakare732 months ago
//Java Solution --> hint use BFS
class Solution
{
public static class pair{
int i, j;
pair(int a, int b){
i = a;
j = b;
}
}
public static boolean checkSafe(int i, int j, int m, int n, int[][] result, int preI, int preJ){
return (i >= 0 && j >= 0 && i < m && j < n && result[preI][preJ] < result[i][j]);
}
//Function to find distance of nearest 1 in the grid for each cell.
public int[][] nearest(int[][] grid){
// Code here
int m = grid.length;
int n = grid[0].length;
int[][] result = new int[m][n];
for(int i = 0; i < m; i++){
Arrays.fill(result[i], Integer.MAX_VALUE);
}
Queue<pair> pq = new LinkedList<>();
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(grid[i][j] == 1){
result[i][j] = 0;
pq.add(new pair(i, j));
}
}
}
int x[] = {1, -1, 0, 0};
int y[] = {0, 0, -1, 1};
while(!pq.isEmpty()){
pair current = pq.poll();
int curtI = current.i;
int curtJ = current.j;
for(int i = 0; i < 4; i++){
if(checkSafe(curtI+x[i], curtJ+y[i], m, n, result, curtI, curtJ)){
result[curtI+x[i]][curtJ+y[i]] = result[curtI][curtJ]+1;
pq.add(new pair(curtI+x[i], curtJ+y[i]));
}
}
}
return result;
}
}
+2
siddhant072 months ago
//BFS based solution to find minimum distance in the grid
bool isValid(int x, int y, int rows, int cols){
if(x < 0 || x >= rows || y < 0 || y>= cols){
return false;
}
return true;
}
vector<vector<int>>nearest(vector<vector<int>>grid)
{
//This is the based on Breadth First Search
int rows = grid.size();
int cols = grid[0].size();
queue<pair<int, int>> q;
vector<vector<bool>> visited;
vector<vector<int>> ans;
for(int i = 0; i < rows; i++){
vector<bool> v (cols, false);
vector<int> a (cols, INT_MAX);
visited.push_back(v);
ans.push_back(a);
}
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
if(grid[i][j] == 1){
visited[i][j] = true;
ans[i][j] = 0;
q.push({i, j});
}
}
}
int dx[4] = {0, 1, 0, -1};
int dy[4] = {1, 0, -1, 0};
while(q.empty() == false){
int x = q.front().first;
int y = q.front().second;
q.pop();
int currDist = ans[x][y];
for(int i = 0; i < 4; i++){
int xdx = x + dx[i];
int ydy = y + dy[i];
if(isValid(xdx, ydy, rows, cols)){
if(visited[xdx][ydy] == false){
visited[xdx][ydy] = true;
q.push({xdx, ydy});
ans[xdx][ydy] = currDist + 1;
}
}
}
}
return ans;
}
0
maheshahirwar2042 months ago
Java Solution
class Solution{ static class Pair{ int x,y; Pair(int x,int y){ this.x=x; this.y=y; } } //Function to find distance of nearest 1 in the grid for each cell. public int[][] nearest(int[][] grid) { int n=grid.length; int m=grid[0].length; Queue<Pair>q=new LinkedList<Pair>(); int a=Integer.MAX_VALUE; int[][]ans=new int[n][m]; ans=fill(ans,a); for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ if(grid[i][j]==1){ ans[i][j]=0; q.add(new Pair(i,j)); } } } while(!q.isEmpty()){ Pair p=q.poll(); int i=p.x; int j=p.y; if((i-1)>=0&&ans[i][j]+1<ans[i-1][j]){ ans[i-1][j]=ans[i][j]+1; q.add(new Pair(i-1,j)); } if((j-1)>=0&&ans[i][j]+1<ans[i][j-1]){ ans[i][j-1]=ans[i][j]+1; q.add(new Pair(i,j-1)); } if((i+1)>=0&&i+1<n&&ans[i][j]+1<ans[i+1][j]){ ans[i+1][j]=ans[i][j]+1; q.add(new Pair(i+1,j)); } if((j+1)>=0&&j+1<m&&ans[i][j]+1<ans[i][j+1]){ ans[i][j+1]=ans[i][j]+1; q.add(new Pair(i,j+1)); } } return ans; } public int[][] fill(int [][]ans,int a){ for(int i=0;i<ans.length;i++){ for(int j=0;j<ans[0].length;j++){ ans[i][j]=a; } } return ans; }}
-1
45mzzbhoest5k5060ff1se8zbxbntzof9sjy5d1e3 months ago
//Solution without creating queue and single traversal of grid. We check closest cells for 1 first.
vector<vector<int>>nearest(vector<vector<int>>grid){ //d represents distance int d=1; int r=grid.size(); int c=grid[0].size(); int m,n,flag=0; vector<vector<int>> g=grid; for(int i=0;i<r;i++){ for(int j=0;j<c;j++){ d=1; flag=0; if(grid[i][j]==1) g[i][j]=0; else{ while(d<=(r+c-2)){ //if(i+d < r) for(m=i;m<=min(i+d,r-1);m++){ n=d-abs(m-i)+j; if(n<c && grid[m][n]==1) { g[i][j]=d; flag=1; break; } else{ n=abs(d-abs(m-i)-j); if(n<c && grid[m][n]==1){ g[i][j]=d; flag=1; break; } } } if(flag==0){ for(m=i;m>=max(i-d,0);m--){ n=d-abs(m-i)+j; if(n<c && grid[m][n]==1) { g[i][j]=d; flag=1; break; } else{ n=abs(d-abs(m-i)-j); if(n<c && grid[m][n]==1){ g[i][j]=d; flag=1; break; } } } } if(flag==1) break; d++; } } } } return g;}
0
mufaddalshakir553 months ago
C++ Beast BFS
vector<vector<int>>nearest(vector<vector<int>>grid)
{
queue<pair<int,pair<int,int>>> q;
int counter = 0;
int n = grid.size();
int m = grid[0].size();
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(grid[i][j] == 0){
grid[i][j] = INT_MAX;
counter++;
}else{
grid[i][j] = 0;
q.push({0,{i,j}});
}
}
}
while(!q.empty()){
auto top = q.front(); q.pop();
int dist = top.first;
int i = top.second.first;
int j = top.second.second;
int arr[] = {0,1,0,-1,0};
for(int k=0;k<4;k++){
int x = i+arr[k];
int y = j+arr[k+1];
if(x>=0 && x<n && y>=0 && y<m && grid[x][y]>0){
if(grid[x][y]>dist+1){
grid[x][y]=dist+1;
q.push({grid[x][y],{x,y}});
//if(--counter==0) return grid;
}
}
}
int arr2[] = {1,1,-1,-1,1};
for(int k=0;k<4;k++){
int x = i+arr2[k];
int y = j+arr2[k+1];
if(x>=0 && x<n && y>=0 && y<m && grid[x][y]>0){
if(grid[x][y]>dist+2){
grid[x][y]=dist+2;
q.push({grid[x][y],{x,y}});
//if(--counter==0) return grid;
}
}
}
}
return grid;
}
};
+1
abhiiishek073 months ago
vector<vector<int>>nearest(vector<vector<int>>grid){ // Code here int n=grid.size(); int m=grid[0].size(); vector<vector<int>> dist(n,vector<int>(m,INT_MAX)); queue<pair<int,int>> q; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if(grid[i][j]==1) { dist[i][j]=0; q.push({i,j}); } } } while(!q.empty()) { int i=q.front().first; int j=q.front().second; q.pop(); if(i+1<n && dist[i+1][j]> 1+dist[i][j]) { dist[i+1][j]=1+dist[i][j]; q.push({i+1,j}); } if(i-1>=0 && dist[i-1][j] > 1+dist[i][j]) { dist[i-1][j]=1+dist[i][j]; q.push({i-1,j}); } if(j-1>=0 && dist[i][j-1]>1+dist[i][j]) { dist[i][j-1]=1+dist[i][j]; q.push({i,j-1}); } if(j+1<m && dist[i][j+1]>1+dist[i][j]) { dist[i][j+1]=1+dist[i][j]; q.push({i,j+1}); } } return dist;}
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": 526,
"s": 238,
"text": "Given a binary grid. Find the distance of nearest 1 in the grid for each cell.\nThe distance is calculated as |i1 – i2| + |j1 – j2|, where i1, j1 are the row number and column number of the current cell and i2, j2 are the row number and column number of the nearest cell having value 1.\n "
},
{
"code": null,
"e": 537,
"s": 526,
"text": "Example 1:"
},
{
"code": null,
"e": 821,
"s": 537,
"text": "Input: grid = {{0,1,1,0},{1,1,0,0},{0,0,1,1}}\nOutput: {{1,0,0,1},{0,0,1,1},{1,1,0,0}}\nExplanation: The grid is-\n0 1 1 0 \n1 1 0 0 \n0 0 1 1 \n0's at (0,0), (0,3), (1,2), (1,3), (2,0) and\n(2,1) are at a distance of 1 from 1's at (0,1),\n(0,2), (0,2), (2,3), (1,0) and (1,1)\nrespectively.\n"
},
{
"code": null,
"e": 832,
"s": 821,
"text": "Example 2:"
},
{
"code": null,
"e": 1080,
"s": 832,
"text": "Input: grid = {{1,0,1},{1,1,0},{1,0,0}}\nOutput: {{0,1,0},{0,0,1},{0,1,2}}\nExplanation: The grid is-\n1 0 1\n1 1 0\n1 0 0\n0's at (0,1), (1,2), (2,1) and (2,2) are at a \ndistance of 1, 1, 1 and 2 from 1's at (0,0),\n(0,2), (2,0) and (1,1) respectively.\n"
},
{
"code": null,
"e": 1384,
"s": 1082,
"text": "Yout Task:\nYou don't need to read or print anything, Your task is to complete the function nearest() which takes grid as input parameter and returns a matrix of same dimensions where the value at index (i, j) in the resultant matrix signifies the minimum distance of 1 in the matrix from grid[i][j].\n "
},
{
"code": null,
"e": 1450,
"s": 1384,
"text": "Expected Time Complexity: O(n*m)\nExpected Auxiliary Space: O(n*m)"
},
{
"code": null,
"e": 1478,
"s": 1450,
"text": "Constraints:\n1 ≤ n, m ≤ 500"
},
{
"code": null,
"e": 1480,
"s": 1478,
"text": "0"
},
{
"code": null,
"e": 1504,
"s": 1480,
"text": "shilsoumyadip1 week ago"
},
{
"code": null,
"e": 2681,
"s": 1504,
"text": " vector<vector<int>>nearest(vector<vector<int>>grid){ // Code here int row = grid.size(); int column = grid[0].size(); queue<pair<int,int>> q ; vector<vector<int>>ans(row,vector<int>(column,INT_MAX)); for(int i=0;i<row;i++) { for(int j=0;j<column;j++) { if(grid[i][j] == 1) { q.push({i,j}); ans[i][j] = 0; } } } while(!q.empty()) { int i = q.front().first; int j = q.front().second; if( (i - 1) >= 0 and ans[i][j] + 1 < ans[i-1][j]) { ans[i-1][j] = ans[i][j] + 1 ; q.push({i-1,j}); } if((j - 1) >= 0 and ans[i][j] + 1 < ans[i][j-1]) { ans[i][j-1] = ans[i][j] + 1 ; q.push({i,j-1}); } if((i + 1) < row and ans[i][j] + 1 < ans[i+1][j]) { ans[i+1][j] = ans[i][j] + 1 ; q.push({i+1,j}); } if((j + 1) < column and ans[i][j] + 1 < ans[i][j+1]) { ans[i][j+1] = ans[i][j] + 1 ; q.push({i,j+1}); } q.pop(); } return ans;}};"
},
{
"code": null,
"e": 2684,
"s": 2681,
"text": "+2"
},
{
"code": null,
"e": 2712,
"s": 2684,
"text": "saurabhsathe12341 month ago"
},
{
"code": null,
"e": 2724,
"s": 2712,
"text": "C++ : 0.6ms"
},
{
"code": null,
"e": 2757,
"s": 2726,
"text": "Watch this video for concept ,"
},
{
"code": null,
"e": 2803,
"s": 2759,
"text": "https://www.youtube.com/watch?v=wtRT9G42g4g"
},
{
"code": null,
"e": 4167,
"s": 2805,
"text": "bool check(int i , int j ,int n , int m)\n {\n if(i < 0 || j < 0 || i >= n || j >= m )\n return false ;\n \n return true;\n }\n \n \n\tvector<vector<int>>nearest(vector<vector<int>>grid)\n\t{\n\t int n = grid.size();\n\t int m = grid[0].size();\n\t queue<pair<int,int>> q ;\n\t vector<vector<int>>ans(n,vector<int>(m,-1));\n\t \n\t for(int i=0;i<n;i++)\n\t {\n\t for(int j=0;j<m;j++)\n\t {\n\t if(grid[i][j] == 1)\n\t {\n\t q.push({i,j});\n\t ans[i][j] = 0;\n\t }\n\t }\n\t }\n\t \n\t while(!q.empty())\n\t {\n\t int i = q.front().first;\n\t int j = q.front().second;\n\t q.pop();\n\t \n\t if(check(i-1,j,n,m) && ans[i-1][j] == -1)\n\t {\n\t ans[i-1][j] = ans[i][j] + 1 ;\n\t q.push({i-1,j});\n\t }\n\t \n\t if(check(i,j-1,n,m) && ans[i][j-1] == -1)\n\t {\n\t ans[i][j-1] = ans[i][j] + 1 ;\n\t q.push({i,j-1});\n\t }\n\t \n\t if(check(i,j+1,n,m) && ans[i][j+1] == -1)\n\t {\n\t ans[i][j+1] = ans[i][j] + 1 ;\n\t q.push({i,j+1});\n\t }\n\t \n\t if(check(i+1,j,n,m) && ans[i+1][j] == -1)\n\t {\n\t ans[i+1][j] = ans[i][j] + 1 ;\n\t q.push({i+1,j});\n\t }\n\t }\n\t return ans;\n\t}"
},
{
"code": null,
"e": 4169,
"s": 4167,
"text": "0"
},
{
"code": null,
"e": 4200,
"s": 4169,
"text": "milindprajapatmst191 month ago"
},
{
"code": null,
"e": 5578,
"s": 4200,
"text": "HELP!! Why segmentation fault?? I tried to ran it in my local machine via visual studio community, which uses microsoft c++. Also, I tried at some random online ide, which uses gcc compiler. On both the platforms, it is working fine!!\n\nint dx[] = {-1, 0, 1, 0};\nint dy[] = { 0, -1, 0, 1};\n\n# define pi pair<int, int>\n# define mp make_pair\n# define f first\n# define s second\n\nclass Solution {\n public:\n // multi-source bfs \n vector<vector<int>> nearest(vector<vector<int>>& grid) {\n int n = grid.size(), m = grid[0].size();\n vector<vector<int>> dist(n, vector<int>(m, -1));\n queue<pi> q;\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < m; j++) {\n if (grid[i][j] == 1) {\n dist[i][j] = 0;\n q.push(mp(i, j));\n }\n }\n }\n while (!q.empty()) {\n int sz = q.size();\n while(sz--) {\n pi& p = q.front();\n q.pop();\n for (int k = 0; k < 4; k++) {\n int i = p.f + dx[k], j = p.s + dy[k];\n if (0 <= i && i < n && 0 <= j && j < m && dist[i][j] == -1) {\n q.push(mp(i, j));\n dist[i][j] = dist[p.f][p.s] + 1;\n }\n }\n }\n }\n return dist;\n }\n};"
},
{
"code": null,
"e": 5581,
"s": 5578,
"text": "+1"
},
{
"code": null,
"e": 5608,
"s": 5581,
"text": "himanshukug19cs1 month ago"
},
{
"code": null,
"e": 5622,
"s": 5608,
"text": "java solution"
},
{
"code": null,
"e": 6947,
"s": 5622,
"text": " class pair{ int x; int y; pair(int x,int y){ this.x=x; this.y=y; } } boolean[][] vis; boolean isValid(pair p,int[][] grid){ int i=grid.length; int j=grid[0].length; if(p.x<0||p.y<0||p.x>=i||p.y>=j||vis[p.x][p.y]==true||grid[p.x][p.y]==1) return false; return true; } public int[][] nearest(int[][] grid) { // Code here vis= new boolean[grid.length][grid[0].length]; int[][] ans = new int[grid.length][grid[0].length]; ArrayDeque<pair> dq = new ArrayDeque<>(); for(int i=0;i<grid.length;i++){ for(int j=0;j<grid[0].length;j++){ if(grid[i][j]==1){ ans[i][j]=0; dq.add(new pair(i,j)); vis[i][j]=true; } } } int[] xarr={-1,0,1,0}; int[] yarr={-0,1,0,-1}; while(!dq.isEmpty()){ pair re = dq.remove(); for(int i=0;i<4;i++){ pair p = new pair(re.x+xarr[i],re.y+yarr[i]); if(isValid(p,grid)){ vis[p.x][p.y]=true; ans[p.x][p.y]=Math.abs(re.x-p.x)+Math.abs(re.y-p.y)+ans[re.x][re.y]; dq.add(p); } } } return ans; }"
},
{
"code": null,
"e": 6949,
"s": 6947,
"text": "0"
},
{
"code": null,
"e": 6972,
"s": 6949,
"text": "tthakare732 months ago"
},
{
"code": null,
"e": 8548,
"s": 6972,
"text": "//Java Solution --> hint use BFS\nclass Solution\n{\n public static class pair{\n int i, j;\n pair(int a, int b){\n i = a;\n j = b;\n }\n }\n \n public static boolean checkSafe(int i, int j, int m, int n, int[][] result, int preI, int preJ){\n return (i >= 0 && j >= 0 && i < m && j < n && result[preI][preJ] < result[i][j]);\n }\n //Function to find distance of nearest 1 in the grid for each cell.\n public int[][] nearest(int[][] grid){\n // Code here\n int m = grid.length;\n int n = grid[0].length;\n \n int[][] result = new int[m][n];\n for(int i = 0; i < m; i++){\n Arrays.fill(result[i], Integer.MAX_VALUE);\n }\n \n Queue<pair> pq = new LinkedList<>();\n for(int i = 0; i < m; i++){\n for(int j = 0; j < n; j++){\n if(grid[i][j] == 1){\n result[i][j] = 0;\n pq.add(new pair(i, j));\n }\n }\n }\n \n int x[] = {1, -1, 0, 0};\n int y[] = {0, 0, -1, 1};\n while(!pq.isEmpty()){\n pair current = pq.poll();\n int curtI = current.i;\n int curtJ = current.j;\n for(int i = 0; i < 4; i++){\n if(checkSafe(curtI+x[i], curtJ+y[i], m, n, result, curtI, curtJ)){\n result[curtI+x[i]][curtJ+y[i]] = result[curtI][curtJ]+1;\n pq.add(new pair(curtI+x[i], curtJ+y[i]));\n }\n }\n }\n \n return result;\n }\n}"
},
{
"code": null,
"e": 8551,
"s": 8548,
"text": "+2"
},
{
"code": null,
"e": 8574,
"s": 8551,
"text": "siddhant072 months ago"
},
{
"code": null,
"e": 8632,
"s": 8574,
"text": "//BFS based solution to find minimum distance in the grid"
},
{
"code": null,
"e": 10104,
"s": 8632,
"text": " bool isValid(int x, int y, int rows, int cols){\n if(x < 0 || x >= rows || y < 0 || y>= cols){\n return false;\n }\n return true;\n }\n \n\tvector<vector<int>>nearest(vector<vector<int>>grid)\n\t{\n\t //This is the based on Breadth First Search\n\t int rows = grid.size();\n\t int cols = grid[0].size();\n\t queue<pair<int, int>> q;\n\t vector<vector<bool>> visited;\n\t vector<vector<int>> ans;\n\t for(int i = 0; i < rows; i++){\n\t vector<bool> v (cols, false);\n\t vector<int> a (cols, INT_MAX);\n\t visited.push_back(v);\n\t ans.push_back(a);\n\t }\n\t for(int i = 0; i < rows; i++){\n\t for(int j = 0; j < cols; j++){\n\t if(grid[i][j] == 1){\n\t visited[i][j] = true;\n\t ans[i][j] = 0;\n\t q.push({i, j});\n\t }\n\t }\n\t }\n\t int dx[4] = {0, 1, 0, -1};\n\t int dy[4] = {1, 0, -1, 0};\n\t while(q.empty() == false){\n\t int x = q.front().first;\n\t int y = q.front().second;\n\t q.pop();\n\t int currDist = ans[x][y];\n\t for(int i = 0; i < 4; i++){\n\t int xdx = x + dx[i];\n\t int ydy = y + dy[i];\n\t if(isValid(xdx, ydy, rows, cols)){\n\t if(visited[xdx][ydy] == false){\n\t visited[xdx][ydy] = true;\n\t q.push({xdx, ydy});\n\t ans[xdx][ydy] = currDist + 1;\n\t }\n\t }\n\t }\n\t }\n\t return ans;\n\t}"
},
{
"code": null,
"e": 10106,
"s": 10104,
"text": "0"
},
{
"code": null,
"e": 10135,
"s": 10106,
"text": "maheshahirwar2042 months ago"
},
{
"code": null,
"e": 10150,
"s": 10135,
"text": "Java Solution "
},
{
"code": null,
"e": 11630,
"s": 10152,
"text": "class Solution{ static class Pair{ int x,y; Pair(int x,int y){ this.x=x; this.y=y; } } //Function to find distance of nearest 1 in the grid for each cell. public int[][] nearest(int[][] grid) { int n=grid.length; int m=grid[0].length; Queue<Pair>q=new LinkedList<Pair>(); int a=Integer.MAX_VALUE; int[][]ans=new int[n][m]; ans=fill(ans,a); for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ if(grid[i][j]==1){ ans[i][j]=0; q.add(new Pair(i,j)); } } } while(!q.isEmpty()){ Pair p=q.poll(); int i=p.x; int j=p.y; if((i-1)>=0&&ans[i][j]+1<ans[i-1][j]){ ans[i-1][j]=ans[i][j]+1; q.add(new Pair(i-1,j)); } if((j-1)>=0&&ans[i][j]+1<ans[i][j-1]){ ans[i][j-1]=ans[i][j]+1; q.add(new Pair(i,j-1)); } if((i+1)>=0&&i+1<n&&ans[i][j]+1<ans[i+1][j]){ ans[i+1][j]=ans[i][j]+1; q.add(new Pair(i+1,j)); } if((j+1)>=0&&j+1<m&&ans[i][j]+1<ans[i][j+1]){ ans[i][j+1]=ans[i][j]+1; q.add(new Pair(i,j+1)); } } return ans; } public int[][] fill(int [][]ans,int a){ for(int i=0;i<ans.length;i++){ for(int j=0;j<ans[0].length;j++){ ans[i][j]=a; } } return ans; }}"
},
{
"code": null,
"e": 11633,
"s": 11630,
"text": "-1"
},
{
"code": null,
"e": 11686,
"s": 11633,
"text": "45mzzbhoest5k5060ff1se8zbxbntzof9sjy5d1e3 months ago"
},
{
"code": null,
"e": 11787,
"s": 11686,
"text": "//Solution without creating queue and single traversal of grid. We check closest cells for 1 first. "
},
{
"code": null,
"e": 13715,
"s": 11787,
"text": "vector<vector<int>>nearest(vector<vector<int>>grid){ //d represents distance int d=1; int r=grid.size(); int c=grid[0].size(); int m,n,flag=0; vector<vector<int>> g=grid; for(int i=0;i<r;i++){ for(int j=0;j<c;j++){ d=1; flag=0; if(grid[i][j]==1) g[i][j]=0; else{ while(d<=(r+c-2)){ //if(i+d < r) for(m=i;m<=min(i+d,r-1);m++){ n=d-abs(m-i)+j; if(n<c && grid[m][n]==1) { g[i][j]=d; flag=1; break; } else{ n=abs(d-abs(m-i)-j); if(n<c && grid[m][n]==1){ g[i][j]=d; flag=1; break; } } } if(flag==0){ for(m=i;m>=max(i-d,0);m--){ n=d-abs(m-i)+j; if(n<c && grid[m][n]==1) { g[i][j]=d; flag=1; break; } else{ n=abs(d-abs(m-i)-j); if(n<c && grid[m][n]==1){ g[i][j]=d; flag=1; break; } } } } if(flag==1) break; d++; } } } } return g;}"
},
{
"code": null,
"e": 13717,
"s": 13715,
"text": "0"
},
{
"code": null,
"e": 13746,
"s": 13717,
"text": "mufaddalshakir553 months ago"
},
{
"code": null,
"e": 13760,
"s": 13746,
"text": "C++ Beast BFS"
},
{
"code": null,
"e": 15366,
"s": 13760,
"text": "\tvector<vector<int>>nearest(vector<vector<int>>grid)\n\t{\n\t queue<pair<int,pair<int,int>>> q;\n\t int counter = 0;\n\t int n = grid.size();\n\t int m = grid[0].size();\n\t \n\t for(int i=0;i<n;i++){\n\t for(int j=0;j<m;j++){\n\t \n\t if(grid[i][j] == 0){\n\t grid[i][j] = INT_MAX;\n\t counter++;\n\t }else{\n\t grid[i][j] = 0;\n\t q.push({0,{i,j}});\n\t }\n\t \n\t }\n\t }\n\t \n\t \n\t while(!q.empty()){\n\t \n\t auto top = q.front(); q.pop();\n\t int dist = top.first;\n\t int i = top.second.first;\n\t int j = top.second.second;\n\t \n\t int arr[] = {0,1,0,-1,0};\n\t for(int k=0;k<4;k++){\n\t int x = i+arr[k];\n\t int y = j+arr[k+1];\n\t \n\t if(x>=0 && x<n && y>=0 && y<m && grid[x][y]>0){\n\t if(grid[x][y]>dist+1){\n\t grid[x][y]=dist+1;\n\t q.push({grid[x][y],{x,y}});\n\t //if(--counter==0) return grid;\n\t }\n\t }\n\t }\n\t \n\t int arr2[] = {1,1,-1,-1,1};\n\t for(int k=0;k<4;k++){\n\t int x = i+arr2[k];\n\t int y = j+arr2[k+1];\n\t \n\t if(x>=0 && x<n && y>=0 && y<m && grid[x][y]>0){\n\t if(grid[x][y]>dist+2){\n\t grid[x][y]=dist+2;\n\t q.push({grid[x][y],{x,y}});\n\t //if(--counter==0) return grid;\n\t }\n\t }\n\t }\n\t \n\t }\n\t \n\t return grid;\n\t}\n};"
},
{
"code": null,
"e": 15369,
"s": 15366,
"text": "+1"
},
{
"code": null,
"e": 15394,
"s": 15369,
"text": "abhiiishek073 months ago"
},
{
"code": null,
"e": 16426,
"s": 15394,
"text": " vector<vector<int>>nearest(vector<vector<int>>grid){ // Code here int n=grid.size(); int m=grid[0].size(); vector<vector<int>> dist(n,vector<int>(m,INT_MAX)); queue<pair<int,int>> q; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if(grid[i][j]==1) { dist[i][j]=0; q.push({i,j}); } } } while(!q.empty()) { int i=q.front().first; int j=q.front().second; q.pop(); if(i+1<n && dist[i+1][j]> 1+dist[i][j]) { dist[i+1][j]=1+dist[i][j]; q.push({i+1,j}); } if(i-1>=0 && dist[i-1][j] > 1+dist[i][j]) { dist[i-1][j]=1+dist[i][j]; q.push({i-1,j}); } if(j-1>=0 && dist[i][j-1]>1+dist[i][j]) { dist[i][j-1]=1+dist[i][j]; q.push({i,j-1}); } if(j+1<m && dist[i][j+1]>1+dist[i][j]) { dist[i][j+1]=1+dist[i][j]; q.push({i,j+1}); } } return dist;}"
},
{
"code": null,
"e": 16572,
"s": 16426,
"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": 16608,
"s": 16572,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 16618,
"s": 16608,
"text": "\nProblem\n"
},
{
"code": null,
"e": 16628,
"s": 16618,
"text": "\nContest\n"
},
{
"code": null,
"e": 16691,
"s": 16628,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 16839,
"s": 16691,
"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": 17047,
"s": 16839,
"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": 17153,
"s": 17047,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
React useEffect | The useEffect Hook allows you to perform side effects in your components.
Some examples of side effects are: fetching data, directly updating the DOM, and timers.
useEffect accepts two arguments. The second argument is optional.
useEffect(<function>, <dependency>)
Let's use a timer as an example.
Use setTimeout() to count 1 second after initial render:
import { useState, useEffect } from "react";
import ReactDOM from "react-dom/client";
function Timer() {
const [count, setCount] = useState(0);
useEffect(() => {
setTimeout(() => {
setCount((count) => count + 1);
}, 1000);
});
return <h1>I've rendered {count} times!</h1>;
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Timer />);
Run
Example »
But wait!! It keeps counting even though it should only count once!
useEffect runs on every render. That means that when the count changes, a render happens, which then triggers another effect.
This is not what we want. There are several ways to control when side effects run.
We should always include the second parameter which accepts an array.
We can optionally pass dependencies to useEffect in this array.
useEffect(() => {
//Runs on every render
});
useEffect(() => {
//Runs only on the first render
}, []);
useEffect(() => {
//Runs on the first render
//And any time any dependency value changes
}, [prop, state]);
So, to fix this issue, let's only run this effect on the initial render.
Only run the effect on the initial render:
import { useState, useEffect } from "react";
import ReactDOM from "react-dom/client";
function Timer() {
const [count, setCount] = useState(0);
useEffect(() => {
setTimeout(() => {
setCount((count) => count + 1);
}, 1000);
}, []); // <- add empty brackets here
return <h1>I've rendered {count} times!</h1>;
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Timer />);
Run
Example »
Here is an example of a useEffect Hook that is dependent on a variable. If the count variable updates, the effect will run again:
import { useState, useEffect } from "react";
import ReactDOM from "react-dom/client";
function Counter() {
const [count, setCount] = useState(0);
const [calculation, setCalculation] = useState(0);
useEffect(() => {
setCalculation(() => count * 2);
}, [count]); // <- add the count variable here
return (
<>
<p>Count: {count}</p>
<button onClick={() => setCount((c) => c + 1)}>+</button>
<p>Calculation: {calculation}</p>
</>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Counter />);
Run
Example »
If there are multiple dependencies, they should be included in the useEffect dependency array.
Some effects require cleanup to reduce memory leaks.
Timeouts, subscriptions, event listeners, and other effects that are no longer needed should be disposed.
We do this by including a return function at the end of the useEffect Hook.
Clean up the timer at the end of the useEffect Hook:
import { useState, useEffect } from "react";
import ReactDOM from "react-dom/client";
function Timer() {
const [count, setCount] = useState(0);
useEffect(() => {
let timer = setTimeout(() => {
setCount((count) => count + 1);
}, 1000);
return () => clearTimeout(timer)
}, []);
return <h1>I've rendered {count} times!</h1>;
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Timer />);
Run
Example »
Note: To clear the timer, we had to name it.
What do you need to add to the second argument of a useEffect Hook to limit it to running only on the first render?
import { useState, useEffect } from "react";
import ReactDOM from "react-dom/client";
function App() {
const [data, setData] = useState([]);
useEffect(() => {
setData(getData())
}, );
return <DisplayData data={data} />;
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
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": 74,
"s": 0,
"text": "The useEffect Hook allows you to perform side effects in your components."
},
{
"code": null,
"e": 163,
"s": 74,
"text": "Some examples of side effects are: fetching data, directly updating the DOM, and timers."
},
{
"code": null,
"e": 229,
"s": 163,
"text": "useEffect accepts two arguments. The second argument is optional."
},
{
"code": null,
"e": 265,
"s": 229,
"text": "useEffect(<function>, <dependency>)"
},
{
"code": null,
"e": 298,
"s": 265,
"text": "Let's use a timer as an example."
},
{
"code": null,
"e": 355,
"s": 298,
"text": "Use setTimeout() to count 1 second after initial render:"
},
{
"code": null,
"e": 747,
"s": 355,
"text": "import { useState, useEffect } from \"react\";\nimport ReactDOM from \"react-dom/client\";\n\nfunction Timer() {\n const [count, setCount] = useState(0);\n\n useEffect(() => {\n setTimeout(() => {\n setCount((count) => count + 1);\n }, 1000);\n });\n\n return <h1>I've rendered {count} times!</h1>;\n}\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(<Timer />);"
},
{
"code": null,
"e": 764,
"s": 747,
"text": "\nRun \nExample »\n"
},
{
"code": null,
"e": 832,
"s": 764,
"text": "But wait!! It keeps counting even though it should only count once!"
},
{
"code": null,
"e": 958,
"s": 832,
"text": "useEffect runs on every render. That means that when the count changes, a render happens, which then triggers another effect."
},
{
"code": null,
"e": 1041,
"s": 958,
"text": "This is not what we want. There are several ways to control when side effects run."
},
{
"code": null,
"e": 1175,
"s": 1041,
"text": "We should always include the second parameter which accepts an array.\nWe can optionally pass dependencies to useEffect in this array."
},
{
"code": null,
"e": 1222,
"s": 1175,
"text": "useEffect(() => {\n //Runs on every render\n});"
},
{
"code": null,
"e": 1282,
"s": 1222,
"text": "useEffect(() => {\n //Runs only on the first render\n}, []);"
},
{
"code": null,
"e": 1394,
"s": 1282,
"text": "useEffect(() => {\n //Runs on the first render\n //And any time any dependency value changes\n}, [prop, state]);"
},
{
"code": null,
"e": 1467,
"s": 1394,
"text": "So, to fix this issue, let's only run this effect on the initial render."
},
{
"code": null,
"e": 1510,
"s": 1467,
"text": "Only run the effect on the initial render:"
},
{
"code": null,
"e": 1936,
"s": 1510,
"text": "import { useState, useEffect } from \"react\";\nimport ReactDOM from \"react-dom/client\";\n\nfunction Timer() {\n const [count, setCount] = useState(0);\n\n useEffect(() => {\n setTimeout(() => {\n setCount((count) => count + 1);\n }, 1000);\n }, []); // <- add empty brackets here\n\n return <h1>I've rendered {count} times!</h1>;\n}\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(<Timer />);"
},
{
"code": null,
"e": 1953,
"s": 1936,
"text": "\nRun \nExample »\n"
},
{
"code": null,
"e": 2083,
"s": 1953,
"text": "Here is an example of a useEffect Hook that is dependent on a variable. If the count variable updates, the effect will run again:"
},
{
"code": null,
"e": 2652,
"s": 2083,
"text": "import { useState, useEffect } from \"react\";\nimport ReactDOM from \"react-dom/client\";\n\nfunction Counter() {\n const [count, setCount] = useState(0);\n const [calculation, setCalculation] = useState(0);\n\n useEffect(() => {\n setCalculation(() => count * 2);\n }, [count]); // <- add the count variable here\n\n return (\n <>\n <p>Count: {count}</p>\n <button onClick={() => setCount((c) => c + 1)}>+</button>\n <p>Calculation: {calculation}</p>\n </>\n );\n}\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(<Counter />);"
},
{
"code": null,
"e": 2669,
"s": 2652,
"text": "\nRun \nExample »\n"
},
{
"code": null,
"e": 2764,
"s": 2669,
"text": "If there are multiple dependencies, they should be included in the useEffect dependency array."
},
{
"code": null,
"e": 2817,
"s": 2764,
"text": "Some effects require cleanup to reduce memory leaks."
},
{
"code": null,
"e": 2923,
"s": 2817,
"text": "Timeouts, subscriptions, event listeners, and other effects that are no longer needed should be disposed."
},
{
"code": null,
"e": 2999,
"s": 2923,
"text": "We do this by including a return function at the end of the useEffect Hook."
},
{
"code": null,
"e": 3052,
"s": 2999,
"text": "Clean up the timer at the end of the useEffect Hook:"
},
{
"code": null,
"e": 3492,
"s": 3052,
"text": "import { useState, useEffect } from \"react\";\nimport ReactDOM from \"react-dom/client\";\n\nfunction Timer() {\n const [count, setCount] = useState(0);\n\n useEffect(() => {\n let timer = setTimeout(() => {\n setCount((count) => count + 1);\n }, 1000);\n\n return () => clearTimeout(timer)\n }, []);\n\n return <h1>I've rendered {count} times!</h1>;\n}\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(<Timer />);"
},
{
"code": null,
"e": 3509,
"s": 3492,
"text": "\nRun \nExample »\n"
},
{
"code": null,
"e": 3554,
"s": 3509,
"text": "Note: To clear the timer, we had to name it."
},
{
"code": null,
"e": 3670,
"s": 3554,
"text": "What do you need to add to the second argument of a useEffect Hook to limit it to running only on the first render?"
},
{
"code": null,
"e": 3998,
"s": 3670,
"text": "import { useState, useEffect } from \"react\";\nimport ReactDOM from \"react-dom/client\";\n\nfunction App() {\n const [data, setData] = useState([]);\n\n useEffect(() => {\n setData(getData())\n }, );\n\n return <DisplayData data={data} />;\n}\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(<App />);\n"
},
{
"code": null,
"e": 4017,
"s": 3998,
"text": "Start the Exercise"
},
{
"code": null,
"e": 4050,
"s": 4017,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 4092,
"s": 4050,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 4199,
"s": 4092,
"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": 4218,
"s": 4199,
"text": "[email protected]"
}
] |
Node.js - Buffers | Pure JavaScript is Unicode friendly, but it is not so for binary data. While dealing with TCP streams or the file system, it's necessary to handle octet streams. Node provides Buffer class which provides instances to store raw data similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap.
Buffer class is a global class that can be accessed in an application without importing the buffer module.
Node Buffer can be constructed in a variety of ways.
Following is the syntax to create an uninitiated Buffer of 10 octets −
var buf = new Buffer(10);
Following is the syntax to create a Buffer from a given array −
var buf = new Buffer([10, 20, 30, 40, 50]);
Following is the syntax to create a Buffer from a given string and optionally encoding type −
var buf = new Buffer("Simply Easy Learning", "utf-8");
Though "utf8" is the default encoding, you can use any of the following encodings "ascii", "utf8", "utf16le", "ucs2", "base64" or "hex".
Following is the syntax of the method to write into a Node Buffer −
buf.write(string[, offset][, length][, encoding])
Here is the description of the parameters used −
string − This is the string data to be written to buffer.
string − This is the string data to be written to buffer.
offset − This is the index of the buffer to start writing at. Default value is 0.
offset − This is the index of the buffer to start writing at. Default value is 0.
length − This is the number of bytes to write. Defaults to buffer.length.
length − This is the number of bytes to write. Defaults to buffer.length.
encoding − Encoding to use. 'utf8' is the default encoding.
encoding − Encoding to use. 'utf8' is the default encoding.
This method returns the number of octets written. If there is not enough space in the buffer to fit the entire string, it will write a part of the string.
buf = new Buffer(256);
len = buf.write("Simply Easy Learning");
console.log("Octets written : "+ len);
When the above program is executed, it produces the following result −
Octets written : 20
Following is the syntax of the method to read data from a Node Buffer −
buf.toString([encoding][, start][, end])
Here is the description of the parameters used −
encoding − Encoding to use. 'utf8' is the default encoding.
encoding − Encoding to use. 'utf8' is the default encoding.
start − Beginning index to start reading, defaults to 0.
start − Beginning index to start reading, defaults to 0.
end − End index to end reading, defaults is complete buffer.
end − End index to end reading, defaults is complete buffer.
This method decodes and returns a string from buffer data encoded using the specified character set encoding.
buf = new Buffer(26);
for (var i = 0 ; i < 26 ; i++) {
buf[i] = i + 97;
}
console.log( buf.toString('ascii')); // outputs: abcdefghijklmnopqrstuvwxyz
console.log( buf.toString('ascii',0,5)); // outputs: abcde
console.log( buf.toString('utf8',0,5)); // outputs: abcde
console.log( buf.toString(undefined,0,5)); // encoding defaults to 'utf8', outputs abcde
When the above program is executed, it produces the following result −
abcdefghijklmnopqrstuvwxyz
abcde
abcde
abcde
Following is the syntax of the method to convert a Node Buffer into JSON object −
buf.toJSON()
This method returns a JSON-representation of the Buffer instance.
var buf = new Buffer('Simply Easy Learning');
var json = buf.toJSON(buf);
console.log(json);
When the above program is executed, it produces the following result −
{ type: 'Buffer',
data:
[
83,
105,
109,
112,
108,
121,
32,
69,
97,
115,
121,
32,
76,
101,
97,
114,
110,
105,
110,
103
]
}
Following is the syntax of the method to concatenate Node buffers to a single Node Buffer −
Buffer.concat(list[, totalLength])
Here is the description of the parameters used −
list − Array List of Buffer objects to be concatenated.
list − Array List of Buffer objects to be concatenated.
totalLength − This is the total length of the buffers when concatenated.
totalLength − This is the total length of the buffers when concatenated.
This method returns a Buffer instance.
var buffer1 = new Buffer('TutorialsPoint ');
var buffer2 = new Buffer('Simply Easy Learning');
var buffer3 = Buffer.concat([buffer1,buffer2]);
console.log("buffer3 content: " + buffer3.toString());
When the above program is executed, it produces the following result −
buffer3 content: TutorialsPoint Simply Easy Learning
Following is the syntax of the method to compare two Node buffers −
buf.compare(otherBuffer);
Here is the description of the parameters used −
otherBuffer − This is the other buffer which will be compared with buf
otherBuffer − This is the other buffer which will be compared with buf
Returns a number indicating whether it comes before or after or is the same as the otherBuffer in sort order.
var buffer1 = new Buffer('ABC');
var buffer2 = new Buffer('ABCD');
var result = buffer1.compare(buffer2);
if(result < 0) {
console.log(buffer1 +" comes before " + buffer2);
} else if(result === 0) {
console.log(buffer1 +" is same as " + buffer2);
} else {
console.log(buffer1 +" comes after " + buffer2);
}
When the above program is executed, it produces the following result −
ABC comes before ABCD
Following is the syntax of the method to copy a node buffer −
buf.copy(targetBuffer[, targetStart][, sourceStart][, sourceEnd])
Here is the description of the parameters used −
targetBuffer − Buffer object where buffer will be copied.
targetBuffer − Buffer object where buffer will be copied.
targetStart − Number, Optional, Default: 0
targetStart − Number, Optional, Default: 0
sourceStart − Number, Optional, Default: 0
sourceStart − Number, Optional, Default: 0
sourceEnd − Number, Optional, Default: buffer.length
sourceEnd − Number, Optional, Default: buffer.length
No return value. Copies data from a region of this buffer to a region in the target buffer even if the target memory region overlaps with the source. If undefined, the targetStart and sourceStart parameters default to 0, while sourceEnd defaults to buffer.length.
var buffer1 = new Buffer('ABC');
//copy a buffer
var buffer2 = new Buffer(3);
buffer1.copy(buffer2);
console.log("buffer2 content: " + buffer2.toString());
When the above program is executed, it produces the following result −
buffer2 content: ABC
Following is the syntax of the method to get a sub-buffer of a node buffer −
buf.slice([start][, end])
Here is the description of the parameters used −
start − Number, Optional, Default: 0
start − Number, Optional, Default: 0
end − Number, Optional, Default: buffer.length
end − Number, Optional, Default: buffer.length
Returns a new buffer which references the same memory as the old one, but offset and cropped by the start (defaults to 0) and end (defaults to buffer.length) indexes. Negative indexes start from the end of the buffer.
var buffer1 = new Buffer('TutorialsPoint');
//slicing a buffer
var buffer2 = buffer1.slice(0,9);
console.log("buffer2 content: " + buffer2.toString());
When the above program is executed, it produces the following result −
buffer2 content: Tutorials
Following is the syntax of the method to get a size of a node buffer in bytes −
buf.length;
Returns the size of a buffer in bytes.
var buffer = new Buffer('TutorialsPoint');
//length of the buffer
console.log("buffer length: " + buffer.length);
When the above program is executed, it produces following result −
buffer length: 14
new Buffer(size)
Allocates a new buffer of size octets. Note that the size must be no more than kMaxLength. Otherwise, a RangeError will be thrown here.
new Buffer(buffer)
Copies the passed buffer data onto a new Buffer instance.
new Buffer(str[, encoding])
Allocates a new buffer containing the given str. encoding defaults to 'utf8'.
buf.length
Returns the size of the buffer in bytes. Note that this is not necessarily the size of the contents. length refers to the amount of memory allocated for the buffer object. It does not change when the contents of the buffer are changed.
buf.write(string[, offset][, length][, encoding])
Writes a string to the buffer at offset using the given encoding. offset defaults to 0, encoding defaults to 'utf8'. length is the number of bytes to write. Returns the number of octets written.
buf.writeUIntLE(value, offset, byteLength[, noAssert])
Writes a value to the buffer at the specified offset and byteLength. Supports up to 48 bits of accuracy. Set noAssert to true to skip validation of value and offset. Defaults to false.
buf.writeUIntBE(value, offset, byteLength[, noAssert])
Writes a value to the buffer at the specified offset and byteLength. Supports up to 48 bits of accuracy. Set noAssert to true to skip validation of value and offset. Defaults to false.
buf.writeIntLE(value, offset, byteLength[, noAssert])
Writes a value to the buffer at the specified offset and byteLength. Supports up to 48 bits of accuracy. Set noAssert to true to skip validation of value and offset. Defaults to false.
buf.writeIntBE(value, offset, byteLength[, noAssert])
Writes a value to the buffer at the specified offset and byteLength. Supports up to 48 bits of accuracy. Set noAssert to true to skip validation of value and offset. Defaults to false.
buf.readUIntLE(offset, byteLength[, noAssert])
A generalized version of all numeric read methods. Supports up to 48 bits of accuracy. Set noAssert to true to skip validation of offset. It means that the offset may be beyond the end of the buffer. Defaults to false.
buf.readUIntBE(offset, byteLength[, noAssert])
A generalized version of all numeric read methods. Supports up to 48 bits of accuracy. Set noAssert to true to skip validation of offset. It means that the offset may be beyond the end of the buffer. Defaults to false.
buf.readIntLE(offset, byteLength[, noAssert])
A generalized version of all numeric read methods. Supports up to 48 bits of accuracy. Set noAssert to true to skip validation of offset. It means that the offset may be beyond the end of the buffer. Defaults to false.
buf.readIntBE(offset, byteLength[, noAssert])
A generalized version of all numeric read methods. Supports up to 48 bits of accuracy. Set noAssert to true to skip validation of offset. It means that the offset may be beyond the end of the buffer. Defaults to false.
buf.toString([encoding][, start][, end])
Decodes and returns a string from buffer data encoded using the specified character set encoding.
buf.toJSON()
Returns a JSON-representation of the Buffer instance. JSON.stringify implicitly calls this function when stringifying a Buffer instance.
buf[index]
Get and set the octet at index. The values refer to individual bytes, so the legal range is between 0x00 and 0xFF hex or 0 and 255.
buf.equals(otherBuffer)
Returns a boolean if this buffer and otherBuffer have the same bytes.
buf.compare(otherBuffer)
Returns a number indicating whether this buffer comes before or after or is the same as the otherBuffer in sort order.
buf.copy(targetBuffer[, targetStart][, sourceStart][, sourceEnd])
Copies data from a region of this buffer to a region in the target buffer even if the target memory region overlaps with the source. If undefined, the targetStart and sourceStart parameters default to 0, while sourceEnd defaults to buffer.length.
buf.slice([start][, end])
Returns a new buffer which references the same memory as the old, but offset and cropped by the start (defaults to 0) and end (defaults to buffer.length) indexes. Negative indexes start from the end of the buffer.
buf.readUInt8(offset[, noAssert])
Reads an unsigned 8 bit integer from the buffer at the specified offset. Set noAssert to true to skip validation of offset. It means that the offset may be beyond the end of the buffer. Defaults to false.
buf.readUInt16LE(offset[, noAssert])
Reads an unsigned 16-bit integer from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false.
buf.readUInt16BE(offset[, noAssert])
Reads an unsigned 16-bit integer from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false.
buf.readUInt32LE(offset[, noAssert])
Reads an unsigned 32-bit integer from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false.
buf.readUInt32BE(offset[, noAssert])
Reads an unsigned 32-bit integer from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false.
buf.readInt8(offset[, noAssert])
Reads a signed 8-bit integer from the buffer at the specified offset. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false.
buf.readInt16LE(offset[, noAssert])
Reads a signed 16-bit integer from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false.
buf.readInt16BE(offset[, noAssert])
Reads a signed 16-bit integer from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false.
buf.readInt32LE(offset[, noAssert])
Reads a signed 32-bit integer from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false.
buf.readInt32BE(offset[, noAssert])
Reads a signed 32-bit integer from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false.
buf.readFloatLE(offset[, noAssert])
Reads a 32-bit float from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false.
buf.readFloatBE(offset[, noAssert])
Reads a 32-bit float from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false.
buf.readDoubleLE(offset[, noAssert])
Reads a 64-bit double from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false.
buf.readDoubleBE(offset[, noAssert])
Reads a 64-bit double from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false.
buf.writeUInt8(value, offset[, noAssert])
Writes a value to the buffer at the specified offset. Note that the value must be a valid unsigned 8-bit integer. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false.
buf.writeUInt16LE(value, offset[, noAssert])
Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a valid unsigned 16-bit integer. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of correctness. Defaults to false.
buf.writeUInt16BE(value, offset[, noAssert])
Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a valid unsigned 16-bit integer. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false.
buf.writeUInt32LE(value, offset[, noAssert])
Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a valid unsigned 32-bit integer. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false.
buf.writeUInt32BE(value, offset[, noAssert])
Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a valid unsigned 32-bit integer. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false.
buf.writeInt8(value, offset[, noAssert])
Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a valid signed 8-bit integer. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false.
buf.writeInt16LE(value, offset[, noAssert])
Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a valid signed 16-bit integer. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false.
buf.writeInt16BE(value, offset[, noAssert])
Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a valid signed 16-bit integer. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false.
buf.writeInt32LE(value, offset[, noAssert])
Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a valid signed 32-bit integer. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false.
buf.writeInt32BE(value, offset[, noAssert])
Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a valid signed 32-bit integer. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of correctness. Defaults to false.
buf.writeFloatLE(value, offset[, noAssert])
Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a valid 32-bit float. Set noAssert to true to skip validation of value and offset. It means that the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false.
buf.writeFloatBE(value, offset[, noAssert])
Writes a value to the buffer at the specified offset with the specified endian format. Note, value must be a valid 32-bit float. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false.
buf.writeDoubleLE(value, offset[, noAssert])
Writes a value to the buffer at the specified offset with the specified endian format. Note, value must be a valid 64-bit double. Set noAssert to true to skip validation of value and offset. It means that value may be too large for the specific function and offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false.
buf.writeDoubleBE(value, offset[, noAssert])
Writes a value to the buffer at the specified offset with the specified endian format. Note, value must be a valid 64-bit double. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false.
buf.fill(value[, offset][, end])
Fills the buffer with the specified value. If the offset (defaults to 0) and end (defaults to buffer.length) are not given, it will fill the entire buffer.
Buffer.isEncoding(encoding)
Returns true if the encoding is a valid encoding argument, false otherwise.
Buffer.isBuffer(obj)
Tests if obj is a Buffer.
Buffer.byteLength(string[, encoding])
Gives the actual byte length of a string. encoding defaults to 'utf8'. It is not the same as String.prototype.length, since String.prototype.length returns the number of characters in a string.
Buffer.concat(list[, totalLength])
Returns a buffer which is the result of concatenating all the buffers in the list together.
Buffer.compare(buf1, buf2)
The same as buf1.compare(buf2). Useful for sorting an array of buffers.
44 Lectures
7.5 hours
Eduonix Learning Solutions
88 Lectures
17 hours
Eduonix Learning Solutions
32 Lectures
1.5 hours
Richard Wells
8 Lectures
33 mins
Anant Rungta
9 Lectures
2.5 hours
SHIVPRASAD KOIRALA
97 Lectures
6 hours
Skillbakerystudios
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2346,
"s": 2018,
"text": "Pure JavaScript is Unicode friendly, but it is not so for binary data. While dealing with TCP streams or the file system, it's necessary to handle octet streams. Node provides Buffer class which provides instances to store raw data similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap."
},
{
"code": null,
"e": 2453,
"s": 2346,
"text": "Buffer class is a global class that can be accessed in an application without importing the buffer module."
},
{
"code": null,
"e": 2506,
"s": 2453,
"text": "Node Buffer can be constructed in a variety of ways."
},
{
"code": null,
"e": 2577,
"s": 2506,
"text": "Following is the syntax to create an uninitiated Buffer of 10 octets −"
},
{
"code": null,
"e": 2604,
"s": 2577,
"text": "var buf = new Buffer(10);\n"
},
{
"code": null,
"e": 2668,
"s": 2604,
"text": "Following is the syntax to create a Buffer from a given array −"
},
{
"code": null,
"e": 2713,
"s": 2668,
"text": "var buf = new Buffer([10, 20, 30, 40, 50]);\n"
},
{
"code": null,
"e": 2807,
"s": 2713,
"text": "Following is the syntax to create a Buffer from a given string and optionally encoding type −"
},
{
"code": null,
"e": 2863,
"s": 2807,
"text": "var buf = new Buffer(\"Simply Easy Learning\", \"utf-8\");\n"
},
{
"code": null,
"e": 3000,
"s": 2863,
"text": "Though \"utf8\" is the default encoding, you can use any of the following encodings \"ascii\", \"utf8\", \"utf16le\", \"ucs2\", \"base64\" or \"hex\"."
},
{
"code": null,
"e": 3068,
"s": 3000,
"text": "Following is the syntax of the method to write into a Node Buffer −"
},
{
"code": null,
"e": 3119,
"s": 3068,
"text": "buf.write(string[, offset][, length][, encoding])\n"
},
{
"code": null,
"e": 3168,
"s": 3119,
"text": "Here is the description of the parameters used −"
},
{
"code": null,
"e": 3226,
"s": 3168,
"text": "string − This is the string data to be written to buffer."
},
{
"code": null,
"e": 3284,
"s": 3226,
"text": "string − This is the string data to be written to buffer."
},
{
"code": null,
"e": 3366,
"s": 3284,
"text": "offset − This is the index of the buffer to start writing at. Default value is 0."
},
{
"code": null,
"e": 3448,
"s": 3366,
"text": "offset − This is the index of the buffer to start writing at. Default value is 0."
},
{
"code": null,
"e": 3522,
"s": 3448,
"text": "length − This is the number of bytes to write. Defaults to buffer.length."
},
{
"code": null,
"e": 3596,
"s": 3522,
"text": "length − This is the number of bytes to write. Defaults to buffer.length."
},
{
"code": null,
"e": 3656,
"s": 3596,
"text": "encoding − Encoding to use. 'utf8' is the default encoding."
},
{
"code": null,
"e": 3716,
"s": 3656,
"text": "encoding − Encoding to use. 'utf8' is the default encoding."
},
{
"code": null,
"e": 3871,
"s": 3716,
"text": "This method returns the number of octets written. If there is not enough space in the buffer to fit the entire string, it will write a part of the string."
},
{
"code": null,
"e": 3976,
"s": 3871,
"text": "buf = new Buffer(256);\nlen = buf.write(\"Simply Easy Learning\");\n\nconsole.log(\"Octets written : \"+ len);"
},
{
"code": null,
"e": 4047,
"s": 3976,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 4068,
"s": 4047,
"text": "Octets written : 20\n"
},
{
"code": null,
"e": 4140,
"s": 4068,
"text": "Following is the syntax of the method to read data from a Node Buffer −"
},
{
"code": null,
"e": 4182,
"s": 4140,
"text": "buf.toString([encoding][, start][, end])\n"
},
{
"code": null,
"e": 4231,
"s": 4182,
"text": "Here is the description of the parameters used −"
},
{
"code": null,
"e": 4291,
"s": 4231,
"text": "encoding − Encoding to use. 'utf8' is the default encoding."
},
{
"code": null,
"e": 4351,
"s": 4291,
"text": "encoding − Encoding to use. 'utf8' is the default encoding."
},
{
"code": null,
"e": 4408,
"s": 4351,
"text": "start − Beginning index to start reading, defaults to 0."
},
{
"code": null,
"e": 4465,
"s": 4408,
"text": "start − Beginning index to start reading, defaults to 0."
},
{
"code": null,
"e": 4526,
"s": 4465,
"text": "end − End index to end reading, defaults is complete buffer."
},
{
"code": null,
"e": 4587,
"s": 4526,
"text": "end − End index to end reading, defaults is complete buffer."
},
{
"code": null,
"e": 4697,
"s": 4587,
"text": "This method decodes and returns a string from buffer data encoded using the specified character set encoding."
},
{
"code": null,
"e": 5067,
"s": 4697,
"text": "buf = new Buffer(26);\nfor (var i = 0 ; i < 26 ; i++) {\n buf[i] = i + 97;\n}\n\nconsole.log( buf.toString('ascii')); // outputs: abcdefghijklmnopqrstuvwxyz\nconsole.log( buf.toString('ascii',0,5)); // outputs: abcde\nconsole.log( buf.toString('utf8',0,5)); // outputs: abcde\nconsole.log( buf.toString(undefined,0,5)); // encoding defaults to 'utf8', outputs abcde"
},
{
"code": null,
"e": 5138,
"s": 5067,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 5184,
"s": 5138,
"text": "abcdefghijklmnopqrstuvwxyz\nabcde\nabcde\nabcde\n"
},
{
"code": null,
"e": 5266,
"s": 5184,
"text": "Following is the syntax of the method to convert a Node Buffer into JSON object −"
},
{
"code": null,
"e": 5280,
"s": 5266,
"text": "buf.toJSON()\n"
},
{
"code": null,
"e": 5346,
"s": 5280,
"text": "This method returns a JSON-representation of the Buffer instance."
},
{
"code": null,
"e": 5440,
"s": 5346,
"text": "var buf = new Buffer('Simply Easy Learning');\nvar json = buf.toJSON(buf);\n\nconsole.log(json);"
},
{
"code": null,
"e": 5511,
"s": 5440,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 5766,
"s": 5511,
"text": "{ type: 'Buffer',\n data: \n [ \n 83,\n 105,\n 109,\n 112,\n 108,\n 121,\n 32,\n 69,\n 97,\n 115,\n 121,\n 32,\n 76,\n 101,\n 97,\n 114,\n 110,\n 105,\n 110,\n 103 \n ]\n}\n"
},
{
"code": null,
"e": 5858,
"s": 5766,
"text": "Following is the syntax of the method to concatenate Node buffers to a single Node Buffer −"
},
{
"code": null,
"e": 5894,
"s": 5858,
"text": "Buffer.concat(list[, totalLength])\n"
},
{
"code": null,
"e": 5943,
"s": 5894,
"text": "Here is the description of the parameters used −"
},
{
"code": null,
"e": 5999,
"s": 5943,
"text": "list − Array List of Buffer objects to be concatenated."
},
{
"code": null,
"e": 6055,
"s": 5999,
"text": "list − Array List of Buffer objects to be concatenated."
},
{
"code": null,
"e": 6128,
"s": 6055,
"text": "totalLength − This is the total length of the buffers when concatenated."
},
{
"code": null,
"e": 6201,
"s": 6128,
"text": "totalLength − This is the total length of the buffers when concatenated."
},
{
"code": null,
"e": 6240,
"s": 6201,
"text": "This method returns a Buffer instance."
},
{
"code": null,
"e": 6439,
"s": 6240,
"text": "var buffer1 = new Buffer('TutorialsPoint ');\nvar buffer2 = new Buffer('Simply Easy Learning');\nvar buffer3 = Buffer.concat([buffer1,buffer2]);\n\nconsole.log(\"buffer3 content: \" + buffer3.toString());"
},
{
"code": null,
"e": 6510,
"s": 6439,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 6564,
"s": 6510,
"text": "buffer3 content: TutorialsPoint Simply Easy Learning\n"
},
{
"code": null,
"e": 6632,
"s": 6564,
"text": "Following is the syntax of the method to compare two Node buffers −"
},
{
"code": null,
"e": 6659,
"s": 6632,
"text": "buf.compare(otherBuffer);\n"
},
{
"code": null,
"e": 6708,
"s": 6659,
"text": "Here is the description of the parameters used −"
},
{
"code": null,
"e": 6779,
"s": 6708,
"text": "otherBuffer − This is the other buffer which will be compared with buf"
},
{
"code": null,
"e": 6850,
"s": 6779,
"text": "otherBuffer − This is the other buffer which will be compared with buf"
},
{
"code": null,
"e": 6960,
"s": 6850,
"text": "Returns a number indicating whether it comes before or after or is the same as the otherBuffer in sort order."
},
{
"code": null,
"e": 7277,
"s": 6960,
"text": "var buffer1 = new Buffer('ABC');\nvar buffer2 = new Buffer('ABCD');\nvar result = buffer1.compare(buffer2);\n\nif(result < 0) {\n console.log(buffer1 +\" comes before \" + buffer2);\n} else if(result === 0) {\n console.log(buffer1 +\" is same as \" + buffer2);\n} else {\n console.log(buffer1 +\" comes after \" + buffer2);\n}"
},
{
"code": null,
"e": 7348,
"s": 7277,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 7371,
"s": 7348,
"text": "ABC comes before ABCD\n"
},
{
"code": null,
"e": 7433,
"s": 7371,
"text": "Following is the syntax of the method to copy a node buffer −"
},
{
"code": null,
"e": 7500,
"s": 7433,
"text": "buf.copy(targetBuffer[, targetStart][, sourceStart][, sourceEnd])\n"
},
{
"code": null,
"e": 7549,
"s": 7500,
"text": "Here is the description of the parameters used −"
},
{
"code": null,
"e": 7607,
"s": 7549,
"text": "targetBuffer − Buffer object where buffer will be copied."
},
{
"code": null,
"e": 7665,
"s": 7607,
"text": "targetBuffer − Buffer object where buffer will be copied."
},
{
"code": null,
"e": 7708,
"s": 7665,
"text": "targetStart − Number, Optional, Default: 0"
},
{
"code": null,
"e": 7751,
"s": 7708,
"text": "targetStart − Number, Optional, Default: 0"
},
{
"code": null,
"e": 7794,
"s": 7751,
"text": "sourceStart − Number, Optional, Default: 0"
},
{
"code": null,
"e": 7837,
"s": 7794,
"text": "sourceStart − Number, Optional, Default: 0"
},
{
"code": null,
"e": 7890,
"s": 7837,
"text": "sourceEnd − Number, Optional, Default: buffer.length"
},
{
"code": null,
"e": 7943,
"s": 7890,
"text": "sourceEnd − Number, Optional, Default: buffer.length"
},
{
"code": null,
"e": 8207,
"s": 7943,
"text": "No return value. Copies data from a region of this buffer to a region in the target buffer even if the target memory region overlaps with the source. If undefined, the targetStart and sourceStart parameters default to 0, while sourceEnd defaults to buffer.length."
},
{
"code": null,
"e": 8364,
"s": 8207,
"text": "var buffer1 = new Buffer('ABC');\n\n//copy a buffer\nvar buffer2 = new Buffer(3);\nbuffer1.copy(buffer2);\nconsole.log(\"buffer2 content: \" + buffer2.toString());"
},
{
"code": null,
"e": 8435,
"s": 8364,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 8457,
"s": 8435,
"text": "buffer2 content: ABC\n"
},
{
"code": null,
"e": 8534,
"s": 8457,
"text": "Following is the syntax of the method to get a sub-buffer of a node buffer −"
},
{
"code": null,
"e": 8561,
"s": 8534,
"text": "buf.slice([start][, end])\n"
},
{
"code": null,
"e": 8610,
"s": 8561,
"text": "Here is the description of the parameters used −"
},
{
"code": null,
"e": 8647,
"s": 8610,
"text": "start − Number, Optional, Default: 0"
},
{
"code": null,
"e": 8684,
"s": 8647,
"text": "start − Number, Optional, Default: 0"
},
{
"code": null,
"e": 8731,
"s": 8684,
"text": "end − Number, Optional, Default: buffer.length"
},
{
"code": null,
"e": 8778,
"s": 8731,
"text": "end − Number, Optional, Default: buffer.length"
},
{
"code": null,
"e": 8996,
"s": 8778,
"text": "Returns a new buffer which references the same memory as the old one, but offset and cropped by the start (defaults to 0) and end (defaults to buffer.length) indexes. Negative indexes start from the end of the buffer."
},
{
"code": null,
"e": 9149,
"s": 8996,
"text": "var buffer1 = new Buffer('TutorialsPoint');\n\n//slicing a buffer\nvar buffer2 = buffer1.slice(0,9);\nconsole.log(\"buffer2 content: \" + buffer2.toString());"
},
{
"code": null,
"e": 9220,
"s": 9149,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 9248,
"s": 9220,
"text": "buffer2 content: Tutorials\n"
},
{
"code": null,
"e": 9328,
"s": 9248,
"text": "Following is the syntax of the method to get a size of a node buffer in bytes −"
},
{
"code": null,
"e": 9341,
"s": 9328,
"text": "buf.length;\n"
},
{
"code": null,
"e": 9380,
"s": 9341,
"text": "Returns the size of a buffer in bytes."
},
{
"code": null,
"e": 9495,
"s": 9380,
"text": "var buffer = new Buffer('TutorialsPoint');\n\n//length of the buffer\nconsole.log(\"buffer length: \" + buffer.length);"
},
{
"code": null,
"e": 9562,
"s": 9495,
"text": "When the above program is executed, it produces following result −"
},
{
"code": null,
"e": 9581,
"s": 9562,
"text": "buffer length: 14\n"
},
{
"code": null,
"e": 9598,
"s": 9581,
"text": "new Buffer(size)"
},
{
"code": null,
"e": 9734,
"s": 9598,
"text": "Allocates a new buffer of size octets. Note that the size must be no more than kMaxLength. Otherwise, a RangeError will be thrown here."
},
{
"code": null,
"e": 9753,
"s": 9734,
"text": "new Buffer(buffer)"
},
{
"code": null,
"e": 9811,
"s": 9753,
"text": "Copies the passed buffer data onto a new Buffer instance."
},
{
"code": null,
"e": 9839,
"s": 9811,
"text": "new Buffer(str[, encoding])"
},
{
"code": null,
"e": 9917,
"s": 9839,
"text": "Allocates a new buffer containing the given str. encoding defaults to 'utf8'."
},
{
"code": null,
"e": 9928,
"s": 9917,
"text": "buf.length"
},
{
"code": null,
"e": 10164,
"s": 9928,
"text": "Returns the size of the buffer in bytes. Note that this is not necessarily the size of the contents. length refers to the amount of memory allocated for the buffer object. It does not change when the contents of the buffer are changed."
},
{
"code": null,
"e": 10214,
"s": 10164,
"text": "buf.write(string[, offset][, length][, encoding])"
},
{
"code": null,
"e": 10409,
"s": 10214,
"text": "Writes a string to the buffer at offset using the given encoding. offset defaults to 0, encoding defaults to 'utf8'. length is the number of bytes to write. Returns the number of octets written."
},
{
"code": null,
"e": 10464,
"s": 10409,
"text": "buf.writeUIntLE(value, offset, byteLength[, noAssert])"
},
{
"code": null,
"e": 10649,
"s": 10464,
"text": "Writes a value to the buffer at the specified offset and byteLength. Supports up to 48 bits of accuracy. Set noAssert to true to skip validation of value and offset. Defaults to false."
},
{
"code": null,
"e": 10704,
"s": 10649,
"text": "buf.writeUIntBE(value, offset, byteLength[, noAssert])"
},
{
"code": null,
"e": 10889,
"s": 10704,
"text": "Writes a value to the buffer at the specified offset and byteLength. Supports up to 48 bits of accuracy. Set noAssert to true to skip validation of value and offset. Defaults to false."
},
{
"code": null,
"e": 10943,
"s": 10889,
"text": "buf.writeIntLE(value, offset, byteLength[, noAssert])"
},
{
"code": null,
"e": 11128,
"s": 10943,
"text": "Writes a value to the buffer at the specified offset and byteLength. Supports up to 48 bits of accuracy. Set noAssert to true to skip validation of value and offset. Defaults to false."
},
{
"code": null,
"e": 11182,
"s": 11128,
"text": "buf.writeIntBE(value, offset, byteLength[, noAssert])"
},
{
"code": null,
"e": 11367,
"s": 11182,
"text": "Writes a value to the buffer at the specified offset and byteLength. Supports up to 48 bits of accuracy. Set noAssert to true to skip validation of value and offset. Defaults to false."
},
{
"code": null,
"e": 11414,
"s": 11367,
"text": "buf.readUIntLE(offset, byteLength[, noAssert])"
},
{
"code": null,
"e": 11633,
"s": 11414,
"text": "A generalized version of all numeric read methods. Supports up to 48 bits of accuracy. Set noAssert to true to skip validation of offset. It means that the offset may be beyond the end of the buffer. Defaults to false."
},
{
"code": null,
"e": 11680,
"s": 11633,
"text": "buf.readUIntBE(offset, byteLength[, noAssert])"
},
{
"code": null,
"e": 11899,
"s": 11680,
"text": "A generalized version of all numeric read methods. Supports up to 48 bits of accuracy. Set noAssert to true to skip validation of offset. It means that the offset may be beyond the end of the buffer. Defaults to false."
},
{
"code": null,
"e": 11945,
"s": 11899,
"text": "buf.readIntLE(offset, byteLength[, noAssert])"
},
{
"code": null,
"e": 12164,
"s": 11945,
"text": "A generalized version of all numeric read methods. Supports up to 48 bits of accuracy. Set noAssert to true to skip validation of offset. It means that the offset may be beyond the end of the buffer. Defaults to false."
},
{
"code": null,
"e": 12210,
"s": 12164,
"text": "buf.readIntBE(offset, byteLength[, noAssert])"
},
{
"code": null,
"e": 12429,
"s": 12210,
"text": "A generalized version of all numeric read methods. Supports up to 48 bits of accuracy. Set noAssert to true to skip validation of offset. It means that the offset may be beyond the end of the buffer. Defaults to false."
},
{
"code": null,
"e": 12470,
"s": 12429,
"text": "buf.toString([encoding][, start][, end])"
},
{
"code": null,
"e": 12568,
"s": 12470,
"text": "Decodes and returns a string from buffer data encoded using the specified character set encoding."
},
{
"code": null,
"e": 12581,
"s": 12568,
"text": "buf.toJSON()"
},
{
"code": null,
"e": 12718,
"s": 12581,
"text": "Returns a JSON-representation of the Buffer instance. JSON.stringify implicitly calls this function when stringifying a Buffer instance."
},
{
"code": null,
"e": 12729,
"s": 12718,
"text": "buf[index]"
},
{
"code": null,
"e": 12861,
"s": 12729,
"text": "Get and set the octet at index. The values refer to individual bytes, so the legal range is between 0x00 and 0xFF hex or 0 and 255."
},
{
"code": null,
"e": 12885,
"s": 12861,
"text": "buf.equals(otherBuffer)"
},
{
"code": null,
"e": 12955,
"s": 12885,
"text": "Returns a boolean if this buffer and otherBuffer have the same bytes."
},
{
"code": null,
"e": 12980,
"s": 12955,
"text": "buf.compare(otherBuffer)"
},
{
"code": null,
"e": 13099,
"s": 12980,
"text": "Returns a number indicating whether this buffer comes before or after or is the same as the otherBuffer in sort order."
},
{
"code": null,
"e": 13165,
"s": 13099,
"text": "buf.copy(targetBuffer[, targetStart][, sourceStart][, sourceEnd])"
},
{
"code": null,
"e": 13412,
"s": 13165,
"text": "Copies data from a region of this buffer to a region in the target buffer even if the target memory region overlaps with the source. If undefined, the targetStart and sourceStart parameters default to 0, while sourceEnd defaults to buffer.length."
},
{
"code": null,
"e": 13438,
"s": 13412,
"text": "buf.slice([start][, end])"
},
{
"code": null,
"e": 13652,
"s": 13438,
"text": "Returns a new buffer which references the same memory as the old, but offset and cropped by the start (defaults to 0) and end (defaults to buffer.length) indexes. Negative indexes start from the end of the buffer."
},
{
"code": null,
"e": 13686,
"s": 13652,
"text": "buf.readUInt8(offset[, noAssert])"
},
{
"code": null,
"e": 13891,
"s": 13686,
"text": "Reads an unsigned 8 bit integer from the buffer at the specified offset. Set noAssert to true to skip validation of offset. It means that the offset may be beyond the end of the buffer. Defaults to false."
},
{
"code": null,
"e": 13928,
"s": 13891,
"text": "buf.readUInt16LE(offset[, noAssert])"
},
{
"code": null,
"e": 14162,
"s": 13928,
"text": "Reads an unsigned 16-bit integer from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false."
},
{
"code": null,
"e": 14199,
"s": 14162,
"text": "buf.readUInt16BE(offset[, noAssert])"
},
{
"code": null,
"e": 14433,
"s": 14199,
"text": "Reads an unsigned 16-bit integer from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false."
},
{
"code": null,
"e": 14470,
"s": 14433,
"text": "buf.readUInt32LE(offset[, noAssert])"
},
{
"code": null,
"e": 14704,
"s": 14470,
"text": "Reads an unsigned 32-bit integer from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false."
},
{
"code": null,
"e": 14741,
"s": 14704,
"text": "buf.readUInt32BE(offset[, noAssert])"
},
{
"code": null,
"e": 14975,
"s": 14741,
"text": "Reads an unsigned 32-bit integer from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false."
},
{
"code": null,
"e": 15008,
"s": 14975,
"text": "buf.readInt8(offset[, noAssert])"
},
{
"code": null,
"e": 15205,
"s": 15008,
"text": "Reads a signed 8-bit integer from the buffer at the specified offset. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false."
},
{
"code": null,
"e": 15241,
"s": 15205,
"text": "buf.readInt16LE(offset[, noAssert])"
},
{
"code": null,
"e": 15472,
"s": 15241,
"text": "Reads a signed 16-bit integer from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false."
},
{
"code": null,
"e": 15508,
"s": 15472,
"text": "buf.readInt16BE(offset[, noAssert])"
},
{
"code": null,
"e": 15739,
"s": 15508,
"text": "Reads a signed 16-bit integer from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false."
},
{
"code": null,
"e": 15775,
"s": 15739,
"text": "buf.readInt32LE(offset[, noAssert])"
},
{
"code": null,
"e": 16006,
"s": 15775,
"text": "Reads a signed 32-bit integer from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false."
},
{
"code": null,
"e": 16042,
"s": 16006,
"text": "buf.readInt32BE(offset[, noAssert])"
},
{
"code": null,
"e": 16273,
"s": 16042,
"text": "Reads a signed 32-bit integer from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false."
},
{
"code": null,
"e": 16309,
"s": 16273,
"text": "buf.readFloatLE(offset[, noAssert])"
},
{
"code": null,
"e": 16531,
"s": 16309,
"text": "Reads a 32-bit float from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false."
},
{
"code": null,
"e": 16567,
"s": 16531,
"text": "buf.readFloatBE(offset[, noAssert])"
},
{
"code": null,
"e": 16789,
"s": 16567,
"text": "Reads a 32-bit float from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false."
},
{
"code": null,
"e": 16826,
"s": 16789,
"text": "buf.readDoubleLE(offset[, noAssert])"
},
{
"code": null,
"e": 17049,
"s": 16826,
"text": "Reads a 64-bit double from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false."
},
{
"code": null,
"e": 17086,
"s": 17049,
"text": "buf.readDoubleBE(offset[, noAssert])"
},
{
"code": null,
"e": 17309,
"s": 17086,
"text": "Reads a 64-bit double from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false."
},
{
"code": null,
"e": 17351,
"s": 17309,
"text": "buf.writeUInt8(value, offset[, noAssert])"
},
{
"code": null,
"e": 17765,
"s": 17351,
"text": "Writes a value to the buffer at the specified offset. Note that the value must be a valid unsigned 8-bit integer. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false."
},
{
"code": null,
"e": 17810,
"s": 17765,
"text": "buf.writeUInt16LE(value, offset[, noAssert])"
},
{
"code": null,
"e": 18258,
"s": 17810,
"text": "Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a valid unsigned 16-bit integer. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of correctness. Defaults to false."
},
{
"code": null,
"e": 18303,
"s": 18258,
"text": "buf.writeUInt16BE(value, offset[, noAssert])"
},
{
"code": null,
"e": 18755,
"s": 18303,
"text": "Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a valid unsigned 16-bit integer. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false."
},
{
"code": null,
"e": 18800,
"s": 18755,
"text": "buf.writeUInt32LE(value, offset[, noAssert])"
},
{
"code": null,
"e": 19252,
"s": 18800,
"text": "Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a valid unsigned 32-bit integer. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false."
},
{
"code": null,
"e": 19297,
"s": 19252,
"text": "buf.writeUInt32BE(value, offset[, noAssert])"
},
{
"code": null,
"e": 19749,
"s": 19297,
"text": "Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a valid unsigned 32-bit integer. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false."
},
{
"code": null,
"e": 19790,
"s": 19749,
"text": "buf.writeInt8(value, offset[, noAssert])"
},
{
"code": null,
"e": 20239,
"s": 19790,
"text": "Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a valid signed 8-bit integer. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false."
},
{
"code": null,
"e": 20283,
"s": 20239,
"text": "buf.writeInt16LE(value, offset[, noAssert])"
},
{
"code": null,
"e": 20733,
"s": 20283,
"text": "Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a valid signed 16-bit integer. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false."
},
{
"code": null,
"e": 20777,
"s": 20733,
"text": "buf.writeInt16BE(value, offset[, noAssert])"
},
{
"code": null,
"e": 21223,
"s": 20777,
"text": "Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a valid signed 16-bit integer. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false."
},
{
"code": null,
"e": 21267,
"s": 21223,
"text": "buf.writeInt32LE(value, offset[, noAssert])"
},
{
"code": null,
"e": 21717,
"s": 21267,
"text": "Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a valid signed 32-bit integer. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false."
},
{
"code": null,
"e": 21761,
"s": 21717,
"text": "buf.writeInt32BE(value, offset[, noAssert])"
},
{
"code": null,
"e": 22207,
"s": 21761,
"text": "Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a valid signed 32-bit integer. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of correctness. Defaults to false."
},
{
"code": null,
"e": 22251,
"s": 22207,
"text": "buf.writeFloatLE(value, offset[, noAssert])"
},
{
"code": null,
"e": 22697,
"s": 22251,
"text": "Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a valid 32-bit float. Set noAssert to true to skip validation of value and offset. It means that the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false."
},
{
"code": null,
"e": 22741,
"s": 22697,
"text": "buf.writeFloatBE(value, offset[, noAssert])"
},
{
"code": null,
"e": 23174,
"s": 22741,
"text": "Writes a value to the buffer at the specified offset with the specified endian format. Note, value must be a valid 32-bit float. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false."
},
{
"code": null,
"e": 23219,
"s": 23174,
"text": "buf.writeDoubleLE(value, offset[, noAssert])"
},
{
"code": null,
"e": 23650,
"s": 23219,
"text": "Writes a value to the buffer at the specified offset with the specified endian format. Note, value must be a valid 64-bit double. Set noAssert to true to skip validation of value and offset. It means that value may be too large for the specific function and offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false."
},
{
"code": null,
"e": 23695,
"s": 23650,
"text": "buf.writeDoubleBE(value, offset[, noAssert])"
},
{
"code": null,
"e": 24129,
"s": 23695,
"text": "Writes a value to the buffer at the specified offset with the specified endian format. Note, value must be a valid 64-bit double. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false."
},
{
"code": null,
"e": 24162,
"s": 24129,
"text": "buf.fill(value[, offset][, end])"
},
{
"code": null,
"e": 24318,
"s": 24162,
"text": "Fills the buffer with the specified value. If the offset (defaults to 0) and end (defaults to buffer.length) are not given, it will fill the entire buffer."
},
{
"code": null,
"e": 24346,
"s": 24318,
"text": "Buffer.isEncoding(encoding)"
},
{
"code": null,
"e": 24422,
"s": 24346,
"text": "Returns true if the encoding is a valid encoding argument, false otherwise."
},
{
"code": null,
"e": 24443,
"s": 24422,
"text": "Buffer.isBuffer(obj)"
},
{
"code": null,
"e": 24469,
"s": 24443,
"text": "Tests if obj is a Buffer."
},
{
"code": null,
"e": 24507,
"s": 24469,
"text": "Buffer.byteLength(string[, encoding])"
},
{
"code": null,
"e": 24701,
"s": 24507,
"text": "Gives the actual byte length of a string. encoding defaults to 'utf8'. It is not the same as String.prototype.length, since String.prototype.length returns the number of characters in a string."
},
{
"code": null,
"e": 24736,
"s": 24701,
"text": "Buffer.concat(list[, totalLength])"
},
{
"code": null,
"e": 24828,
"s": 24736,
"text": "Returns a buffer which is the result of concatenating all the buffers in the list together."
},
{
"code": null,
"e": 24855,
"s": 24828,
"text": "Buffer.compare(buf1, buf2)"
},
{
"code": null,
"e": 24927,
"s": 24855,
"text": "The same as buf1.compare(buf2). Useful for sorting an array of buffers."
},
{
"code": null,
"e": 24962,
"s": 24927,
"text": "\n 44 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 24990,
"s": 24962,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 25024,
"s": 24990,
"text": "\n 88 Lectures \n 17 hours \n"
},
{
"code": null,
"e": 25052,
"s": 25024,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 25087,
"s": 25052,
"text": "\n 32 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 25102,
"s": 25087,
"text": " Richard Wells"
},
{
"code": null,
"e": 25133,
"s": 25102,
"text": "\n 8 Lectures \n 33 mins\n"
},
{
"code": null,
"e": 25147,
"s": 25133,
"text": " Anant Rungta"
},
{
"code": null,
"e": 25181,
"s": 25147,
"text": "\n 9 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 25201,
"s": 25181,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 25234,
"s": 25201,
"text": "\n 97 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 25254,
"s": 25234,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 25261,
"s": 25254,
"text": " Print"
},
{
"code": null,
"e": 25272,
"s": 25261,
"text": " Add Notes"
}
] |
Basics of FileStream in C# - GeeksforGeeks | 02 Jul, 2020
The FileStream is a class used for reading and writing files in C#. It is part of the System.IO namespace. To manipulate files using FileStream, you need to create an object of FileStream class. This object has four parameters; the Name of the File, FileMode, FileAccess, and FileShare.
The Syntax to declare a FileStream object is given as
FileStream fileObj = new FileStream(file Name/Path, FileMode.field, FileAccess.field, FileShare.field);
Example: In the code given below we write and read some text to a text file. To write the text first create an object of the FileStream class in Create mode and Write access. Store the text you want to write in a variable of type var, it is a keyword used to declare implicit types.
Next, create a byte array and encode the text into UTF8 which is an encoding standard capable of encoding all 1, 112, 064 valid character code points in Unicode. Then using the Write() method write to the text file. The Write() method’s parameters are the byte array to write from, the offset of the text file, and the length of the text. Lastly, close the FileStream object using Close().
To read the text file we create a FileStream object in Open mode and Read access. Declare a byte array to read from the text file and an integer to keep the count of the bytes. Using the Read() method read from the text file. The Read() method’s parameters are the byte array, offset of the text file from where to begin reading, and the length of the text that has to be read. Lastly using GetString() write the read text from the byte array to the console.
// C# program to write and read from // a text file using FileStream classusing System;using System.IO;using System.Text; namespace FileStreamWriteRead { class GFG { static void Main(string[] args) { // Create a FileStream Object // to write to a text file // The parameters are complete // path of the text file in the // system, in Create mode, the // access to this process is // Write and for other // processes is None FileStream fWrite = new FileStream(@"M:\Documents\Textfile.txt", FileMode.Create, FileAccess.Write, FileShare.None); // Store the text in the variable text var text = "This is some text written to the textfile "+ "named Textfile using FileStream class."; // Store the text in a byte array with // UTF8 encoding (8-bit Unicode // Transformation Format) byte[] writeArr = Encoding.UTF8.GetBytes(text); // Using the Write method write // the encoded byte array to // the textfile fWrite.Write(writeArr, 0, text.Length); // Closee the FileStream object fWrite.Close(); // Create a FileStream Object // to read from a text file // The parameters are complete // path of the text file in // the system, in Open mode, // the access to this process is // Read and for other processes // is Read as well FileStream fRead = new FileStream(@"M:\Documents\Textfile.txt", FileMode.Open, FileAccess.Read, FileShare.Read); // Create a byte array // to read from the // text file byte[] readArr = new byte[text.Length]; int count; // Using the Read method // read until end of file while ((count = fRead.Read(readArr, 0, readArr.Length)) > 0) { Console.WriteLine(Encoding.UTF8.GetString(readArr, 0, count)); } // Close the FileStream Object fRead.Close(); Console.ReadKey(); }}}
Output:
CSharp-File-Handling
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 50 C# Interview Questions & Answers
Extension Method in C#
HashSet in C# with Examples
Partial Classes in C#
C# | Inheritance
Convert String to Character Array in C#
Linked List Implementation in C#
C# | How to insert an element in an Array?
C# | List Class
Difference between Hashtable and Dictionary in C# | [
{
"code": null,
"e": 23911,
"s": 23883,
"text": "\n02 Jul, 2020"
},
{
"code": null,
"e": 24198,
"s": 23911,
"text": "The FileStream is a class used for reading and writing files in C#. It is part of the System.IO namespace. To manipulate files using FileStream, you need to create an object of FileStream class. This object has four parameters; the Name of the File, FileMode, FileAccess, and FileShare."
},
{
"code": null,
"e": 24252,
"s": 24198,
"text": "The Syntax to declare a FileStream object is given as"
},
{
"code": null,
"e": 24356,
"s": 24252,
"text": "FileStream fileObj = new FileStream(file Name/Path, FileMode.field, FileAccess.field, FileShare.field);"
},
{
"code": null,
"e": 24639,
"s": 24356,
"text": "Example: In the code given below we write and read some text to a text file. To write the text first create an object of the FileStream class in Create mode and Write access. Store the text you want to write in a variable of type var, it is a keyword used to declare implicit types."
},
{
"code": null,
"e": 25029,
"s": 24639,
"text": "Next, create a byte array and encode the text into UTF8 which is an encoding standard capable of encoding all 1, 112, 064 valid character code points in Unicode. Then using the Write() method write to the text file. The Write() method’s parameters are the byte array to write from, the offset of the text file, and the length of the text. Lastly, close the FileStream object using Close()."
},
{
"code": null,
"e": 25488,
"s": 25029,
"text": "To read the text file we create a FileStream object in Open mode and Read access. Declare a byte array to read from the text file and an integer to keep the count of the bytes. Using the Read() method read from the text file. The Read() method’s parameters are the byte array, offset of the text file from where to begin reading, and the length of the text that has to be read. Lastly using GetString() write the read text from the byte array to the console."
},
{
"code": "// C# program to write and read from // a text file using FileStream classusing System;using System.IO;using System.Text; namespace FileStreamWriteRead { class GFG { static void Main(string[] args) { // Create a FileStream Object // to write to a text file // The parameters are complete // path of the text file in the // system, in Create mode, the // access to this process is // Write and for other // processes is None FileStream fWrite = new FileStream(@\"M:\\Documents\\Textfile.txt\", FileMode.Create, FileAccess.Write, FileShare.None); // Store the text in the variable text var text = \"This is some text written to the textfile \"+ \"named Textfile using FileStream class.\"; // Store the text in a byte array with // UTF8 encoding (8-bit Unicode // Transformation Format) byte[] writeArr = Encoding.UTF8.GetBytes(text); // Using the Write method write // the encoded byte array to // the textfile fWrite.Write(writeArr, 0, text.Length); // Closee the FileStream object fWrite.Close(); // Create a FileStream Object // to read from a text file // The parameters are complete // path of the text file in // the system, in Open mode, // the access to this process is // Read and for other processes // is Read as well FileStream fRead = new FileStream(@\"M:\\Documents\\Textfile.txt\", FileMode.Open, FileAccess.Read, FileShare.Read); // Create a byte array // to read from the // text file byte[] readArr = new byte[text.Length]; int count; // Using the Read method // read until end of file while ((count = fRead.Read(readArr, 0, readArr.Length)) > 0) { Console.WriteLine(Encoding.UTF8.GetString(readArr, 0, count)); } // Close the FileStream Object fRead.Close(); Console.ReadKey(); }}}",
"e": 27594,
"s": 25488,
"text": null
},
{
"code": null,
"e": 27602,
"s": 27594,
"text": "Output:"
},
{
"code": null,
"e": 27623,
"s": 27602,
"text": "CSharp-File-Handling"
},
{
"code": null,
"e": 27626,
"s": 27623,
"text": "C#"
},
{
"code": null,
"e": 27724,
"s": 27626,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27733,
"s": 27724,
"text": "Comments"
},
{
"code": null,
"e": 27746,
"s": 27733,
"text": "Old Comments"
},
{
"code": null,
"e": 27786,
"s": 27746,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 27809,
"s": 27786,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 27837,
"s": 27809,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 27859,
"s": 27837,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 27876,
"s": 27859,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 27916,
"s": 27876,
"text": "Convert String to Character Array in C#"
},
{
"code": null,
"e": 27949,
"s": 27916,
"text": "Linked List Implementation in C#"
},
{
"code": null,
"e": 27992,
"s": 27949,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 28008,
"s": 27992,
"text": "C# | List Class"
}
] |
Software Engineering - Quick Guide | Let us first understand what software engineering stands for. The term is made of two words, software and engineering.
Software is more than just a program code. A program is an executable code, which serves some computational purpose. Software is considered to be collection of executable programming code, associated libraries and documentations. Software, when made for a specific requirement is called software product.
Engineering on the other hand, is all about developing products, using well-defined, scientific principles and methods.
Software engineering is an engineering branch associated with development of software product using well-defined scientific principles, methods and procedures. The outcome of software engineering is an efficient and reliable software product.
IEEE defines software engineering as:
(1) The application of a systematic,disciplined,quantifiable approach to the development,operation and maintenance of software; that is, the application of engineering to software.
(2) The study of approaches as in the above statement.
Fritz Bauer, a German computer scientist, defines software engineering as:
Software engineering is the establishment and use of sound engineering principles in order to obtain economically software that is reliable and work efficiently on real machines.
The process of developing a software product using software engineering principles and methods is referred to as software evolution. This includes the initial development of software and its maintenance and updates, till desired software product is developed, which satisfies the expected requirements.
Evolution starts from the requirement gathering process. After which developers create a prototype of the intended software and show it to the users to get their feedback at the early stage of software product development. The users suggest changes, on which several consecutive updates and maintenance keep on changing too. This process changes to the original software, till the desired software is accomplished.
Even after the user has desired software in hand, the advancing technology and the changing requirements force the software product to change accordingly. Re-creating software from scratch and to go one-on-one with requirement is not feasible. The only feasible and economical solution is to update the existing software so that it matches the latest requirements.
Lehman has given laws for software evolution. He divided the software into three different categories:
S-type (static-type) - This is a software, which works strictly according to defined specifications and solutions. The solution and the method to achieve it, both are immediately understood before coding. The s-type software is least subjected to changes hence this is the simplest of all. For example, calculator program for mathematical computation.
P-type (practical-type) - This is a software with a collection of procedures. This is defined by exactly what procedures can do. In this software, the specifications can be described but the solution is not obvious instantly. For example, gaming software.
E-type (embedded-type) - This software works closely as the requirement of real-world environment. This software has a high degree of evolution as there are various changes in laws, taxes etc. in the real world situations. For example, Online trading software.
Lehman has given eight laws for E-Type software evolution -
Continuing change - An E-type software system must continue to adapt to the real world changes, else it becomes progressively less useful.
Increasing complexity - As an E-type software system evolves, its complexity tends to increase unless work is done to maintain or reduce it.
Conservation of familiarity - The familiarity with the software or the knowledge about how it was developed, why was it developed in that particular manner etc. must be retained at any cost, to implement the changes in the system.
Continuing growth- In order for an E-type system intended to resolve some business problem, its size of implementing the changes grows according to the lifestyle changes of the business.
Reducing quality - An E-type software system declines in quality unless rigorously maintained and adapted to a changing operational environment.
Feedback systems- The E-type software systems constitute multi-loop, multi-level feedback systems and must be treated as such to be successfully modified or improved.
Self-regulation - E-type system evolution processes are self-regulating with the distribution of product and process measures close to normal.
Organizational stability - The average effective global activity rate in an evolving E-type system is invariant over the lifetime of the product.
Software paradigms refer to the methods and steps, which are taken while designing the software. There are many methods proposed and are in work today, but we need to see where in the software engineering these paradigms stand. These can be combined into various categories, though each of them is contained in one another:
Programming paradigm is a subset of Software design paradigm which is further a subset of Software development paradigm.
This Paradigm is known as software engineering paradigms where all the engineering concepts pertaining to the development of software are applied. It includes various researches and requirement gathering which helps the software product to build. It consists of –
Requirement gathering
Software design
Programming
This paradigm is a part of Software Development and includes –
Design
Maintenance
Programming
This paradigm is related closely to programming aspect of software development. This includes –
Coding
Testing
Integration
The need of software engineering arises because of higher rate of change in user requirements and environment on which the software is working.
Large software - It is easier to build a wall than to a house or building, likewise, as the size of software become large engineering has to step to give it a scientific process.
Scalability- If the software process were not based on scientific and engineering concepts, it would be easier to re-create new software than to scale an existing one.
Cost- As hardware industry has shown its skills and huge manufacturing has lower down he price of computer and electronic hardware. But the cost of software remains high if proper process is not adapted.
Dynamic Nature- The always growing and adapting nature of software hugely depends upon the environment in which user works. If the nature of software is always changing, new enhancements need to be done in the existing one. This is where software engineering plays a good role.
Quality Management- Better process of software development provides better and quality software product.
A software product can be judged by what it offers and how well it can be used. This software must satisfy on the following grounds:
Operational
Transitional
Maintenance
Well-engineered and crafted software is expected to have the following characteristics:
This tells us how well software works in operations. It can be measured on:
Budget
Usability
Efficiency
Correctness
Functionality
Dependability
Security
Safety
This aspect is important when the software is moved from one platform to another:
Portability
Interoperability
Reusability
Adaptability
This aspect briefs about how well a software has the capabilities to maintain itself in the ever-changing environment:
Modularity
Maintainability
Flexibility
Scalability
In short, Software engineering is a branch of computer science, which uses well-defined engineering concepts required to produce efficient, durable, scalable, in-budget and on-time software products.
Software Development Life Cycle, SDLC for short, is a well-defined, structured sequence of stages in software engineering to develop the intended software product.
SDLC provides a series of steps to be followed to design and develop a software product efficiently. SDLC framework includes the following steps:
This is the first step where the user initiates the request for a desired software product. He contacts the service provider and tries to negotiate the terms. He submits his request to the service providing organization in writing.
This step onwards the software development team works to carry on the project. The team holds discussions with various stakeholders from problem domain and tries to bring out as much information as possible on their requirements. The requirements are contemplated and segregated into user requirements, system requirements and functional requirements. The requirements are collected using a number of practices as given -
studying the existing or obsolete system and software,
conducting interviews of users and developers,
referring to the database or
collecting answers from the questionnaires.
After requirement gathering, the team comes up with a rough plan of software process. At this step the team analyzes if a software can be made to fulfill all requirements of the user and if there is any possibility of software being no more useful. It is found out, if the project is financially, practically and technologically feasible for the organization to take up. There are many algorithms available, which help the developers to conclude the feasibility of a software project.
At this step the developers decide a roadmap of their plan and try to bring up the best software model suitable for the project. System analysis includes Understanding of software product limitations, learning system related problems or changes to be done in existing systems beforehand, identifying and addressing the impact of project on organization and personnel etc. The project team analyzes the scope of the project and plans the schedule and resources accordingly.
Next step is to bring down whole knowledge of requirements and analysis on the desk and design the software product. The inputs from users and information gathered in requirement gathering phase are the inputs of this step. The output of this step comes in the form of two designs; logical design and physical design. Engineers produce meta-data and data dictionaries, logical diagrams, data-flow diagrams and in some cases pseudo codes.
This step is also known as programming phase. The implementation of software design starts in terms of writing program code in the suitable programming language and developing error-free executable programs efficiently.
An estimate says that 50% of whole software development process should be tested. Errors may ruin the software from critical level to its own removal. Software testing is done while coding by the developers and thorough testing is conducted by testing experts at various levels of code such as module testing, program testing, product testing, in-house testing and testing the product at user’s end. Early discovery of errors and their remedy is the key to reliable software.
Software may need to be integrated with the libraries, databases and other program(s). This stage of SDLC is involved in the integration of software with outer world entities.
This means installing the software on user machines. At times, software needs post-installation configurations at user end. Software is tested for portability and adaptability and integration related issues are solved during implementation.
This phase confirms the software operation in terms of more efficiency and less errors. If required, the users are trained on, or aided with the documentation on how to operate the software and how to keep the software operational. The software is maintained timely by updating the code according to the changes taking place in user end environment or technology. This phase may face challenges from hidden bugs and real-world unidentified problems.
As time elapses, the software may decline on the performance front. It may go completely obsolete or may need intense upgradation. Hence a pressing need to eliminate a major portion of the system arises. This phase includes archiving data and required software components, closing down the system, planning disposition activity and terminating system at appropriate end-of-system time.
The software development paradigm helps developer to select a strategy to develop the software. A software development paradigm has its own set of tools, methods and procedures, which are expressed clearly and defines software development life cycle. A few of software development paradigms or process models are defined as follows:
Waterfall model is the simplest model of software development paradigm. It says the all the phases of SDLC will function one after another in linear manner. That is, when the first phase is finished then only the second phase will start and so on.
This model assumes that everything is carried out and taken place perfectly as planned in the previous stage and there is no need to think about the past issues that may arise in the next phase. This model does not work smoothly if there are some issues left at the previous step. The sequential nature of model does not allow us go back and undo or redo our actions.
This model is best suited when developers already have designed and developed similar software in the past and are aware of all its domains.
This model leads the software development process in iterations. It projects the process of development in cyclic manner repeating every step after every cycle of SDLC process.
The software is first developed on very small scale and all the steps are followed which are taken into consideration. Then, on every next iteration, more features and modules are designed, coded, tested and added to the software. Every cycle produces a software, which is complete in itself and has more features and capabilities than that of the previous one.
After each iteration, the management team can do work on risk management and prepare for the next iteration. Because a cycle includes small portion of whole software process, it is easier to manage the development process but it consumes more resources.
Spiral model is a combination of both, iterative model and one of the SDLC model. It can be seen as if you choose one SDLC model and combine it with cyclic process (iterative model).
This model considers risk, which often goes un-noticed by most other models. The model starts with determining objectives and constraints of the software at the start of one iteration. Next phase is of prototyping the software. This includes risk analysis. Then one standard SDLC model is used to build the software. In the fourth phase of the plan of next iteration is prepared.
The major drawback of waterfall model is we move to the next stage only when the previous one is finished and there was no chance to go back if something is found wrong in later stages. V-Model provides means of testing of software at each stage in reverse manner.
At every stage, test plans and test cases are created to verify and validate the product according to the requirement of that stage. For example, in requirement gathering stage the test team prepares all the test cases in correspondence to the requirements. Later, when the product is developed and is ready for testing, test cases of this stage verify the software against its validity towards requirements at this stage.
This makes both verification and validation go in parallel. This model is also known as verification and validation model.
This model is the simplest model in its form. It requires little planning, lots of programming and lots of funds. This model is conceptualized around the big bang of universe. As scientists say that after big bang lots of galaxies, planets and stars evolved just as an event. Likewise, if we put together lots of programming and funds, you may achieve the best software product.
For this model, very small amount of planning is required. It does not follow any process, or at times the customer is not sure about the requirements and future needs. So the input requirements are arbitrary.
This model is not suitable for large software projects but good one for learning and experimenting.
For an in-depth reading on SDLC and its various models, click here.
The job pattern of an IT company engaged in software development can be seen split in two parts:
Software Creation
Software Project Management
A project is well-defined task, which is a collection of several operations done in order to achieve a goal (for example, software development and delivery). A Project can be characterized as:
Every project may has a unique and distinct goal.
Project is not routine activity or day-to-day operations.
Project comes with a start time and end time.
Project ends when its goal is achieved hence it is a temporary phase in the lifetime of an organization.
Project needs adequate resources in terms of time, manpower, finance, material and knowledge-bank.
A Software Project is the complete procedure of software development from requirement gathering to testing and maintenance, carried out according to the execution methodologies, in a specified period of time to achieve intended software product.
Software is said to be an intangible product. Software development is a kind of all new stream in world business and there’s very little experience in building software products. Most software products are tailor made to fit client’s requirements. The most important is that the underlying technology changes and advances so frequently and rapidly that experience of one product may not be applied to the other one. All such business and environmental constraints bring risk in software development hence it is essential to manage software projects efficiently.
The image above shows triple constraints for software projects. It is an essential part of software organization to deliver quality product, keeping the cost within client’s budget constrain and deliver the project as per scheduled. There are several factors, both internal and external, which may impact this triple constrain triangle. Any of three factor can severely impact the other two.
Therefore, software project management is essential to incorporate user requirements along with budget and time constraints.
A software project manager is a person who undertakes the responsibility of executing the software project. Software project manager is thoroughly aware of all the phases of SDLC that the software would go through. Project manager may never directly involve in producing the end product but he controls and manages the activities involved in production.
A project manager closely monitors the development process, prepares and executes various plans, arranges necessary and adequate resources, maintains communication among all team members in order to address issues of cost, budget, resources, time, quality and customer satisfaction.
Let us see few responsibilities that a project manager shoulders -
Act as project leader
Lesion with stakeholders
Managing human resources
Setting up reporting hierarchy etc.
Defining and setting up project scope
Managing project management activities
Monitoring progress and performance
Risk analysis at every phase
Take necessary step to avoid or come out of problems
Act as project spokesperson
Software project management comprises of a number of activities, which contains planning of project, deciding scope of software product, estimation of cost in various terms, scheduling of tasks and events, and resource management. Project management activities may include:
Project Planning
Scope Management
Project Estimation
Software project planning is task, which is performed before the production of software actually starts. It is there for the software production but involves no concrete activity that has any direction connection with software production; rather it is a set of multiple processes, which facilitates software production. Project planning may include the following:
It defines the scope of project; this includes all the activities, process need to be done in order to make a deliverable software product. Scope management is essential because it creates boundaries of the project by clearly defining what would be done in the project and what would not be done. This makes project to contain limited and quantifiable tasks, which can easily be documented and in turn avoids cost and time overrun.
During Project Scope management, it is necessary to -
Define the scope
Decide its verification and control
Divide the project into various smaller parts for ease of management.
Verify the scope
Control the scope by incorporating changes to the scope
For an effective management accurate estimation of various measures is a must. With correct estimation managers can manage and control the project more efficiently and effectively.
Project estimation may involve the following:
Software size estimation
Software size may be estimated either in terms of KLOC (Kilo Line of Code) or by calculating number of function points in the software. Lines of code depend upon coding practices and Function points vary according to the user or software requirement.
Software size may be estimated either in terms of KLOC (Kilo Line of Code) or by calculating number of function points in the software. Lines of code depend upon coding practices and Function points vary according to the user or software requirement.
Effort estimation
The managers estimate efforts in terms of personnel requirement and man-hour required to produce the software. For effort estimation software size should be known. This can either be derived by managers’ experience, organization’s historical data or software size can be converted into efforts by using some standard formulae.
The managers estimate efforts in terms of personnel requirement and man-hour required to produce the software. For effort estimation software size should be known. This can either be derived by managers’ experience, organization’s historical data or software size can be converted into efforts by using some standard formulae.
Time estimation
Once size and efforts are estimated, the time required to produce the software can be estimated. Efforts required is segregated into sub categories as per the requirement specifications and interdependency of various components of software. Software tasks are divided into smaller tasks, activities or events by Work Breakthrough Structure (WBS). The tasks are scheduled on day-to-day basis or in calendar months.
The sum of time required to complete all tasks in hours or days is the total time invested to complete the project.
Once size and efforts are estimated, the time required to produce the software can be estimated. Efforts required is segregated into sub categories as per the requirement specifications and interdependency of various components of software. Software tasks are divided into smaller tasks, activities or events by Work Breakthrough Structure (WBS). The tasks are scheduled on day-to-day basis or in calendar months.
The sum of time required to complete all tasks in hours or days is the total time invested to complete the project.
Cost estimation
This might be considered as the most difficult of all because it depends on more elements than any of the previous ones. For estimating project cost, it is required to consider -
This might be considered as the most difficult of all because it depends on more elements than any of the previous ones. For estimating project cost, it is required to consider -
Size of software
Software quality
Hardware
Additional software or tools, licenses etc.
Skilled personnel with task-specific skills
Travel involved
Communication
Training and support
We discussed various parameters involving project estimation such as size, effort, time and cost.
Project manager can estimate the listed factors using two broadly recognized techniques –
This technique assumes the software as a product of various compositions.
There are two main models -
Line of Code Estimation is done on behalf of number of line of codes in the software product.
Function Points Estimation is done on behalf of number of function points in the software product.
This technique uses empirically derived formulae to make estimation.These formulae are based on LOC or FPs.
Putnam Model
This model is made by Lawrence H. Putnam, which is based on Norden’s frequency distribution (Rayleigh curve). Putnam model maps time and efforts required with software size.
This model is made by Lawrence H. Putnam, which is based on Norden’s frequency distribution (Rayleigh curve). Putnam model maps time and efforts required with software size.
COCOMO
COCOMO stands for COnstructive COst MOdel, developed by Barry W. Boehm. It divides the software product into three categories of software: organic, semi-detached and embedded.
COCOMO stands for COnstructive COst MOdel, developed by Barry W. Boehm. It divides the software product into three categories of software: organic, semi-detached and embedded.
Project Scheduling in a project refers to roadmap of all activities to be done with specified order and within time slot allotted to each activity. Project managers tend to tend to define various tasks, and project milestones and arrange them keeping various factors in mind. They look for tasks lie in critical path in the schedule, which are necessary to complete in specific manner (because of task interdependency) and strictly within the time allocated. Arrangement of tasks which lies out of critical path are less likely to impact over all schedule of the project.
For scheduling a project, it is necessary to -
Break down the project tasks into smaller, manageable form
Find out various tasks and correlate them
Estimate time frame required for each task
Divide time into work-units
Assign adequate number of work-units for each task
Calculate total time required for the project from start to finish
All elements used to develop a software product may be assumed as resource for that project. This may include human resource, productive tools and software libraries.
The resources are available in limited quantity and stay in the organization as a pool of assets. The shortage of resources hampers the development of project and it can lag behind the schedule. Allocating extra resources increases development cost in the end. It is therefore necessary to estimate and allocate adequate resources for the project.
Resource management includes -
Defining proper organization project by creating a project team and allocating responsibilities to each team member
Determining resources required at a particular stage and their availability
Manage Resources by generating resource request when they are required and de-allocating them when they are no more needed.
Risk management involves all activities pertaining to identification, analyzing and making provision for predictable and non-predictable risks in the project. Risk may include the following:
Experienced staff leaving the project and new staff coming in.
Change in organizational management.
Requirement change or misinterpreting requirement.
Under-estimation of required time and resources.
Technological changes, environmental changes, business competition.
There are following activities involved in risk management process:
Identification - Make note of all possible risks, which may occur in the project.
Categorize - Categorize known risks into high, medium and low risk intensity as per their possible impact on the project.
Manage - Analyze the probability of occurrence of risks at various phases. Make plan to avoid or face risks. Attempt to minimize their side-effects.
Monitor - Closely monitor the potential risks and their early symptoms. Also monitor the effects of steps taken to mitigate or avoid them.
In this phase, the tasks described in project plans are executed according to their schedules.
Execution needs monitoring in order to check whether everything is going according to the plan. Monitoring is observing to check the probability of risk and taking measures to address the risk or report the status of various tasks.
These measures include -
Activity Monitoring - All activities scheduled within some task can be monitored on day-to-day basis. When all activities in a task are completed, it is considered as complete.
Status Reports - The reports contain status of activities and tasks completed within a given time frame, generally a week. Status can be marked as finished, pending or work-in-progress etc.
Milestones Checklist - Every project is divided into multiple phases where major tasks are performed (milestones) based on the phases of SDLC. This milestone checklist is prepared once every few weeks and reports the status of milestones.
Effective communication plays vital role in the success of a project. It bridges gaps between client and the organization, among the team members as well as other stake holders in the project such as hardware suppliers.
Communication can be oral or written. Communication management process may have the following steps:
Planning - This step includes the identifications of all the stakeholders in the project and the mode of communication among them. It also considers if any additional communication facilities are required.
Sharing - After determining various aspects of planning, manager focuses on sharing correct information with the correct person on correct time. This keeps every one involved the project up to date with project progress and its status.
Feedback - Project managers use various measures and feedback mechanism and create status and performance reports. This mechanism ensures that input from various stakeholders is coming to the project manager as their feedback.
Closure - At the end of each major event, end of a phase of SDLC or end of the project itself, administrative closure is formally announced to update every stakeholder by sending email, by distributing a hardcopy of document or by other mean of effective communication.
After closure, the team moves to next phase or project.
Configuration management is a process of tracking and controlling the changes in software in terms of the requirements, design, functions and development of the product.
IEEE defines it as “the process of identifying and defining the items in the system, controlling the change of these items throughout their life cycle, recording and reporting the status of items and change requests, and verifying the completeness and correctness of items”.
Generally, once the SRS is finalized there is less chance of requirement of changes from user. If they occur, the changes are addressed only with prior approval of higher management, as there is a possibility of cost and time overrun.
A phase of SDLC is assumed over if it baselined, i.e. baseline is a measurement that defines completeness of a phase. A phase is baselined when all activities pertaining to it are finished and well documented. If it was not the final phase, its output would be used in next immediate phase.
Configuration management is a discipline of organization administration, which takes care of occurrence of any change (process, requirement, technological, strategical etc.) after a phase is baselined. CM keeps check on any changes done in software.
Change control is function of configuration management, which ensures that all changes made to software system are consistent and made as per organizational rules and regulations.
A change in the configuration of product goes through following steps -
Identification - A change request arrives from either internal or external source. When change request is identified formally, it is properly documented.
Identification - A change request arrives from either internal or external source. When change request is identified formally, it is properly documented.
Validation - Validity of the change request is checked and its handling procedure is confirmed.
Validation - Validity of the change request is checked and its handling procedure is confirmed.
Analysis - The impact of change request is analyzed in terms of schedule, cost and required efforts. Overall impact of the prospective change on system is analyzed.
Analysis - The impact of change request is analyzed in terms of schedule, cost and required efforts. Overall impact of the prospective change on system is analyzed.
Control - If the prospective change either impacts too many entities in the system or it is unavoidable, it is mandatory to take approval of high authorities before change is incorporated into the system. It is decided if the change is worth incorporation or not. If it is not, change request is refused formally.
Control - If the prospective change either impacts too many entities in the system or it is unavoidable, it is mandatory to take approval of high authorities before change is incorporated into the system. It is decided if the change is worth incorporation or not. If it is not, change request is refused formally.
Execution - If the previous phase determines to execute the change request, this phase take appropriate actions to execute the change, does a thorough revision if necessary.
Execution - If the previous phase determines to execute the change request, this phase take appropriate actions to execute the change, does a thorough revision if necessary.
Close request - The change is verified for correct implementation and merging with the rest of the system. This newly incorporated change in the software is documented properly and the request is formally is closed.
Close request - The change is verified for correct implementation and merging with the rest of the system. This newly incorporated change in the software is documented properly and the request is formally is closed.
The risk and uncertainty rises multifold with respect to the size of the project, even when the project is developed according to set methodologies.
There are tools available, which aid for effective project management. A few are described -
Gantt charts was devised by Henry Gantt (1917). It represents project schedule with respect to time periods. It is a horizontal bar chart with bars representing activities and time scheduled for the project activities.
PERT (Program Evaluation & Review Technique) chart is a tool that depicts project as network diagram. It is capable of graphically representing main events of project in both parallel and consecutive way. Events, which occur one after another, show dependency of the later event over the previous one.
Events are shown as numbered nodes. They are connected by labeled arrows depicting sequence of tasks in the project.
This is a graphical tool that contains bar or chart representing number of resources (usually skilled staff) required over time for a project event (or phase). Resource Histogram is an effective tool for staff planning and coordination.
This tools is useful in recognizing interdependent tasks in the project. It also helps to find out the shortest path or critical path to complete the project successfully. Like PERT diagram, each event is allotted a specific time frame. This tool shows dependency of event assuming an event can proceed to next only if the previous one is completed.
The events are arranged according to their earliest possible start time. Path between start and end node is critical path which cannot be further reduced and all events require to be executed in same order.
The software requirements are description of features and functionalities of the target system. Requirements convey the expectations of users from the software product. The requirements can be obvious or hidden, known or unknown, expected or unexpected from client’s point of view.
The process to gather the software requirements from client, analyze and document them is known as requirement engineering.
The goal of requirement engineering is to develop and maintain sophisticated and descriptive ‘System Requirements Specification’ document.
It is a four step process, which includes –
Feasibility Study
Requirement Gathering
Software Requirement Specification
Software Requirement Validation
Let us see the process briefly -
When the client approaches the organization for getting the desired product developed, it comes up with rough idea about what all functions the software must perform and which all features are expected from the software.
Referencing to this information, the analysts does a detailed study about whether the desired system and its functionality are feasible to develop.
This feasibility study is focused towards goal of the organization. This study analyzes whether the software product can be practically materialized in terms of implementation, contribution of project to organization, cost constraints and as per values and objectives of the organization. It explores technical aspects of the project and product such as usability, maintainability, productivity and integration ability.
The output of this phase should be a feasibility study report that should contain adequate comments and recommendations for management about whether or not the project should be undertaken.
If the feasibility report is positive towards undertaking the project, next phase starts with gathering requirements from the user. Analysts and engineers communicate with the client and end-users to know their ideas on what the software should provide and which features they want the software to include.
SRS is a document created by system analyst after the requirements are collected from various stakeholders.
SRS defines how the intended software will interact with hardware, external interfaces, speed of operation, response time of system, portability of software across various platforms, maintainability, speed of recovery after crashing, Security, Quality, Limitations etc.
The requirements received from client are written in natural language. It is the responsibility of system analyst to document the requirements in technical language so that they can be comprehended and useful by the software development team.
SRS should come up with following features:
User Requirements are expressed in natural language.
Technical requirements are expressed in structured language, which is used inside the organization.
Design description should be written in Pseudo code.
Format of Forms and GUI screen prints.
Conditional and mathematical notations for DFDs etc.
After requirement specifications are developed, the requirements mentioned in this document are validated. User might ask for illegal, impractical solution or experts may interpret the requirements incorrectly. This results in huge increase in cost if not nipped in the bud. Requirements can be checked against following conditions -
If they can be practically implemented
If they are valid and as per functionality and domain of software
If there are any ambiguities
If they are complete
If they can be demonstrated
Requirement elicitation process can be depicted using the folloiwng diagram:
Requirements gathering - The developers discuss with the client and end users and know their expectations from the software.
Organizing Requirements - The developers prioritize and arrange the requirements in order of importance, urgency and convenience.
Negotiation & discussion - If requirements are ambiguous or there are some conflicts in requirements of various stakeholders, if they are, it is then negotiated and discussed with stakeholders. Requirements may then be prioritized and reasonably compromised.
The requirements come from various stakeholders. To remove the ambiguity and conflicts, they are discussed for clarity and correctness. Unrealistic requirements are compromised reasonably.
Negotiation & discussion - If requirements are ambiguous or there are some conflicts in requirements of various stakeholders, if they are, it is then negotiated and discussed with stakeholders. Requirements may then be prioritized and reasonably compromised.
The requirements come from various stakeholders. To remove the ambiguity and conflicts, they are discussed for clarity and correctness. Unrealistic requirements are compromised reasonably.
Documentation - All formal & informal, functional and non-functional requirements are documented and made available for next phase processing.
Requirements Elicitation is the process to find out the requirements for an intended software system by communicating with client, end users, system users and others who have a stake in the software system development.
There are various ways to discover requirements
Interviews are strong medium to collect requirements. Organization may conduct several types of interviews such as:
Structured (closed) interviews, where every single information to gather is decided in advance, they follow pattern and matter of discussion firmly.
Non-structured (open) interviews, where information to gather is not decided in advance, more flexible and less biased.
Oral interviews
Written interviews
One-to-one interviews which are held between two persons across the table.
Group interviews which are held between groups of participants. They help to uncover any missing requirement as numerous people are involved.
Organization may conduct surveys among various stakeholders by querying about their expectation and requirements from the upcoming system.
A document with pre-defined set of objective questions and respective options is handed over to all stakeholders to answer, which are collected and compiled.
A shortcoming of this technique is, if an option for some issue is not mentioned in the questionnaire, the issue might be left unattended.
Team of engineers and developers may analyze the operation for which the new system is required. If the client already has some software to perform certain operation, it is studied and requirements of proposed system are collected.
Every software falls into some domain category. The expert people in the domain can be a great help to analyze general and specific requirements.
An informal debate is held among various stakeholders and all their inputs are recorded for further requirements analysis.
Prototyping is building user interface without adding detail functionality for user to interpret the features of intended software product. It helps giving better idea of requirements. If there is no software installed at client’s end for developer’s reference and the client is not aware of its own requirements, the developer creates a prototype based on initially mentioned requirements. The prototype is shown to the client and the feedback is noted. The client feedback serves as an input for requirement gathering.
Team of experts visit the client’s organization or workplace. They observe the actual working of the existing installed systems. They observe the workflow at client’s end and how execution problems are dealt. The team itself draws some conclusions which aid to form requirements expected from the software.
Gathering software requirements is the foundation of the entire software development project. Hence they must be clear, correct and well-defined.
A complete Software Requirement Specifications must be:
Clear
Correct
Consistent
Coherent
Comprehensible
Modifiable
Verifiable
Prioritized
Unambiguous
Traceable
Credible source
We should try to understand what sort of requirements may arise in the requirement elicitation phase and what kinds of requirements are expected from the software system.
Broadly software requirements should be categorized in two categories:
Requirements, which are related to functional aspect of software fall into this category.
They define functions and functionality within and from the software system.
Search option given to user to search from various invoices.
User should be able to mail any report to management.
Users can be divided into groups and groups can be given separate rights.
Should comply business rules and administrative functions.
Software is developed keeping downward compatibility intact.
Requirements, which are not related to functional aspect of software, fall into this category. They are implicit or expected characteristics of software, which users make assumption of.
Non-functional requirements include -
Security
Logging
Storage
Configuration
Performance
Cost
Interoperability
Flexibility
Disaster recovery
Accessibility
Requirements are categorized logically as
Must Have : Software cannot be said operational without them.
Should have : Enhancing the functionality of software.
Could have : Software can still properly function with these requirements.
Wish list : These requirements do not map to any objectives of software.
While developing software, ‘Must have’ must be implemented, ‘Should have’ is a matter of debate with stakeholders and negation, whereas ‘could have’ and ‘wish list’ can be kept for software updates.
UI is an important part of any software or hardware or hybrid system. A software is widely accepted if it is -
easy to operate
quick in response
effectively handling operational errors
providing simple yet consistent user interface
User acceptance majorly depends upon how user can use the software. UI is the only way for users to perceive the system. A well performing software system must also be equipped with attractive, clear, consistent and responsive user interface. Otherwise the functionalities of software system can not be used in convenient way. A system is said be good if it provides means to use it efficiently. User interface requirements are briefly mentioned below -
Content presentation
Easy Navigation
Simple interface
Responsive
Consistent UI elements
Feedback mechanism
Default settings
Purposeful layout
Strategical use of color and texture.
Provide help information
User centric approach
Group based view settings.
System analyst in an IT organization is a person, who analyzes the requirement of proposed system and ensures that requirements are conceived and documented properly & correctly. Role of an analyst starts during Software Analysis Phase of SDLC. It is the responsibility of analyst to make sure that the developed software meets the requirements of the client.
System Analysts have the following responsibilities:
Analyzing and understanding requirements of intended software
Understanding how the project will contribute in the organization objectives
Identify sources of requirement
Validation of requirement
Develop and implement requirement management plan
Documentation of business, technical, process and product requirements
Coordination with clients to prioritize requirements and remove and ambiguity
Finalizing acceptance criteria with client and other stakeholders
Software Measures can be understood as a process of quantifying and symbolizing various attributes and aspects of software.
Software Metrics provide measures for various aspects of software process and software product.
Software measures are fundamental requirement of software engineering. They not only help to control the software development process but also aid to keep quality of ultimate product excellent.
According to Tom DeMarco, a (Software Engineer), “You cannot control what you cannot measure.” By his saying, it is very clear how important software measures are.
Let us see some software metrics:
Size Metrics - LOC (Lines of Code), mostly calculated in thousands of delivered source code lines, denoted as KLOC.
Function Point Count is measure of the functionality provided by the software. Function Point count defines the size of functional aspect of software.
Size Metrics - LOC (Lines of Code), mostly calculated in thousands of delivered source code lines, denoted as KLOC.
Function Point Count is measure of the functionality provided by the software. Function Point count defines the size of functional aspect of software.
Complexity Metrics - McCabe’s Cyclomatic complexity quantifies the upper bound of the number of independent paths in a program, which is perceived as complexity of the program or its modules. It is represented in terms of graph theory concepts by using control flow graph.
Quality Metrics - Defects, their types and causes, consequence, intensity of severity and their implications define the quality of product.
The number of defects found in development process and number of defects reported by the client after the product is installed or delivered at client-end, define quality of product.
Quality Metrics - Defects, their types and causes, consequence, intensity of severity and their implications define the quality of product.
The number of defects found in development process and number of defects reported by the client after the product is installed or delivered at client-end, define quality of product.
Process Metrics - In various phases of SDLC, the methods and tools used, the company standards and the performance of development are software process metrics.
Resource Metrics - Effort, time and various resources used, represents metrics for resource measurement.
Software design is a process to transform user requirements into some suitable form, which helps the programmer in software coding and implementation.
For assessing user requirements, an SRS (Software Requirement Specification) document is created whereas for coding and implementation, there is a need of more specific and detailed requirements in software terms. The output of this process can directly be used into implementation in programming languages.
Software design is the first step in SDLC (Software Design Life Cycle), which moves the concentration from problem domain to solution domain. It tries to specify how to fulfill the requirements mentioned in SRS.
Software design yields three levels of results:
Architectural Design - The architectural design is the highest abstract version of the system. It identifies the software as a system with many components interacting with each other. At this level, the designers get the idea of proposed solution domain.
High-level Design- The high-level design breaks the ‘single entity-multiple component’ concept of architectural design into less-abstracted view of sub-systems and modules and depicts their interaction with each other. High-level design focuses on how the system along with all of its components can be implemented in forms of modules. It recognizes modular structure of each sub-system and their relation and interaction among each other.
Detailed Design- Detailed design deals with the implementation part of what is seen as a system and its sub-systems in the previous two designs. It is more detailed towards modules and their implementations. It defines logical structure of each module and their interfaces to communicate with other modules.
Modularization is a technique to divide a software system into multiple discrete and independent modules, which are expected to be capable of carrying out task(s) independently. These modules may work as basic constructs for the entire software. Designers tend to design modules such that they can be executed and/or compiled separately and independently.
Modular design unintentionally follows the rules of ‘divide and conquer’ problem-solving strategy this is because there are many other benefits attached with the modular design of a software.
Advantage of modularization:
Smaller components are easier to maintain
Program can be divided based on functional aspects
Desired level of abstraction can be brought in the program
Components with high cohesion can be re-used again
Concurrent execution can be made possible
Desired from security aspect
Back in time, all software are meant to be executed sequentially. By sequential execution we mean that the coded instruction will be executed one after another implying only one portion of program being activated at any given time. Say, a software has multiple modules, then only one of all the modules can be found active at any time of execution.
In software design, concurrency is implemented by splitting the software into multiple independent units of execution, like modules and executing them in parallel. In other words, concurrency provides capability to the software to execute more than one part of code in parallel to each other.
It is necessary for the programmers and designers to recognize those modules, which can be made parallel execution.
The spell check feature in word processor is a module of software, which runs along side the word processor itself.
When a software program is modularized, its tasks are divided into several modules based on some characteristics. As we know, modules are set of instructions put together in order to achieve some tasks. They are though, considered as single entity but may refer to each other to work together. There are measures by which the quality of a design of modules and their interaction among them can be measured. These measures are called coupling and cohesion.
Cohesion is a measure that defines the degree of intra-dependability within elements of a module. The greater the cohesion, the better is the program design.
There are seven types of cohesion, namely –
Co-incidental cohesion - It is unplanned and random cohesion, which might be the result of breaking the program into smaller modules for the sake of modularization. Because it is unplanned, it may serve confusion to the programmers and is generally not-accepted.
Logical cohesion - When logically categorized elements are put together into a module, it is called logical cohesion.
emporal Cohesion - When elements of module are organized such that they are processed at a similar point in time, it is called temporal cohesion.
Procedural cohesion - When elements of module are grouped together, which are executed sequentially in order to perform a task, it is called procedural cohesion.
Communicational cohesion - When elements of module are grouped together, which are executed sequentially and work on same data (information), it is called communicational cohesion.
Sequential cohesion - When elements of module are grouped because the output of one element serves as input to another and so on, it is called sequential cohesion.
Functional cohesion - It is considered to be the highest degree of cohesion, and it is highly expected. Elements of module in functional cohesion are grouped because they all contribute to a single well-defined function. It can also be reused.
Coupling is a measure that defines the level of inter-dependability among modules of a program. It tells at what level the modules interfere and interact with each other. The lower the coupling, the better the program.
There are five levels of coupling, namely -
Content coupling - When a module can directly access or modify or refer to the content of another module, it is called content level coupling.
Common coupling- When multiple modules have read and write access to some global data, it is called common or global coupling.
Control coupling- Two modules are called control-coupled if one of them decides the function of the other module or changes its flow of execution.
Stamp coupling- When multiple modules share common data structure and work on different part of it, it is called stamp coupling.
Data coupling- Data coupling is when two modules interact with each other by means of passing data (as parameter). If a module passes data structure as parameter, then the receiving module should use all its components.
Ideally, no coupling is considered to be the best.
The output of software design process is design documentation, pseudo codes, detailed logic diagrams, process diagrams, and detailed description of all functional or non-functional requirements.
The next phase, which is the implementation of software, depends on all outputs mentioned above.
It is then becomes necessary to verify the output before proceeding to the next phase. The early any mistake is detected, the better it is or it might not be detected until testing of the product. If the outputs of design phase are in formal notation form, then their associated tools for verification should be used otherwise a thorough design review can be used for verification and validation.
By structured verification approach, reviewers can detect defects that might be caused by overlooking some conditions. A good design review is important for good software design, accuracy and quality.
Software analysis and design includes all activities, which help the transformation of requirement specification into implementation. Requirement specifications specify all functional and non-functional expectations from the software. These requirement specifications come in the shape of human readable and understandable documents, to which a computer has nothing to do.
Software analysis and design is the intermediate stage, which helps human-readable requirements to be transformed into actual code.
Let us see few analysis and design tools used by software designers:
Data flow diagram is graphical representation of flow of data in an information system. It is capable of depicting incoming data flow, outgoing data flow and stored data. The DFD does not mention anything about how data flows through the system.
There is a prominent difference between DFD and Flowchart. The flowchart depicts flow of control in program modules. DFDs depict flow of data in the system at various levels. DFD does not contain any control or branch elements.
Data Flow Diagrams are either Logical or Physical.
Logical DFD - This type of DFD concentrates on the system process, and flow of data in the system.For example in a Banking software system, how data is moved between different entities.
Physical DFD - This type of DFD shows how the data flow is actually implemented in the system. It is more specific and close to the implementation.
DFD can represent Source, destination, storage and flow of data using the following set of components -
Entities - Entities are source and destination of information data. Entities are represented by a rectangles with their respective names.
Process - Activities and action taken on the data are represented by Circle or Round-edged rectangles.
Data Storage - There are two variants of data storage - it can either be represented as a rectangle with absence of both smaller sides or as an open-sided rectangle with only one side missing.
Data Flow - Movement of data is shown by pointed arrows. Data movement is shown from the base of arrow as its source towards head of the arrow as destination.
Level 0 - Highest abstraction level DFD is known as Level 0 DFD, which depicts the entire information system as one diagram concealing all the underlying details. Level 0 DFDs are also known as context level DFDs.
Level 1 - The Level 0 DFD is broken down into more specific, Level 1 DFD. Level 1 DFD depicts basic modules in the system and flow of data among various modules. Level 1 DFD also mentions basic processes and sources of information.
Level 2 - At this level, DFD shows how data flows inside the modules mentioned in Level 1.
Higher level DFDs can be transformed into more specific lower level DFDs with deeper level of understanding unless the desired level of specification is achieved.
Level 2 - At this level, DFD shows how data flows inside the modules mentioned in Level 1.
Higher level DFDs can be transformed into more specific lower level DFDs with deeper level of understanding unless the desired level of specification is achieved.
Structure chart is a chart derived from Data Flow Diagram. It represents the system in more detail than DFD. It breaks down the entire system into lowest functional modules, describes functions and sub-functions of each module of the system to a greater detail than DFD.
Structure chart represents hierarchical structure of modules. At each layer a specific task is performed.
Here are the symbols used in construction of structure charts -
Module - It represents process or subroutine or task. A control module branches to more than one sub-module. Library Modules are re-usable and invokable from any module.
Condition - It is represented by small diamond at the base of module. It depicts that control module can select any of sub-routine based on some condition.
Jump - An arrow is shown pointing inside the module to depict that the control will jump in the middle of the sub-module.
Loop - A curved arrow represents loop in the module. All sub-modules covered by loop repeat execution of module.
Data flow - A directed arrow with empty circle at the end represents data flow.
Control flow - A directed arrow with filled circle at the end represents control flow.
HIPO (Hierarchical Input Process Output) diagram is a combination of two organized method to analyze the system and provide the means of documentation. HIPO model was developed by IBM in year 1970.
HIPO diagram represents the hierarchy of modules in the software system. Analyst uses HIPO diagram in order to obtain high-level view of system functions. It decomposes functions into sub-functions in a hierarchical manner. It depicts the functions performed by system.
HIPO diagrams are good for documentation purpose. Their graphical representation makes it easier for designers and managers to get the pictorial idea of the system structure.
In contrast to IPO (Input Process Output) diagram, which depicts the flow of control and data in a module, HIPO does not provide any information about data flow or control flow.
Both parts of HIPO diagram, Hierarchical presentation and IPO Chart are used for structure design of software program as well as documentation of the same.
Most programmers are unaware of the large picture of software so they only rely on what their managers tell them to do. It is the responsibility of higher software management to provide accurate information to the programmers to develop accurate yet fast code.
Other forms of methods, which use graphs or diagrams, may are sometimes interpreted differently by different people.
Hence, analysts and designers of the software come up with tools such as Structured English. It is nothing but the description of what is required to code and how to code it. Structured English helps the programmer to write error-free code.
Other form of methods, which use graphs or diagrams, may are sometimes interpreted differently by different people. Here, both Structured English and Pseudo-Code tries to mitigate that understanding gap.
Structured English is the It uses plain English words in structured programming paradigm. It is not the ultimate code but a kind of description what is required to code and how to code it. The following are some tokens of structured programming.
IF-THEN-ELSE,
DO-WHILE-UNTIL
Analyst uses the same variable and data name, which are stored in Data Dictionary, making it much simpler to write and understand the code.
We take the same example of Customer Authentication in the online shopping environment. This procedure to authenticate customer can be written in Structured English as:
Enter Customer_Name
SEEK Customer_Name in Customer_Name_DB file
IF Customer_Name found THEN
Call procedure USER_PASSWORD_AUTHENTICATE()
ELSE
PRINT error message
Call procedure NEW_CUSTOMER_REQUEST()
ENDIF
The code written in Structured English is more like day-to-day spoken English. It can not be implemented directly as a code of software. Structured English is independent of programming language.
Pseudo code is written more close to programming language. It may be considered as augmented programming language, full of comments and descriptions.
Pseudo code avoids variable declaration but they are written using some actual programming language’s constructs, like C, Fortran, Pascal etc.
Pseudo code contains more programming details than Structured English. It provides a method to perform the task, as if a computer is executing the code.
Program to print Fibonacci up to n numbers.
void function Fibonacci
Get value of n;
Set value of a to 1;
Set value of b to 1;
Initialize I to 0
for (i=0; i< n; i++)
{
if a greater than b
{
Increase b by a;
Print b;
}
else if b greater than a
{
increase a by b;
print a;
}
}
A Decision table represents conditions and the respective actions to be taken to address them, in a structured tabular format.
It is a powerful tool to debug and prevent errors. It helps group similar information into a single table and then by combining tables it delivers easy and convenient decision-making.
To create the decision table, the developer must follow basic four steps:
Identify all possible conditions to be addressed
Determine actions for all identified conditions
Create Maximum possible rules
Define action for each rule
Decision Tables should be verified by end-users and can lately be simplified by eliminating duplicate rules and actions.
Let us take a simple example of day-to-day problem with our Internet connectivity. We begin by identifying all problems that can arise while starting the internet and their respective possible solutions.
We list all possible problems under column conditions and the prospective actions under column Actions.
Entity-Relationship model is a type of database model based on the notion of real world entities and relationship among them. We can map real world scenario onto ER database model. ER Model creates a set of entities with their attributes, a set of constraints and relation among them.
ER Model is best used for the conceptual design of database. ER Model can be represented as follows :
Entity - An entity in ER Model is a real world being, which has some properties called attributes. Every attribute is defined by its corresponding set of values, called domain.
For example, Consider a school database. Here, a student is an entity. Student has various attributes like name, id, age and class etc.
Entity - An entity in ER Model is a real world being, which has some properties called attributes. Every attribute is defined by its corresponding set of values, called domain.
For example, Consider a school database. Here, a student is an entity. Student has various attributes like name, id, age and class etc.
Relationship - The logical association among entities is called relationship. Relationships are mapped with entities in various ways. Mapping cardinalities define the number of associations between two entities.
Mapping cardinalities:
one to one
one to many
many to one
many to many
Relationship - The logical association among entities is called relationship. Relationships are mapped with entities in various ways. Mapping cardinalities define the number of associations between two entities.
Mapping cardinalities:
one to one
one to many
many to one
many to many
Data dictionary is the centralized collection of information about data. It stores meaning and origin of data, its relationship with other data, data format for usage etc. Data dictionary has rigorous definitions of all names in order to facilitate user and software designers.
Data dictionary is often referenced as meta-data (data about data) repository. It is created along with DFD (Data Flow Diagram) model of software program and is expected to be updated whenever DFD is changed or updated.
The data is referenced via data dictionary while designing and implementing software. Data dictionary removes any chances of ambiguity. It helps keeping work of programmers and designers synchronized while using same object reference everywhere in the program.
Data dictionary provides a way of documentation for the complete database system in one place. Validation of DFD is carried out using data dictionary.
Data dictionary should contain information about the following
Data Flow
Data Structure
Data Elements
Data Stores
Data Processing
Data Flow is described by means of DFDs as studied earlier and represented in algebraic form as described.
Address = House No + (Street / Area) + City + State
Course ID = Course Number + Course Name + Course Level + Course Grades
Data elements consist of Name and descriptions of Data and Control Items, Internal or External data stores etc. with the following details:
Primary Name
Secondary Name (Alias)
Use-case (How and where to use)
Content Description (Notation etc. )
Supplementary Information (preset values, constraints etc.)
It stores the information from where the data enters into the system and exists out of the system. The Data Store may include -
Files
Internal to software.
External to software but on the same machine.
External to software and system, located on different machine.
Internal to software.
External to software but on the same machine.
External to software and system, located on different machine.
Tables
Naming convention
Indexing property
Naming convention
Indexing property
There are two types of Data Processing:
Logical: As user sees it
Physical: As software sees it
Software design is a process to conceptualize the software requirements into software implementation. Software design takes the user requirements as challenges and tries to find optimum solution. While the software is being conceptualized, a plan is chalked out to find the best possible design for implementing the intended solution.
There are multiple variants of software design. Let us study them briefly:
Structured design is a conceptualization of problem into several well-organized elements of solution. It is basically concerned with the solution design. Benefit of structured design is, it gives better understanding of how the problem is being solved. Structured design also makes it simpler for designer to concentrate on the problem more accurately.
Structured design is mostly based on ‘divide and conquer’ strategy where a problem is broken into several small problems and each small problem is individually solved until the whole problem is solved.
The small pieces of problem are solved by means of solution modules. Structured design emphasis that these modules be well organized in order to achieve precise solution.
These modules are arranged in hierarchy. They communicate with each other. A good structured design always follows some rules for communication among multiple modules, namely -
Cohesion - grouping of all functionally related elements.
Coupling - communication between different modules.
A good structured design has high cohesion and low coupling arrangements.
In function-oriented design, the system is comprised of many smaller sub-systems known as functions. These functions are capable of performing significant task in the system. The system is considered as top view of all functions.
Function oriented design inherits some properties of structured design where divide and conquer methodology is used.
This design mechanism divides the whole system into smaller functions, which provides means of abstraction by concealing the information and their operation.. These functional modules can share information among themselves by means of information passing and using information available globally.
Another characteristic of functions is that when a program calls a function, the function changes the state of the program, which sometimes is not acceptable by other modules. Function oriented design works well where the system state does not matter and program/functions work on input rather than on a state.
The whole system is seen as how data flows in the system by means of data flow diagram.
DFD depicts how functions changes data and state of entire system.
The entire system is logically broken down into smaller units known as functions on the basis of their operation in the system.
Each function is then described at large.
Object oriented design works around the entities and their characteristics instead of functions involved in the software system. This design strategies focuses on entities and its characteristics. The whole concept of software solution revolves around the engaged entities.
Let us see the important concepts of Object Oriented Design:
Objects - All entities involved in the solution design are known as objects. For example, person, banks, company and customers are treated as objects. Every entity has some attributes associated to it and has some methods to perform on the attributes.
Classes - A class is a generalized description of an object. An object is an instance of a class. Class defines all the attributes, which an object can have and methods, which defines the functionality of the object.
In the solution design, attributes are stored as variables and functionalities are defined by means of methods or procedures.
Classes - A class is a generalized description of an object. An object is an instance of a class. Class defines all the attributes, which an object can have and methods, which defines the functionality of the object.
In the solution design, attributes are stored as variables and functionalities are defined by means of methods or procedures.
Encapsulation - In OOD, the attributes (data variables) and methods (operation on the data) are bundled together is called encapsulation. Encapsulation not only bundles important information of an object together, but also restricts access of the data and methods from the outside world. This is called information hiding.
Inheritance - OOD allows similar classes to stack up in hierarchical manner where the lower or sub-classes can import, implement and re-use allowed variables and methods from their immediate super classes. This property of OOD is known as inheritance. This makes it easier to define specific class and to create generalized classes from specific ones.
Polymorphism - OOD languages provide a mechanism where methods performing similar tasks but vary in arguments, can be assigned same name. This is called polymorphism, which allows a single interface performing tasks for different types. Depending upon how the function is invoked, respective portion of the code gets executed.
Software design process can be perceived as series of well-defined steps. Though it varies according to design approach (function oriented or object oriented, yet It may have the following steps involved:
A solution design is created from requirement or previous used system and/or system sequence diagram.
Objects are identified and grouped into classes on behalf of similarity in attribute characteristics.
Class hierarchy and relation among them is defined.
Application framework is defined.
Here are two generic approaches for software designing:
We know that a system is composed of more than one sub-systems and it contains a number of components. Further, these sub-systems and components may have their on set of sub-system and components and creates hierarchical structure in the system.
Top-down design takes the whole software system as one entity and then decomposes it to achieve more than one sub-system or component based on some characteristics. Each sub-system or component is then treated as a system and decomposed further. This process keeps on running until the lowest level of system in the top-down hierarchy is achieved.
Top-down design starts with a generalized model of system and keeps on defining the more specific part of it. When all components are composed the whole system comes into existence.
Top-down design is more suitable when the software solution needs to be designed from scratch and specific details are unknown.
The bottom up design model starts with most specific and basic components. It proceeds with composing higher level of components by using basic or lower level components. It keeps creating higher level components until the desired system is not evolved as one single component. With each higher level, the amount of abstraction is increased.
Bottom-up strategy is more suitable when a system needs to be created from some existing system, where the basic primitives can be used in the newer system.
Both, top-down and bottom-up approaches are not practical individually. Instead, a good combination of both is used.
User interface is the front-end application view to which user interacts in order to use the software. User can manipulate and control the software as well as hardware by means of user interface. Today, user interface is found at almost every place where digital technology exists, right from computers, mobile phones, cars, music players, airplanes, ships etc.
User interface is part of software and is designed such a way that it is expected to provide the user insight of the software. UI provides fundamental platform for human-computer interaction.
UI can be graphical, text-based, audio-video based, depending upon the underlying hardware and software combination. UI can be hardware or software or a combination of both.
The software becomes more popular if its user interface is:
Attractive
Simple to use
Responsive in short time
Clear to understand
Consistent on all interfacing screens
UI is broadly divided into two categories:
Command Line Interface
Graphical User Interface
CLI has been a great tool of interaction with computers until the video display monitors came into existence. CLI is first choice of many technical users and programmers. CLI is minimum interface a software can provide to its users.
CLI provides a command prompt, the place where the user types the command and feeds to the system. The user needs to remember the syntax of command and its use. Earlier CLI were not programmed to handle the user errors effectively.
A command is a text-based reference to set of instructions, which are expected to be executed by the system. There are methods like macros, scripts that make it easy for the user to operate.
CLI uses less amount of computer resource as compared to GUI.
A text-based command line interface can have the following elements:
Command Prompt - It is text-based notifier that is mostly shows the context in which the user is working. It is generated by the software system.
Command Prompt - It is text-based notifier that is mostly shows the context in which the user is working. It is generated by the software system.
Cursor - It is a small horizontal line or a vertical bar of the height of line, to represent position of character while typing. Cursor is mostly found in blinking state. It moves as the user writes or deletes something.
Cursor - It is a small horizontal line or a vertical bar of the height of line, to represent position of character while typing. Cursor is mostly found in blinking state. It moves as the user writes or deletes something.
Command - A command is an executable instruction. It may have one or more parameters. Output on command execution is shown inline on the screen. When output is produced, command prompt is displayed on the next line.
Command - A command is an executable instruction. It may have one or more parameters. Output on command execution is shown inline on the screen. When output is produced, command prompt is displayed on the next line.
Graphical User Interface provides the user graphical means to interact with the system. GUI can be combination of both hardware and software. Using GUI, user interprets the software.
Typically, GUI is more resource consuming than that of CLI. With advancing technology, the programmers and designers create complex GUI designs that work with more efficiency, accuracy and speed.
GUI provides a set of components to interact with software or hardware.
Every graphical component provides a way to work with the system. A GUI system has following elements such as:
Window - An area where contents of application are displayed. Contents in a window can be displayed in the form of icons or lists, if the window represents file structure. It is easier for a user to navigate in the file system in an exploring window. Windows can be minimized, resized or maximized to the size of screen. They can be moved anywhere on the screen. A window may contain another window of the same application, called child window.
Window - An area where contents of application are displayed. Contents in a window can be displayed in the form of icons or lists, if the window represents file structure. It is easier for a user to navigate in the file system in an exploring window. Windows can be minimized, resized or maximized to the size of screen. They can be moved anywhere on the screen. A window may contain another window of the same application, called child window.
Tabs - If an application allows executing multiple instances of itself, they appear on the screen as separate windows. Tabbed Document Interface has come up to open multiple documents in the same window. This interface also helps in viewing preference panel in application. All modern web-browsers use this feature.
Tabs - If an application allows executing multiple instances of itself, they appear on the screen as separate windows. Tabbed Document Interface has come up to open multiple documents in the same window. This interface also helps in viewing preference panel in application. All modern web-browsers use this feature.
Menu - Menu is an array of standard commands, grouped together and placed at a visible place (usually top) inside the application window. The menu can be programmed to appear or hide on mouse clicks.
Menu - Menu is an array of standard commands, grouped together and placed at a visible place (usually top) inside the application window. The menu can be programmed to appear or hide on mouse clicks.
Icon - An icon is small picture representing an associated application. When these icons are clicked or double clicked, the application window is opened. Icon displays application and programs installed on a system in the form of small pictures.
Icon - An icon is small picture representing an associated application. When these icons are clicked or double clicked, the application window is opened. Icon displays application and programs installed on a system in the form of small pictures.
Cursor - Interacting devices such as mouse, touch pad, digital pen are represented in GUI as cursors. On screen cursor follows the instructions from hardware in almost real-time. Cursors are also named pointers in GUI systems. They are used to select menus, windows and other application features.
Cursor - Interacting devices such as mouse, touch pad, digital pen are represented in GUI as cursors. On screen cursor follows the instructions from hardware in almost real-time. Cursors are also named pointers in GUI systems. They are used to select menus, windows and other application features.
A GUI of an application contains one or more of the listed GUI elements:
Application Window - Most application windows uses the constructs supplied by operating systems but many use their own customer created windows to contain the contents of application.
Application Window - Most application windows uses the constructs supplied by operating systems but many use their own customer created windows to contain the contents of application.
Dialogue Box - It is a child window that contains message for the user and request for some action to be taken. For Example: Application generate a dialogue to get confirmation from user to delete a file.
Dialogue Box - It is a child window that contains message for the user and request for some action to be taken. For Example: Application generate a dialogue to get confirmation from user to delete a file.
Text-Box - Provides an area for user to type and enter text-based data.
Text-Box - Provides an area for user to type and enter text-based data.
Buttons - They imitate real life buttons and are used to submit inputs to the software.
Buttons - They imitate real life buttons and are used to submit inputs to the software.
Radio-button - Displays available options for selection. Only one can be selected among all offered.
Radio-button - Displays available options for selection. Only one can be selected among all offered.
Check-box - Functions similar to list-box. When an option is selected, the box is marked as checked. Multiple options represented by check boxes can be selected.
Check-box - Functions similar to list-box. When an option is selected, the box is marked as checked. Multiple options represented by check boxes can be selected.
List-box - Provides list of available items for selection. More than one item can be selected.
List-box - Provides list of available items for selection. More than one item can be selected.
Other impressive GUI components are:
Sliders
Combo-box
Data-grid
Drop-down list
There are a number of activities performed for designing user interface. The process of GUI design and implementation is alike SDLC. Any model can be used for GUI implementation among Waterfall, Iterative or Spiral Model.
A model used for GUI design and development should fulfill these GUI specific steps.
GUI Requirement Gathering - The designers may like to have list of all functional and non-functional requirements of GUI. This can be taken from user and their existing software solution.
GUI Requirement Gathering - The designers may like to have list of all functional and non-functional requirements of GUI. This can be taken from user and their existing software solution.
User Analysis - The designer studies who is going to use the software GUI. The target audience matters as the design details change according to the knowledge and competency level of the user. If user is technical savvy, advanced and complex GUI can be incorporated. For a novice user, more information is included on how-to of software.
User Analysis - The designer studies who is going to use the software GUI. The target audience matters as the design details change according to the knowledge and competency level of the user. If user is technical savvy, advanced and complex GUI can be incorporated. For a novice user, more information is included on how-to of software.
Task Analysis - Designers have to analyze what task is to be done by the software solution. Here in GUI, it does not matter how it will be done. Tasks can be represented in hierarchical manner taking one major task and dividing it further into smaller sub-tasks. Tasks provide goals for GUI presentation. Flow of information among sub-tasks determines the flow of GUI contents in the software.
Task Analysis - Designers have to analyze what task is to be done by the software solution. Here in GUI, it does not matter how it will be done. Tasks can be represented in hierarchical manner taking one major task and dividing it further into smaller sub-tasks. Tasks provide goals for GUI presentation. Flow of information among sub-tasks determines the flow of GUI contents in the software.
GUI Design & implementation - Designers after having information about requirements, tasks and user environment, design the GUI and implements into code and embed the GUI with working or dummy software in the background. It is then self-tested by the developers.
GUI Design & implementation - Designers after having information about requirements, tasks and user environment, design the GUI and implements into code and embed the GUI with working or dummy software in the background. It is then self-tested by the developers.
Testing - GUI testing can be done in various ways. Organization can have in-house inspection, direct involvement of users and release of beta version are few of them. Testing may include usability, compatibility, user acceptance etc.
Testing - GUI testing can be done in various ways. Organization can have in-house inspection, direct involvement of users and release of beta version are few of them. Testing may include usability, compatibility, user acceptance etc.
There are several tools available using which the designers can create entire GUI on a mouse click. Some tools can be embedded into the software environment (IDE).
GUI implementation tools provide powerful array of GUI controls. For software customization, designers can change the code accordingly.
There are different segments of GUI tools according to their different use and platform.
Mobile GUI, Computer GUI, Touch-Screen GUI etc. Here is a list of few tools which come handy to build GUI:
FLUID
AppInventor (Android)
LucidChart
Wavemaker
Visual Studio
The following rules are mentioned to be the golden rules for GUI design, described by Shneiderman and Plaisant in their book (Designing the User Interface).
Strive for consistency - Consistent sequences of actions should be required in similar situations. Identical terminology should be used in prompts, menus, and help screens. Consistent commands should be employed throughout.
Strive for consistency - Consistent sequences of actions should be required in similar situations. Identical terminology should be used in prompts, menus, and help screens. Consistent commands should be employed throughout.
Enable frequent users to use short-cuts - The user’s desire to reduce the number of interactions increases with the frequency of use. Abbreviations, function keys, hidden commands, and macro facilities are very helpful to an expert user.
Enable frequent users to use short-cuts - The user’s desire to reduce the number of interactions increases with the frequency of use. Abbreviations, function keys, hidden commands, and macro facilities are very helpful to an expert user.
Offer informative feedback - For every operator action, there should be some system feedback. For frequent and minor actions, the response must be modest, while for infrequent and major actions, the response must be more substantial.
Offer informative feedback - For every operator action, there should be some system feedback. For frequent and minor actions, the response must be modest, while for infrequent and major actions, the response must be more substantial.
Design dialog to yield closure - Sequences of actions should be organized into groups with a beginning, middle, and end. The informative feedback at the completion of a group of actions gives the operators the satisfaction of accomplishment, a sense of relief, the signal to drop contingency plans and options from their minds, and this indicates that the way ahead is clear to prepare for the next group of actions.
Design dialog to yield closure - Sequences of actions should be organized into groups with a beginning, middle, and end. The informative feedback at the completion of a group of actions gives the operators the satisfaction of accomplishment, a sense of relief, the signal to drop contingency plans and options from their minds, and this indicates that the way ahead is clear to prepare for the next group of actions.
Offer simple error handling - As much as possible, design the system so the user will not make a serious error. If an error is made, the system should be able to detect it and offer simple, comprehensible mechanisms for handling the error.
Offer simple error handling - As much as possible, design the system so the user will not make a serious error. If an error is made, the system should be able to detect it and offer simple, comprehensible mechanisms for handling the error.
Permit easy reversal of actions - This feature relieves anxiety, since the user knows that errors can be undone. Easy reversal of actions encourages exploration of unfamiliar options. The units of reversibility may be a single action, a data entry, or a complete group of actions.
Permit easy reversal of actions - This feature relieves anxiety, since the user knows that errors can be undone. Easy reversal of actions encourages exploration of unfamiliar options. The units of reversibility may be a single action, a data entry, or a complete group of actions.
Support internal locus of control - Experienced operators strongly desire the sense that they are in charge of the system and that the system responds to their actions. Design the system to make users the initiators of actions rather than the responders.
Support internal locus of control - Experienced operators strongly desire the sense that they are in charge of the system and that the system responds to their actions. Design the system to make users the initiators of actions rather than the responders.
Reduce short-term memory load - The limitation of human information processing in short-term memory requires the displays to be kept simple, multiple page displays be consolidated, window-motion frequency be reduced, and sufficient training time be allotted for codes, mnemonics, and sequences of actions.
Reduce short-term memory load - The limitation of human information processing in short-term memory requires the displays to be kept simple, multiple page displays be consolidated, window-motion frequency be reduced, and sufficient training time be allotted for codes, mnemonics, and sequences of actions.
The term complexity stands for state of events or things, which have multiple interconnected links and highly complicated structures. In software programming, as the design of software is realized, the number of elements and their interconnections gradually emerge to be huge, which becomes too difficult to understand at once.
Software design complexity is difficult to assess without using complexity metrics and measures. Let us see three important software complexity measures.
In 1977, Mr. Maurice Howard Halstead introduced metrics to measure software complexity. Halstead’s metrics depends upon the actual implementation of program and its measures, which are computed directly from the operators and operands from source code, in static manner. It allows to evaluate testing time, vocabulary, size, difficulty, errors, and efforts for C/C++/Java source code.
According to Halstead, “A computer program is an implementation of an algorithm considered to be a collection of tokens which can be classified as either operators or operands”. Halstead metrics think a program as sequence of operators and their associated operands.
He defines various indicators to check complexity of module.
When we select source file to view its complexity details in Metric Viewer, the following result is seen in Metric Report:
Every program encompasses statements to execute in order to perform some task and other decision-making statements that decide, what statements need to be executed. These decision-making constructs change the flow of the program.
If we compare two programs of same size, the one with more decision-making statements will be more complex as the control of program jumps frequently.
McCabe, in 1976, proposed Cyclomatic Complexity Measure to quantify complexity of a given software. It is graph driven model that is based on decision-making constructs of program such as if-else, do-while, repeat-until, switch-case and goto statements.
Process to make flow control graph:
Break program in smaller blocks, delimited by decision-making constructs.
Create nodes representing each of these nodes.
Connect nodes as follows:
If control can branch from block i to block j
Draw an arc
If control can branch from block i to block j
Draw an arc
From exit node to entry node
Draw an arc.
From exit node to entry node
Draw an arc.
To calculate Cyclomatic complexity of a program module, we use the formula -
V(G) = e – n + 2
Where
e is total number of edges
n is total number of nodes
The Cyclomatic complexity of the above module is
e = 10
n = 8
Cyclomatic Complexity = 10 - 8 + 2
= 4
According to P. Jorgensen, Cyclomatic Complexity of a module should not exceed 10.
It is widely used to measure the size of software. Function Point concentrates on functionality provided by the system. Features and functionality of the system are used to measure the software complexity.
Function point counts on five parameters, named as External Input, External Output, Logical Internal Files, External Interface Files, and External Inquiry. To consider the complexity of software each parameter is further categorized as simple, average or complex.
Let us see parameters of function point:
Every unique input to the system, from outside, is considered as external input. Uniqueness of input is measured, as no two inputs should have same formats. These inputs can either be data or control parameters.
Simple - if input count is low and affects less internal files
Simple - if input count is low and affects less internal files
Complex - if input count is high and affects more internal files
Complex - if input count is high and affects more internal files
Average - in-between simple and complex.
Average - in-between simple and complex.
All output types provided by the system are counted in this category. Output is considered unique if their output format and/or processing are unique.
Simple - if output count is low
Simple - if output count is low
Complex - if output count is high
Complex - if output count is high
Average - in between simple and complex.
Average - in between simple and complex.
Every software system maintains internal files in order to maintain its functional information and to function properly. These files hold logical data of the system. This logical data may contain both functional data and control data.
Simple - if number of record types are low
Simple - if number of record types are low
Complex - if number of record types are high
Complex - if number of record types are high
Average - in between simple and complex.
Average - in between simple and complex.
Software system may need to share its files with some external software or it may need to pass the file for processing or as parameter to some function. All these files are counted as external interface files.
Simple - if number of record types in shared file are low
Simple - if number of record types in shared file are low
Complex - if number of record types in shared file are high
Complex - if number of record types in shared file are high
Average - in between simple and complex.
Average - in between simple and complex.
An inquiry is a combination of input and output, where user sends some data to inquire about as input and the system responds to the user with the output of inquiry processed. The complexity of a query is more than External Input and External Output. Query is said to be unique if its input and output are unique in terms of format and data.
Simple - if query needs low processing and yields small amount of output data
Simple - if query needs low processing and yields small amount of output data
Complex - if query needs high process and yields large amount of output data
Complex - if query needs high process and yields large amount of output data
Average - in between simple and complex.
Average - in between simple and complex.
Each of these parameters in the system is given weightage according to their class and complexity. The table below mentions the weightage given to each parameter:
The table above yields raw Function Points. These function points are adjusted according to the environment complexity. System is described using fourteen different characteristics:
Data communications
Distributed processing
Performance objectives
Operation configuration load
Transaction rate
Online data entry,
End user efficiency
Online update
Complex processing logic
Re-usability
Installation ease
Operational ease
Multiple sites
Desire to facilitate changes
These characteristics factors are then rated from 0 to 5, as mentioned below:
No influence
Incidental
Moderate
Average
Significant
Essential
All ratings are then summed up as N. The value of N ranges from 0 to 70 (14 types of characteristics x 5 types of ratings). It is used to calculate Complexity Adjustment Factors (CAF), using the following formulae:
CAF = 0.65 + 0.01N
Then,
Delivered Function Points (FP)= CAF x Raw FP
This FP can then be used in various metrics, such as:
Cost = $ / FP
Quality = Errors / FP
Productivity = FP / person-month
In this chapter, we will study about programming methods, documentation and challenges in software implementation.
In the process of coding, the lines of code keep multiplying, thus, size of the software increases. Gradually, it becomes next to impossible to remember the flow of program. If one forgets how software and its underlying programs, files, procedures are constructed it then becomes very difficult to share, debug and modify the program. The solution to this is structured programming. It encourages the developer to use subroutines and loops instead of using simple jumps in the code, thereby bringing clarity in the code and improving its efficiency Structured programming also helps programmer to reduce coding time and organize code properly.
Structured programming states how the program shall be coded. Structured programming uses three main concepts:
Top-down analysis - A software is always made to perform some rational work. This rational work is known as problem in the software parlance. Thus it is very important that we understand how to solve the problem. Under top-down analysis, the problem is broken down into small pieces where each one has some significance. Each problem is individually solved and steps are clearly stated about how to solve the problem.
Top-down analysis - A software is always made to perform some rational work. This rational work is known as problem in the software parlance. Thus it is very important that we understand how to solve the problem. Under top-down analysis, the problem is broken down into small pieces where each one has some significance. Each problem is individually solved and steps are clearly stated about how to solve the problem.
Modular Programming - While programming, the code is broken down into smaller group of instructions. These groups are known as modules, subprograms or subroutines. Modular programming based on the understanding of top-down analysis. It discourages jumps using ‘goto’ statements in the program, which often makes the program flow non-traceable. Jumps are prohibited and modular format is encouraged in structured programming.
Modular Programming - While programming, the code is broken down into smaller group of instructions. These groups are known as modules, subprograms or subroutines. Modular programming based on the understanding of top-down analysis. It discourages jumps using ‘goto’ statements in the program, which often makes the program flow non-traceable. Jumps are prohibited and modular format is encouraged in structured programming.
Structured Coding - In reference with top-down analysis, structured coding sub-divides the modules into further smaller units of code in the order of their execution. Structured programming uses control structure, which controls the flow of the program, whereas structured coding uses control structure to organize its instructions in definable patterns.
Structured Coding - In reference with top-down analysis, structured coding sub-divides the modules into further smaller units of code in the order of their execution. Structured programming uses control structure, which controls the flow of the program, whereas structured coding uses control structure to organize its instructions in definable patterns.
Functional programming is style of programming language, which uses the concepts of mathematical functions. A function in mathematics should always produce the same result on receiving the same argument. In procedural languages, the flow of the program runs through procedures, i.e. the control of program is transferred to the called procedure. While control flow is transferring from one procedure to another, the program changes its state.
In procedural programming, it is possible for a procedure to produce different results when it is called with the same argument, as the program itself can be in different state while calling it. This is a property as well as a drawback of procedural programming, in which the sequence or timing of the procedure execution becomes important.
Functional programming provides means of computation as mathematical functions, which produces results irrespective of program state. This makes it possible to predict the behavior of the program.
Functional programming uses the following concepts:
First class and High-order functions - These functions have capability to accept another function as argument or they return other functions as results.
First class and High-order functions - These functions have capability to accept another function as argument or they return other functions as results.
Pure functions - These functions do not include destructive updates, that is, they do not affect any I/O or memory and if they are not in use, they can easily be removed without hampering the rest of the program.
Pure functions - These functions do not include destructive updates, that is, they do not affect any I/O or memory and if they are not in use, they can easily be removed without hampering the rest of the program.
Recursion - Recursion is a programming technique where a function calls itself and repeats the program code in it unless some pre-defined condition matches. Recursion is the way of creating loops in functional programming.
Recursion - Recursion is a programming technique where a function calls itself and repeats the program code in it unless some pre-defined condition matches. Recursion is the way of creating loops in functional programming.
Strict evaluation - It is a method of evaluating the expression passed to a function as an argument. Functional programming has two types of evaluation methods, strict (eager) or non-strict (lazy). Strict evaluation always evaluates the expression before invoking the function. Non-strict evaluation does not evaluate the expression unless it is needed.
Strict evaluation - It is a method of evaluating the expression passed to a function as an argument. Functional programming has two types of evaluation methods, strict (eager) or non-strict (lazy). Strict evaluation always evaluates the expression before invoking the function. Non-strict evaluation does not evaluate the expression unless it is needed.
λ-calculus - Most functional programming languages use λ-calculus as their type systems. λ-expressions are executed by evaluating them as they occur.
λ-calculus - Most functional programming languages use λ-calculus as their type systems. λ-expressions are executed by evaluating them as they occur.
Common Lisp, Scala, Haskell, Erlang and F# are some examples of functional programming languages.
Programming style is set of coding rules followed by all the programmers to write the code. When multiple programmers work on the same software project, they frequently need to work with the program code written by some other developer. This becomes tedious or at times impossible, if all developers do not follow some standard programming style to code the program.
An appropriate programming style includes using function and variable names relevant to the intended task, using well-placed indentation, commenting code for the convenience of reader and overall presentation of code. This makes the program code readable and understandable by all, which in turn makes debugging and error solving easier. Also, proper coding style helps ease the documentation and updation.
Practice of coding style varies with organizations, operating systems and language of coding itself.
The following coding elements may be defined under coding guidelines of an organization:
Naming conventions - This section defines how to name functions, variables, constants and global variables.
Naming conventions - This section defines how to name functions, variables, constants and global variables.
Indenting - This is the space left at the beginning of line, usually 2-8 whitespace or single tab.
Indenting - This is the space left at the beginning of line, usually 2-8 whitespace or single tab.
Whitespace - It is generally omitted at the end of line.
Whitespace - It is generally omitted at the end of line.
Operators - Defines the rules of writing mathematical, assignment and logical operators. For example, assignment operator ‘=’ should have space before and after it, as in “x = 2”.
Operators - Defines the rules of writing mathematical, assignment and logical operators. For example, assignment operator ‘=’ should have space before and after it, as in “x = 2”.
Control Structures - The rules of writing if-then-else, case-switch, while-until and for control flow statements solely and in nested fashion.
Control Structures - The rules of writing if-then-else, case-switch, while-until and for control flow statements solely and in nested fashion.
Line length and wrapping - Defines how many characters should be there in one line, mostly a line is 80 characters long. Wrapping defines how a line should be wrapped, if is too long.
Line length and wrapping - Defines how many characters should be there in one line, mostly a line is 80 characters long. Wrapping defines how a line should be wrapped, if is too long.
Functions - This defines how functions should be declared and invoked, with and without parameters.
Functions - This defines how functions should be declared and invoked, with and without parameters.
Variables - This mentions how variables of different data types are declared and defined.
Variables - This mentions how variables of different data types are declared and defined.
Comments - This is one of the important coding components, as the comments included in the code describe what the code actually does and all other associated descriptions. This section also helps creating help documentations for other developers.
Comments - This is one of the important coding components, as the comments included in the code describe what the code actually does and all other associated descriptions. This section also helps creating help documentations for other developers.
Software documentation is an important part of software process. A well written document provides a great tool and means of information repository necessary to know about software process. Software documentation also provides information about how to use the product.
A well-maintained documentation should involve the following documents:
Requirement documentation - This documentation works as key tool for software designer, developer and the test team to carry out their respective tasks. This document contains all the functional, non-functional and behavioral description of the intended software.
Source of this document can be previously stored data about the software, already running software at the client’s end, client’s interview, questionnaires and research. Generally it is stored in the form of spreadsheet or word processing document with the high-end software management team.
This documentation works as foundation for the software to be developed and is majorly used in verification and validation phases. Most test-cases are built directly from requirement documentation.
Requirement documentation - This documentation works as key tool for software designer, developer and the test team to carry out their respective tasks. This document contains all the functional, non-functional and behavioral description of the intended software.
Source of this document can be previously stored data about the software, already running software at the client’s end, client’s interview, questionnaires and research. Generally it is stored in the form of spreadsheet or word processing document with the high-end software management team.
This documentation works as foundation for the software to be developed and is majorly used in verification and validation phases. Most test-cases are built directly from requirement documentation.
Software Design documentation - These documentations contain all the necessary information, which are needed to build the software. It contains: (a) High-level software architecture, (b) Software design details, (c) Data flow diagrams, (d) Database design
These documents work as repository for developers to implement the software. Though these documents do not give any details on how to code the program, they give all necessary information that is required for coding and implementation.
Software Design documentation - These documentations contain all the necessary information, which are needed to build the software. It contains: (a) High-level software architecture, (b) Software design details, (c) Data flow diagrams, (d) Database design
These documents work as repository for developers to implement the software. Though these documents do not give any details on how to code the program, they give all necessary information that is required for coding and implementation.
Technical documentation - These documentations are maintained by the developers and actual coders. These documents, as a whole, represent information about the code. While writing the code, the programmers also mention objective of the code, who wrote it, where will it be required, what it does and how it does, what other resources the code uses, etc.
The technical documentation increases the understanding between various programmers working on the same code. It enhances re-use capability of the code. It makes debugging easy and traceable.
There are various automated tools available and some comes with the programming language itself. For example java comes JavaDoc tool to generate technical documentation of code.
Technical documentation - These documentations are maintained by the developers and actual coders. These documents, as a whole, represent information about the code. While writing the code, the programmers also mention objective of the code, who wrote it, where will it be required, what it does and how it does, what other resources the code uses, etc.
The technical documentation increases the understanding between various programmers working on the same code. It enhances re-use capability of the code. It makes debugging easy and traceable.
There are various automated tools available and some comes with the programming language itself. For example java comes JavaDoc tool to generate technical documentation of code.
User documentation - This documentation is different from all the above explained. All previous documentations are maintained to provide information about the software and its development process. But user documentation explains how the software product should work and how it should be used to get the desired results.
These documentations may include, software installation procedures, how-to guides, user-guides, uninstallation method and special references to get more information like license updation etc.
User documentation - This documentation is different from all the above explained. All previous documentations are maintained to provide information about the software and its development process. But user documentation explains how the software product should work and how it should be used to get the desired results.
These documentations may include, software installation procedures, how-to guides, user-guides, uninstallation method and special references to get more information like license updation etc.
There are some challenges faced by the development team while implementing the software. Some of them are mentioned below:
Code-reuse - Programming interfaces of present-day languages are very sophisticated and are equipped huge library functions. Still, to bring the cost down of end product, the organization management prefers to re-use the code, which was created earlier for some other software. There are huge issues faced by programmers for compatibility checks and deciding how much code to re-use.
Code-reuse - Programming interfaces of present-day languages are very sophisticated and are equipped huge library functions. Still, to bring the cost down of end product, the organization management prefers to re-use the code, which was created earlier for some other software. There are huge issues faced by programmers for compatibility checks and deciding how much code to re-use.
Version Management - Every time a new software is issued to the customer, developers have to maintain version and configuration related documentation. This documentation needs to be highly accurate and available on time.
Version Management - Every time a new software is issued to the customer, developers have to maintain version and configuration related documentation. This documentation needs to be highly accurate and available on time.
Target-Host - The software program, which is being developed in the organization, needs to be designed for host machines at the customers end. But at times, it is impossible to design a software that works on the target machines.
Target-Host - The software program, which is being developed in the organization, needs to be designed for host machines at the customers end. But at times, it is impossible to design a software that works on the target machines.
Software Testing is evaluation of the software against requirements gathered from users and system specifications. Testing is conducted at the phase level in software development life cycle or at module level in program code. Software testing comprises of Validation and Verification.
Validation is process of examining whether or not the software satisfies the user requirements. It is carried out at the end of the SDLC. If the software matches requirements for which it was made, it is validated.
Validation ensures the product under development is as per the user requirements.
Validation answers the question – "Are we developing the product which attempts all that user needs from this software ?".
Validation emphasizes on user requirements.
Verification is the process of confirming if the software is meeting the business requirements, and is developed adhering to the proper specifications and methodologies.
Verification ensures the product being developed is according to design specifications.
Verification answers the question– "Are we developing this product by firmly following all design specifications ?"
Verifications concentrates on the design and system specifications.
Target of the test are -
Errors - These are actual coding mistakes made by developers. In addition, there is a difference in output of software and desired output, is considered as an error.
Errors - These are actual coding mistakes made by developers. In addition, there is a difference in output of software and desired output, is considered as an error.
Fault - When error exists fault occurs. A fault, also known as a bug, is a result of an error which can cause system to fail.
Fault - When error exists fault occurs. A fault, also known as a bug, is a result of an error which can cause system to fail.
Failure - failure is said to be the inability of the system to perform the desired task. Failure occurs when fault exists in the system.
Failure - failure is said to be the inability of the system to perform the desired task. Failure occurs when fault exists in the system.
Testing can either be done manually or using an automated testing tool:
Manual - This testing is performed without taking help of automated testing tools. The software tester prepares test cases for different sections and levels of the code, executes the tests and reports the result to the manager.
Manual testing is time and resource consuming. The tester needs to confirm whether or not right test cases are used. Major portion of testing involves manual testing.
Manual - This testing is performed without taking help of automated testing tools. The software tester prepares test cases for different sections and levels of the code, executes the tests and reports the result to the manager.
Manual testing is time and resource consuming. The tester needs to confirm whether or not right test cases are used. Major portion of testing involves manual testing.
Automated This testing is a testing procedure done with aid of automated testing tools. The limitations with manual testing can be overcome using automated test tools.
Automated This testing is a testing procedure done with aid of automated testing tools. The limitations with manual testing can be overcome using automated test tools.
A test needs to check if a webpage can be opened in Internet Explorer. This can be easily done with manual testing. But to check if the web-server can take the load of 1 million users, it is quite impossible to test manually.
There are software and hardware tools which helps tester in conducting load testing, stress testing, regression testing.
Tests can be conducted based on two approaches –
Functionality testing
Implementation testing
When functionality is being tested without taking the actual implementation in concern it is known as black-box testing. The other side is known as white-box testing where not only functionality is tested but the way it is implemented is also analyzed.
Exhaustive tests are the best-desired method for a perfect testing. Every single possible value in the range of the input and output values is tested. It is not possible to test each and every value in real world scenario if the range of values is large.
It is carried out to test functionality of the program. It is also called ‘Behavioral’ testing. The tester in this case, has a set of input values and respective desired results. On providing input, if the output matches with the desired results, the program is tested ‘ok’, and problematic otherwise.
In this testing method, the design and structure of the code are not known to the tester, and testing engineers and end users conduct this test on the software.
Black-box testing techniques:
Equivalence class - The input is divided into similar classes. If one element of a class passes the test, it is assumed that all the class is passed.
Equivalence class - The input is divided into similar classes. If one element of a class passes the test, it is assumed that all the class is passed.
Boundary values - The input is divided into higher and lower end values. If these values pass the test, it is assumed that all values in between may pass too.
Boundary values - The input is divided into higher and lower end values. If these values pass the test, it is assumed that all values in between may pass too.
Cause-effect graphing - In both previous methods, only one input value at a time is tested. Cause (input) – Effect (output) is a testing technique where combinations of input values are tested in a systematic way.
Cause-effect graphing - In both previous methods, only one input value at a time is tested. Cause (input) – Effect (output) is a testing technique where combinations of input values are tested in a systematic way.
Pair-wise Testing - The behavior of software depends on multiple parameters. In pairwise testing, the multiple parameters are tested pair-wise for their different values.
Pair-wise Testing - The behavior of software depends on multiple parameters. In pairwise testing, the multiple parameters are tested pair-wise for their different values.
State-based testing - The system changes state on provision of input. These systems are tested based on their states and input.
State-based testing - The system changes state on provision of input. These systems are tested based on their states and input.
It is conducted to test program and its implementation, in order to improve code efficiency or structure. It is also known as ‘Structural’ testing.
In this testing method, the design and structure of the code are known to the tester. Programmers of the code conduct this test on the code.
The below are some White-box testing techniques:
Control-flow testing - The purpose of the control-flow testing to set up test cases which covers all statements and branch conditions. The branch conditions are tested for both being true and false, so that all statements can be covered.
Control-flow testing - The purpose of the control-flow testing to set up test cases which covers all statements and branch conditions. The branch conditions are tested for both being true and false, so that all statements can be covered.
Data-flow testing - This testing technique emphasis to cover all the data variables included in the program. It tests where the variables were declared and defined and where they were used or changed.
Data-flow testing - This testing technique emphasis to cover all the data variables included in the program. It tests where the variables were declared and defined and where they were used or changed.
Testing itself may be defined at various levels of SDLC. The testing process runs parallel to software development. Before jumping on the next stage, a stage is tested, validated and verified.
Testing separately is done just to make sure that there are no hidden bugs or issues left in the software. Software is tested on various levels -
While coding, the programmer performs some tests on that unit of program to know if it is error free. Testing is performed under white-box testing approach. Unit testing helps developers decide that individual units of the program are working as per requirement and are error free.
Even if the units of software are working fine individually, there is a need to find out if the units if integrated together would also work without errors. For example, argument passing and data updation etc.
The software is compiled as product and then it is tested as a whole. This can be accomplished using one or more of the following tests:
Functionality testing - Tests all functionalities of the software against the requirement.
Functionality testing - Tests all functionalities of the software against the requirement.
Performance testing - This test proves how efficient the software is. It tests the effectiveness and average time taken by the software to do desired task. Performance testing is done by means of load testing and stress testing where the software is put under high user and data load under various environment conditions.
Performance testing - This test proves how efficient the software is. It tests the effectiveness and average time taken by the software to do desired task. Performance testing is done by means of load testing and stress testing where the software is put under high user and data load under various environment conditions.
Security & Portability - These tests are done when the software is meant to work on various platforms and accessed by number of persons.
Security & Portability - These tests are done when the software is meant to work on various platforms and accessed by number of persons.
When the software is ready to hand over to the customer it has to go through last phase of testing where it is tested for user-interaction and response. This is important because even if the software matches all user requirements and if user does not like the way it appears or works, it may be rejected.
Alpha testing - The team of developer themselves perform alpha testing by using the system as if it is being used in work environment. They try to find out how user would react to some action in software and how the system should respond to inputs.
Alpha testing - The team of developer themselves perform alpha testing by using the system as if it is being used in work environment. They try to find out how user would react to some action in software and how the system should respond to inputs.
Beta testing - After the software is tested internally, it is handed over to the users to use it under their production environment only for testing purpose. This is not as yet the delivered product. Developers expect that users at this stage will bring minute problems, which were skipped to attend.
Beta testing - After the software is tested internally, it is handed over to the users to use it under their production environment only for testing purpose. This is not as yet the delivered product. Developers expect that users at this stage will bring minute problems, which were skipped to attend.
Whenever a software product is updated with new code, feature or functionality, it is tested thoroughly to detect if there is any negative impact of the added code. This is known as regression testing.
Testing documents are prepared at different stages -
Testing starts with test cases generation. Following documents are needed for reference –
SRS document - Functional Requirements document
SRS document - Functional Requirements document
Test Policy document - This describes how far testing should take place before releasing the product.
Test Policy document - This describes how far testing should take place before releasing the product.
Test Strategy document - This mentions detail aspects of test team, responsibility matrix and rights/responsibility of test manager and test engineer.
Test Strategy document - This mentions detail aspects of test team, responsibility matrix and rights/responsibility of test manager and test engineer.
Traceability Matrix document - This is SDLC document, which is related to requirement gathering process. As new requirements come, they are added to this matrix. These matrices help testers know the source of requirement. They can be traced forward and backward.
Traceability Matrix document - This is SDLC document, which is related to requirement gathering process. As new requirements come, they are added to this matrix. These matrices help testers know the source of requirement. They can be traced forward and backward.
The following documents may be required while testing is started and is being done:
Test Case document - This document contains list of tests required to be conducted. It includes Unit test plan, Integration test plan, System test plan and Acceptance test plan.
Test Case document - This document contains list of tests required to be conducted. It includes Unit test plan, Integration test plan, System test plan and Acceptance test plan.
Test description - This document is a detailed description of all test cases and procedures to execute them.
Test description - This document is a detailed description of all test cases and procedures to execute them.
Test case report - This document contains test case report as a result of the test.
Test case report - This document contains test case report as a result of the test.
Test logs - This document contains test logs for every test case report.
Test logs - This document contains test logs for every test case report.
The following documents may be generated after testing :
Test summary - This test summary is collective analysis of all test reports and logs. It summarizes and concludes if the software is ready to be launched. The software is released under version control system if it is ready to launch.
Test summary - This test summary is collective analysis of all test reports and logs. It summarizes and concludes if the software is ready to be launched. The software is released under version control system if it is ready to launch.
We need to understand that software testing is different from software quality assurance, software quality control and software auditing.
Software quality assurance - These are software development process monitoring means, by which it is assured that all the measures are taken as per the standards of organization. This monitoring is done to make sure that proper software development methods were followed.
Software quality assurance - These are software development process monitoring means, by which it is assured that all the measures are taken as per the standards of organization. This monitoring is done to make sure that proper software development methods were followed.
Software quality control - This is a system to maintain the quality of software product. It may include functional and non-functional aspects of software product, which enhance the goodwill of the organization. This system makes sure that the customer is receiving quality product for their requirement and the product certified as ‘fit for use’.
Software quality control - This is a system to maintain the quality of software product. It may include functional and non-functional aspects of software product, which enhance the goodwill of the organization. This system makes sure that the customer is receiving quality product for their requirement and the product certified as ‘fit for use’.
Software audit - This is a review of procedure used by the organization to develop the software. A team of auditors, independent of development team examines the software process, procedure, requirements and other aspects of SDLC. The purpose of software audit is to check that software and its development process, both conform standards, rules and regulations.
Software audit - This is a review of procedure used by the organization to develop the software. A team of auditors, independent of development team examines the software process, procedure, requirements and other aspects of SDLC. The purpose of software audit is to check that software and its development process, both conform standards, rules and regulations.
Software maintenance is widely accepted part of SDLC now a days. It stands for all the modifications and updations done after the delivery of software product. There are number of reasons, why modifications are required, some of them are briefly mentioned below:
Market Conditions - Policies, which changes over the time, such as taxation and newly introduced constraints like, how to maintain bookkeeping, may trigger need for modification.
Market Conditions - Policies, which changes over the time, such as taxation and newly introduced constraints like, how to maintain bookkeeping, may trigger need for modification.
Client Requirements - Over the time, customer may ask for new features or functions in the software.
Client Requirements - Over the time, customer may ask for new features or functions in the software.
Host Modifications - If any of the hardware and/or platform (such as operating system) of the target host changes, software changes are needed to keep adaptability.
Host Modifications - If any of the hardware and/or platform (such as operating system) of the target host changes, software changes are needed to keep adaptability.
Organization Changes - If there is any business level change at client end, such as reduction of organization strength, acquiring another company, organization venturing into new business, need to modify in the original software may arise.
Organization Changes - If there is any business level change at client end, such as reduction of organization strength, acquiring another company, organization venturing into new business, need to modify in the original software may arise.
In a software lifetime, type of maintenance may vary based on its nature. It may be just a routine maintenance tasks as some bug discovered by some user or it may be a large event in itself based on maintenance size or nature. Following are some types of maintenance based on their characteristics:
Corrective Maintenance - This includes modifications and updations done in order to correct or fix problems, which are either discovered by user or concluded by user error reports.
Corrective Maintenance - This includes modifications and updations done in order to correct or fix problems, which are either discovered by user or concluded by user error reports.
Adaptive Maintenance - This includes modifications and updations applied to keep the software product up-to date and tuned to the ever changing world of technology and business environment.
Adaptive Maintenance - This includes modifications and updations applied to keep the software product up-to date and tuned to the ever changing world of technology and business environment.
Perfective Maintenance - This includes modifications and updates done in order to keep the software usable over long period of time. It includes new features, new user requirements for refining the software and improve its reliability and performance.
Perfective Maintenance - This includes modifications and updates done in order to keep the software usable over long period of time. It includes new features, new user requirements for refining the software and improve its reliability and performance.
Preventive Maintenance - This includes modifications and updations to prevent future problems of the software. It aims to attend problems, which are not significant at this moment but may cause serious issues in future.
Preventive Maintenance - This includes modifications and updations to prevent future problems of the software. It aims to attend problems, which are not significant at this moment but may cause serious issues in future.
Reports suggest that the cost of maintenance is high. A study on estimating software maintenance found that the cost of maintenance is as high as 67% of the cost of entire software process cycle.
On an average, the cost of software maintenance is more than 50% of all SDLC phases. There are various factors, which trigger maintenance cost go high, such as:
The standard age of any software is considered up to 10 to 15 years.
Older softwares, which were meant to work on slow machines with less memory and storage capacity cannot keep themselves challenging against newly coming enhanced softwares on modern hardware.
As technology advances, it becomes costly to maintain old software.
Most maintenance engineers are newbie and use trial and error method to rectify problem.
Often, changes made can easily hurt the original structure of the software, making it hard for any subsequent changes.
Changes are often left undocumented which may cause more conflicts in future.
Structure of Software Program
Programming Language
Dependence on external environment
Staff reliability and availability
IEEE provides a framework for sequential maintenance process activities. It can be used in iterative manner and can be extended so that customized items and processes can be included.
These activities go hand-in-hand with each of the following phase:
Identification & Tracing - It involves activities pertaining to identification of requirement of modification or maintenance. It is generated by user or system may itself report via logs or error messages.Here, the maintenance type is classified also.
Identification & Tracing - It involves activities pertaining to identification of requirement of modification or maintenance. It is generated by user or system may itself report via logs or error messages.Here, the maintenance type is classified also.
Analysis - The modification is analyzed for its impact on the system including safety and security implications. If probable impact is severe, alternative solution is looked for. A set of required modifications is then materialized into requirement specifications. The cost of modification/maintenance is analyzed and estimation is concluded.
Analysis - The modification is analyzed for its impact on the system including safety and security implications. If probable impact is severe, alternative solution is looked for. A set of required modifications is then materialized into requirement specifications. The cost of modification/maintenance is analyzed and estimation is concluded.
Design - New modules, which need to be replaced or modified, are designed against requirement specifications set in the previous stage. Test cases are created for validation and verification.
Design - New modules, which need to be replaced or modified, are designed against requirement specifications set in the previous stage. Test cases are created for validation and verification.
Implementation - The new modules are coded with the help of structured design created in the design step.Every programmer is expected to do unit testing in parallel.
Implementation - The new modules are coded with the help of structured design created in the design step.Every programmer is expected to do unit testing in parallel.
System Testing - Integration testing is done among newly created modules. Integration testing is also carried out between new modules and the system. Finally the system is tested as a whole, following regressive testing procedures.
System Testing - Integration testing is done among newly created modules. Integration testing is also carried out between new modules and the system. Finally the system is tested as a whole, following regressive testing procedures.
Acceptance Testing - After testing the system internally, it is tested for acceptance with the help of users. If at this state, user complaints some issues they are addressed or noted to address in next iteration.
Acceptance Testing - After testing the system internally, it is tested for acceptance with the help of users. If at this state, user complaints some issues they are addressed or noted to address in next iteration.
Delivery - After acceptance test, the system is deployed all over the organization either by small update package or fresh installation of the system. The final testing takes place at client end after the software is delivered.
Training facility is provided if required, in addition to the hard copy of user manual.
Delivery - After acceptance test, the system is deployed all over the organization either by small update package or fresh installation of the system. The final testing takes place at client end after the software is delivered.
Training facility is provided if required, in addition to the hard copy of user manual.
Maintenance management - Configuration management is an essential part of system maintenance. It is aided with version control tools to control versions, semi-version or patch management.
Maintenance management - Configuration management is an essential part of system maintenance. It is aided with version control tools to control versions, semi-version or patch management.
When we need to update the software to keep it to the current market, without impacting its functionality, it is called software re-engineering. It is a thorough process where the design of software is changed and programs are re-written.
Legacy software cannot keep tuning with the latest technology available in the market. As the hardware become obsolete, updating of software becomes a headache. Even if software grows old with time, its functionality does not.
For example, initially Unix was developed in assembly language. When language C came into existence, Unix was re-engineered in C, because working in assembly language was difficult.
Other than this, sometimes programmers notice that few parts of software need more maintenance than others and they also need re-engineering.
Decide what to re-engineer. Is it whole software or a part of it?
Perform Reverse Engineering, in order to obtain specifications of existing software.
Restructure Program if required. For example, changing function-oriented programs into object-oriented programs.
Re-structure data as required.
Apply Forward engineering concepts in order to get re-engineered software.
There are few important terms used in Software re-engineering
It is a process to achieve system specification by thoroughly analyzing, understanding the existing system. This process can be seen as reverse SDLC model, i.e. we try to get higher abstraction level by analyzing lower abstraction levels.
An existing system is previously implemented design, about which we know nothing. Designers then do reverse engineering by looking at the code and try to get the design. With design in hand, they try to conclude the specifications. Thus, going in reverse from code to system specification.
It is a process to re-structure and re-construct the existing software. It is all about re-arranging the source code, either in same programming language or from one programming language to a different one. Restructuring can have either source code-restructuring and data-restructuring or both.
Re-structuring does not impact the functionality of the software but enhance reliability and maintainability. Program components, which cause errors very frequently can be changed, or updated with re-structuring.
The dependability of software on obsolete hardware platform can be removed via re-structuring.
Forward engineering is a process of obtaining desired software from the specifications in hand which were brought down by means of reverse engineering. It assumes that there was some software engineering already done in the past.
Forward engineering is same as software engineering process with only one difference – it is carried out always after reverse engineering.
A component is a part of software program code, which executes an independent task in the system. It can be a small module or sub-system itself.
The login procedures used on the web can be considered as components, printing system in software can be seen as a component of the software.
Components have high cohesion of functionality and lower rate of coupling, i.e. they work independently and can perform tasks without depending on other modules.
In OOP, the objects are designed are very specific to their concern and have fewer chances to be used in some other software.
In modular programming, the modules are coded to perform specific tasks which can be used across number of other software programs.
There is a whole new vertical, which is based on re-use of software component, and is known as Component Based Software Engineering (CBSE).
Re-use can be done at various levels
Application level - Where an entire application is used as sub-system of new software.
Application level - Where an entire application is used as sub-system of new software.
Component level - Where sub-system of an application is used.
Component level - Where sub-system of an application is used.
Modules level - Where functional modules are re-used.
Software components provide interfaces, which can be used to establish communication among different components.
Modules level - Where functional modules are re-used.
Software components provide interfaces, which can be used to establish communication among different components.
Two kinds of method can be adopted: either by keeping requirements same and adjusting components or by keeping components same and modifying requirements.
Requirement Specification - The functional and non-functional requirements are specified, which a software product must comply to, with the help of existing system, user input or both.
Requirement Specification - The functional and non-functional requirements are specified, which a software product must comply to, with the help of existing system, user input or both.
Design - This is also a standard SDLC process step, where requirements are defined in terms of software parlance. Basic architecture of system as a whole and its sub-systems are created.
Design - This is also a standard SDLC process step, where requirements are defined in terms of software parlance. Basic architecture of system as a whole and its sub-systems are created.
Specify Components - By studying the software design, the designers segregate the entire system into smaller components or sub-systems. One complete software design turns into a collection of a huge set of components working together.
Specify Components - By studying the software design, the designers segregate the entire system into smaller components or sub-systems. One complete software design turns into a collection of a huge set of components working together.
Search Suitable Components - The software component repository is referred by designers to search for the matching component, on the basis of functionality and intended software requirements..
Search Suitable Components - The software component repository is referred by designers to search for the matching component, on the basis of functionality and intended software requirements..
Incorporate Components - All matched components are packed together to shape them as complete software.
Incorporate Components - All matched components are packed together to shape them as complete software.
CASE stands for Computer Aided Software Engineering. It means, development and maintenance of software projects with help of various automated software tools.
CASE tools are set of software application programs, which are used to automate SDLC activities. CASE tools are used by software project managers, analysts and engineers to develop software system.
There are number of CASE tools available to simplify various stages of Software Development Life Cycle such as Analysis tools, Design tools, Project management tools, Database Management tools, Documentation tools are to name a few.
Use of CASE tools accelerates the development of project to produce desired result and helps to uncover flaws before moving ahead with next stage in software development.
CASE tools can be broadly divided into the following parts based on their use at a particular SDLC stage:
Central Repository - CASE tools require a central repository, which can serve as a source of common, integrated and consistent information. Central repository is a central place of storage where product specifications, requirement documents, related reports and diagrams, other useful information regarding management is stored. Central repository also serves as data dictionary.
Central Repository - CASE tools require a central repository, which can serve as a source of common, integrated and consistent information. Central repository is a central place of storage where product specifications, requirement documents, related reports and diagrams, other useful information regarding management is stored. Central repository also serves as data dictionary.
Upper Case Tools - Upper CASE tools are used in planning, analysis and design stages of SDLC.
Upper Case Tools - Upper CASE tools are used in planning, analysis and design stages of SDLC.
Lower Case Tools - Lower CASE tools are used in implementation, testing and maintenance.
Lower Case Tools - Lower CASE tools are used in implementation, testing and maintenance.
Integrated Case Tools - Integrated CASE tools are helpful in all the stages of SDLC, from Requirement gathering to Testing and documentation.
Integrated Case Tools - Integrated CASE tools are helpful in all the stages of SDLC, from Requirement gathering to Testing and documentation.
CASE tools can be grouped together if they have similar functionality, process activities and capability of getting integrated with other tools.
The scope of CASE tools goes throughout the SDLC.
Now we briefly go through various CASE tools
These tools are used to represent system components, data and control flow among various software components and system structure in a graphical form. For example, Flow Chart Maker tool for creating state-of-the-art flowcharts.
Process modeling is method to create software process model, which is used to develop the software. Process modeling tools help the managers to choose a process model or modify it as per the requirement of software product. For example, EPF Composer
These tools are used for project planning, cost and effort estimation, project scheduling and resource planning. Managers have to strictly comply project execution with every mentioned step in software project management. Project management tools help in storing and sharing project information in real-time throughout the organization. For example, Creative Pro Office, Trac Project, Basecamp.
Documentation in a software project starts prior to the software process, goes throughout all phases of SDLC and after the completion of the project.
Documentation tools generate documents for technical users and end users. Technical users are mostly in-house professionals of the development team who refer to system manual, reference manual, training manual, installation manuals etc. The end user documents describe the functioning and how-to of the system such as user manual. For example, Doxygen, DrExplain, Adobe RoboHelp for documentation.
These tools help to gather requirements, automatically check for any inconsistency, inaccuracy in the diagrams, data redundancies or erroneous omissions. For example, Accept 360, Accompa, CaseComplete for requirement analysis, Visible Analyst for total analysis.
These tools help software designers to design the block structure of the software, which may further be broken down in smaller modules using refinement techniques. These tools provides detailing of each module and interconnections among modules. For example, Animated Software Design
An instance of software is released under one version. Configuration Management tools deal with –
Version and revision management
Baseline configuration management
Change control management
CASE tools help in this by automatic tracking, version management and release management. For example, Fossil, Git, Accu REV.
These tools are considered as a part of configuration management tools. They deal with changes made to the software after its baseline is fixed or when the software is first released. CASE tools automate change tracking, file management, code management and more. It also helps in enforcing change policy of the organization.
These tools consist of programming environments like IDE (Integrated Development Environment), in-built modules library and simulation tools. These tools provide comprehensive aid in building software product and include features for simulation and testing. For example, Cscope to search code in C, Eclipse.
Software prototype is simulated version of the intended software product. Prototype provides initial look and feel of the product and simulates few aspect of actual product.
Prototyping CASE tools essentially come with graphical libraries. They can create hardware independent user interfaces and design. These tools help us to build rapid prototypes based on existing information. In addition, they provide simulation of software prototype. For example, Serena prototype composer, Mockup Builder.
These tools assist in designing web pages with all allied elements like forms, text, script, graphic and so on. Web tools also provide live preview of what is being developed and how will it look after completion. For example, Fontello, Adobe Edge Inspect, Foundation 3, Brackets.
Quality assurance in a software organization is monitoring the engineering process and methods adopted to develop the software product in order to ensure conformance of quality as per organization standards. QA tools consist of configuration and change control tools and software testing tools. For example, SoapTest, AppsWatch, JMeter.
Software maintenance includes modifications in the software product after it is delivered. Automatic logging and error reporting techniques, automatic error ticket generation and root cause Analysis are few CASE tools, which help software organization in maintenance phase of SDLC. For example, Bugzilla for defect tracking, HP Quality Center.
80 Lectures
7.5 hours
Arnab Chakraborty
10 Lectures
1 hours
Zach Miller
17 Lectures
1.5 hours
Zach Miller
60 Lectures
5 hours
John Shea
99 Lectures
10 hours
Daniel IT
62 Lectures
5 hours
GlobalETraining
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2156,
"s": 2037,
"text": "Let us first understand what software engineering stands for. The term is made of two words, software and engineering."
},
{
"code": null,
"e": 2462,
"s": 2156,
"text": "Software is more than just a program code. A program is an executable code, which serves some computational purpose. Software is considered to be collection of executable programming code, associated libraries and documentations. Software, when made for a specific requirement is called software product."
},
{
"code": null,
"e": 2582,
"s": 2462,
"text": "Engineering on the other hand, is all about developing products, using well-defined, scientific principles and methods."
},
{
"code": null,
"e": 2825,
"s": 2582,
"text": "Software engineering is an engineering branch associated with development of software product using well-defined scientific principles, methods and procedures. The outcome of software engineering is an efficient and reliable software product."
},
{
"code": null,
"e": 2863,
"s": 2825,
"text": "IEEE defines software engineering as:"
},
{
"code": null,
"e": 3044,
"s": 2863,
"text": "(1) The application of a systematic,disciplined,quantifiable approach to the development,operation and maintenance of software; that is, the application of engineering to software."
},
{
"code": null,
"e": 3099,
"s": 3044,
"text": "(2) The study of approaches as in the above statement."
},
{
"code": null,
"e": 3174,
"s": 3099,
"text": "Fritz Bauer, a German computer scientist, defines software engineering as:"
},
{
"code": null,
"e": 3353,
"s": 3174,
"text": "Software engineering is the establishment and use of sound engineering principles in order to obtain economically software that is reliable and work efficiently on real machines."
},
{
"code": null,
"e": 3656,
"s": 3353,
"text": "The process of developing a software product using software engineering principles and methods is referred to as software evolution. This includes the initial development of software and its maintenance and updates, till desired software product is developed, which satisfies the expected requirements."
},
{
"code": null,
"e": 4072,
"s": 3656,
"text": "Evolution starts from the requirement gathering process. After which developers create a prototype of the intended software and show it to the users to get their feedback at the early stage of software product development. The users suggest changes, on which several consecutive updates and maintenance keep on changing too. This process changes to the original software, till the desired software is accomplished."
},
{
"code": null,
"e": 4439,
"s": 4072,
"text": "Even after the user has desired software in hand, the advancing technology and the changing requirements force the software product to change accordingly. Re-creating software from scratch and to go one-on-one with requirement is not feasible. The only feasible and economical solution is to update the existing software so that it matches the latest requirements."
},
{
"code": null,
"e": 4542,
"s": 4439,
"text": "Lehman has given laws for software evolution. He divided the software into three different categories:"
},
{
"code": null,
"e": 4897,
"s": 4542,
"text": "S-type (static-type) - This is a software, which works strictly according to defined specifications and solutions. The solution and the method to achieve it, both are immediately understood before coding. The s-type software is least subjected to changes hence this is the simplest of all. For example, calculator program for mathematical computation. "
},
{
"code": null,
"e": 5154,
"s": 4897,
"text": "P-type (practical-type) - This is a software with a collection of procedures. This is defined by exactly what procedures can do. In this software, the specifications can be described but the solution is not obvious instantly. For example, gaming software."
},
{
"code": null,
"e": 5417,
"s": 5154,
"text": "E-type (embedded-type) - This software works closely as the requirement of real-world environment. This software has a high degree of evolution as there are various changes in laws, taxes etc. in the real world situations. For example, Online trading software."
},
{
"code": null,
"e": 5479,
"s": 5417,
"text": "Lehman has given eight laws for E-Type software evolution - "
},
{
"code": null,
"e": 5621,
"s": 5479,
"text": "Continuing change - An E-type software system must continue to adapt to the real world changes, else it becomes progressively less useful."
},
{
"code": null,
"e": 5763,
"s": 5621,
"text": "Increasing complexity - As an E-type software system evolves, its complexity tends to increase unless work is done to maintain or reduce it."
},
{
"code": null,
"e": 5995,
"s": 5763,
"text": "Conservation of familiarity - The familiarity with the software or the knowledge about how it was developed, why was it developed in that particular manner etc. must be retained at any cost, to implement the changes in the system."
},
{
"code": null,
"e": 6183,
"s": 5995,
"text": "Continuing growth- In order for an E-type system intended to resolve some business problem, its size of implementing the changes grows according to the lifestyle changes of the business."
},
{
"code": null,
"e": 6329,
"s": 6183,
"text": "Reducing quality - An E-type software system declines in quality unless rigorously maintained and adapted to a changing operational environment."
},
{
"code": null,
"e": 6496,
"s": 6329,
"text": "Feedback systems- The E-type software systems constitute multi-loop, multi-level feedback systems and must be treated as such to be successfully modified or improved."
},
{
"code": null,
"e": 6639,
"s": 6496,
"text": "Self-regulation - E-type system evolution processes are self-regulating with the distribution of product and process measures close to normal."
},
{
"code": null,
"e": 6785,
"s": 6639,
"text": "Organizational stability - The average effective global activity rate in an evolving E-type system is invariant over the lifetime of the product."
},
{
"code": null,
"e": 7109,
"s": 6785,
"text": "Software paradigms refer to the methods and steps, which are taken while designing the software. There are many methods proposed and are in work today, but we need to see where in the software engineering these paradigms stand. These can be combined into various categories, though each of them is contained in one another:"
},
{
"code": null,
"e": 7230,
"s": 7109,
"text": "Programming paradigm is a subset of Software design paradigm which is further a subset of Software development paradigm."
},
{
"code": null,
"e": 7495,
"s": 7230,
"text": "This Paradigm is known as software engineering paradigms where all the engineering concepts pertaining to the development of software are applied. It includes various researches and requirement gathering which helps the software product to build. It consists of – "
},
{
"code": null,
"e": 7517,
"s": 7495,
"text": "Requirement gathering"
},
{
"code": null,
"e": 7534,
"s": 7517,
"text": "Software design "
},
{
"code": null,
"e": 7546,
"s": 7534,
"text": "Programming"
},
{
"code": null,
"e": 7610,
"s": 7546,
"text": "This paradigm is a part of Software Development and includes – "
},
{
"code": null,
"e": 7618,
"s": 7610,
"text": "Design "
},
{
"code": null,
"e": 7630,
"s": 7618,
"text": "Maintenance"
},
{
"code": null,
"e": 7643,
"s": 7630,
"text": " Programming"
},
{
"code": null,
"e": 7739,
"s": 7643,
"text": "This paradigm is related closely to programming aspect of software development. This includes –"
},
{
"code": null,
"e": 7748,
"s": 7739,
"text": " Coding "
},
{
"code": null,
"e": 7756,
"s": 7748,
"text": "Testing"
},
{
"code": null,
"e": 7769,
"s": 7756,
"text": " Integration"
},
{
"code": null,
"e": 7913,
"s": 7769,
"text": "The need of software engineering arises because of higher rate of change in user requirements and environment on which the software is working."
},
{
"code": null,
"e": 8093,
"s": 7913,
"text": "Large software - It is easier to build a wall than to a house or building, likewise, as the size of software become large engineering has to step to give it a scientific process."
},
{
"code": null,
"e": 8262,
"s": 8093,
"text": "Scalability- If the software process were not based on scientific and engineering concepts, it would be easier to re-create new software than to scale an existing one."
},
{
"code": null,
"e": 8467,
"s": 8262,
"text": "Cost- As hardware industry has shown its skills and huge manufacturing has lower down he price of computer and electronic hardware. But the cost of software remains high if proper process is not adapted."
},
{
"code": null,
"e": 8746,
"s": 8467,
"text": "Dynamic Nature- The always growing and adapting nature of software hugely depends upon the environment in which user works. If the nature of software is always changing, new enhancements need to be done in the existing one. This is where software engineering plays a good role."
},
{
"code": null,
"e": 8852,
"s": 8746,
"text": "Quality Management- Better process of software development provides better and quality software product."
},
{
"code": null,
"e": 8986,
"s": 8852,
"text": "A software product can be judged by what it offers and how well it can be used. This software must satisfy on the following grounds:"
},
{
"code": null,
"e": 8998,
"s": 8986,
"text": "Operational"
},
{
"code": null,
"e": 9011,
"s": 8998,
"text": "Transitional"
},
{
"code": null,
"e": 9024,
"s": 9011,
"text": " Maintenance"
},
{
"code": null,
"e": 9112,
"s": 9024,
"text": "Well-engineered and crafted software is expected to have the following characteristics:"
},
{
"code": null,
"e": 9189,
"s": 9112,
"text": " This tells us how well software works in operations. It can be measured on:"
},
{
"code": null,
"e": 9196,
"s": 9189,
"text": "Budget"
},
{
"code": null,
"e": 9206,
"s": 9196,
"text": "Usability"
},
{
"code": null,
"e": 9217,
"s": 9206,
"text": "Efficiency"
},
{
"code": null,
"e": 9229,
"s": 9217,
"text": "Correctness"
},
{
"code": null,
"e": 9243,
"s": 9229,
"text": "Functionality"
},
{
"code": null,
"e": 9257,
"s": 9243,
"text": "Dependability"
},
{
"code": null,
"e": 9266,
"s": 9257,
"text": "Security"
},
{
"code": null,
"e": 9273,
"s": 9266,
"text": "Safety"
},
{
"code": null,
"e": 9356,
"s": 9273,
"text": " This aspect is important when the software is moved from one platform to another:"
},
{
"code": null,
"e": 9368,
"s": 9356,
"text": "Portability"
},
{
"code": null,
"e": 9385,
"s": 9368,
"text": "Interoperability"
},
{
"code": null,
"e": 9397,
"s": 9385,
"text": "Reusability"
},
{
"code": null,
"e": 9410,
"s": 9397,
"text": "Adaptability"
},
{
"code": null,
"e": 9530,
"s": 9410,
"text": " This aspect briefs about how well a software has the capabilities to maintain itself in the ever-changing environment:"
},
{
"code": null,
"e": 9541,
"s": 9530,
"text": "Modularity"
},
{
"code": null,
"e": 9557,
"s": 9541,
"text": "Maintainability"
},
{
"code": null,
"e": 9569,
"s": 9557,
"text": "Flexibility"
},
{
"code": null,
"e": 9581,
"s": 9569,
"text": "Scalability"
},
{
"code": null,
"e": 9781,
"s": 9581,
"text": "In short, Software engineering is a branch of computer science, which uses well-defined engineering concepts required to produce efficient, durable, scalable, in-budget and on-time software products."
},
{
"code": null,
"e": 9946,
"s": 9781,
"text": "Software Development Life Cycle, SDLC for short, is a well-defined, structured sequence of stages in software engineering to develop the intended software product. "
},
{
"code": null,
"e": 10092,
"s": 9946,
"text": "SDLC provides a series of steps to be followed to design and develop a software product efficiently. SDLC framework includes the following steps:"
},
{
"code": null,
"e": 10325,
"s": 10092,
"text": "This is the first step where the user initiates the request for a desired software product. He contacts the service provider and tries to negotiate the terms. He submits his request to the service providing organization in writing."
},
{
"code": null,
"e": 10748,
"s": 10325,
"text": "This step onwards the software development team works to carry on the project. The team holds discussions with various stakeholders from problem domain and tries to bring out as much information as possible on their requirements. The requirements are contemplated and segregated into user requirements, system requirements and functional requirements. The requirements are collected using a number of practices as given - "
},
{
"code": null,
"e": 10803,
"s": 10748,
"text": "studying the existing or obsolete system and software,"
},
{
"code": null,
"e": 10851,
"s": 10803,
"text": "conducting interviews of users and developers, "
},
{
"code": null,
"e": 10881,
"s": 10851,
"text": "referring to the database or "
},
{
"code": null,
"e": 10925,
"s": 10881,
"text": "collecting answers from the questionnaires."
},
{
"code": null,
"e": 11410,
"s": 10925,
"text": "After requirement gathering, the team comes up with a rough plan of software process. At this step the team analyzes if a software can be made to fulfill all requirements of the user and if there is any possibility of software being no more useful. It is found out, if the project is financially, practically and technologically feasible for the organization to take up. There are many algorithms available, which help the developers to conclude the feasibility of a software project."
},
{
"code": null,
"e": 11885,
"s": 11410,
"text": "At this step the developers decide a roadmap of their plan and try to bring up the best software model suitable for the project. System analysis includes Understanding of software product limitations, learning system related problems or changes to be done in existing systems beforehand, identifying and addressing the impact of project on organization and personnel etc. The project team analyzes the scope of the project and plans the schedule and resources accordingly."
},
{
"code": null,
"e": 12324,
"s": 11885,
"text": "Next step is to bring down whole knowledge of requirements and analysis on the desk and design the software product. The inputs from users and information gathered in requirement gathering phase are the inputs of this step. The output of this step comes in the form of two designs; logical design and physical design. Engineers produce meta-data and data dictionaries, logical diagrams, data-flow diagrams and in some cases pseudo codes."
},
{
"code": null,
"e": 12544,
"s": 12324,
"text": "This step is also known as programming phase. The implementation of software design starts in terms of writing program code in the suitable programming language and developing error-free executable programs efficiently."
},
{
"code": null,
"e": 13020,
"s": 12544,
"text": "An estimate says that 50% of whole software development process should be tested. Errors may ruin the software from critical level to its own removal. Software testing is done while coding by the developers and thorough testing is conducted by testing experts at various levels of code such as module testing, program testing, product testing, in-house testing and testing the product at user’s end. Early discovery of errors and their remedy is the key to reliable software."
},
{
"code": null,
"e": 13196,
"s": 13020,
"text": "Software may need to be integrated with the libraries, databases and other program(s). This stage of SDLC is involved in the integration of software with outer world entities."
},
{
"code": null,
"e": 13437,
"s": 13196,
"text": "This means installing the software on user machines. At times, software needs post-installation configurations at user end. Software is tested for portability and adaptability and integration related issues are solved during implementation."
},
{
"code": null,
"e": 13887,
"s": 13437,
"text": "This phase confirms the software operation in terms of more efficiency and less errors. If required, the users are trained on, or aided with the documentation on how to operate the software and how to keep the software operational. The software is maintained timely by updating the code according to the changes taking place in user end environment or technology. This phase may face challenges from hidden bugs and real-world unidentified problems."
},
{
"code": null,
"e": 14274,
"s": 13887,
"text": "As time elapses, the software may decline on the performance front. It may go completely obsolete or may need intense upgradation. Hence a pressing need to eliminate a major portion of the system arises. This phase includes archiving data and required software components, closing down the system, planning disposition activity and terminating system at appropriate end-of-system time."
},
{
"code": null,
"e": 14607,
"s": 14274,
"text": "The software development paradigm helps developer to select a strategy to develop the software. A software development paradigm has its own set of tools, methods and procedures, which are expressed clearly and defines software development life cycle. A few of software development paradigms or process models are defined as follows:"
},
{
"code": null,
"e": 14855,
"s": 14607,
"text": "Waterfall model is the simplest model of software development paradigm. It says the all the phases of SDLC will function one after another in linear manner. That is, when the first phase is finished then only the second phase will start and so on."
},
{
"code": null,
"e": 15223,
"s": 14855,
"text": "This model assumes that everything is carried out and taken place perfectly as planned in the previous stage and there is no need to think about the past issues that may arise in the next phase. This model does not work smoothly if there are some issues left at the previous step. The sequential nature of model does not allow us go back and undo or redo our actions."
},
{
"code": null,
"e": 15365,
"s": 15223,
"text": "This model is best suited when developers already have designed and developed similar software in the past and are aware of all its domains. "
},
{
"code": null,
"e": 15542,
"s": 15365,
"text": "This model leads the software development process in iterations. It projects the process of development in cyclic manner repeating every step after every cycle of SDLC process."
},
{
"code": null,
"e": 15904,
"s": 15542,
"text": "The software is first developed on very small scale and all the steps are followed which are taken into consideration. Then, on every next iteration, more features and modules are designed, coded, tested and added to the software. Every cycle produces a software, which is complete in itself and has more features and capabilities than that of the previous one."
},
{
"code": null,
"e": 16158,
"s": 15904,
"text": "After each iteration, the management team can do work on risk management and prepare for the next iteration. Because a cycle includes small portion of whole software process, it is easier to manage the development process but it consumes more resources."
},
{
"code": null,
"e": 16341,
"s": 16158,
"text": "Spiral model is a combination of both, iterative model and one of the SDLC model. It can be seen as if you choose one SDLC model and combine it with cyclic process (iterative model)."
},
{
"code": null,
"e": 16721,
"s": 16341,
"text": "This model considers risk, which often goes un-noticed by most other models. The model starts with determining objectives and constraints of the software at the start of one iteration. Next phase is of prototyping the software. This includes risk analysis. Then one standard SDLC model is used to build the software. In the fourth phase of the plan of next iteration is prepared."
},
{
"code": null,
"e": 16986,
"s": 16721,
"text": "The major drawback of waterfall model is we move to the next stage only when the previous one is finished and there was no chance to go back if something is found wrong in later stages. V-Model provides means of testing of software at each stage in reverse manner."
},
{
"code": null,
"e": 17409,
"s": 16986,
"text": "At every stage, test plans and test cases are created to verify and validate the product according to the requirement of that stage. For example, in requirement gathering stage the test team prepares all the test cases in correspondence to the requirements. Later, when the product is developed and is ready for testing, test cases of this stage verify the software against its validity towards requirements at this stage."
},
{
"code": null,
"e": 17532,
"s": 17409,
"text": "This makes both verification and validation go in parallel. This model is also known as verification and validation model."
},
{
"code": null,
"e": 17911,
"s": 17532,
"text": "This model is the simplest model in its form. It requires little planning, lots of programming and lots of funds. This model is conceptualized around the big bang of universe. As scientists say that after big bang lots of galaxies, planets and stars evolved just as an event. Likewise, if we put together lots of programming and funds, you may achieve the best software product."
},
{
"code": null,
"e": 18121,
"s": 17911,
"text": "For this model, very small amount of planning is required. It does not follow any process, or at times the customer is not sure about the requirements and future needs. So the input requirements are arbitrary."
},
{
"code": null,
"e": 18221,
"s": 18121,
"text": "This model is not suitable for large software projects but good one for learning and experimenting."
},
{
"code": null,
"e": 18289,
"s": 18221,
"text": "For an in-depth reading on SDLC and its various models, click here."
},
{
"code": null,
"e": 18386,
"s": 18289,
"text": "The job pattern of an IT company engaged in software development can be seen split in two parts:"
},
{
"code": null,
"e": 18404,
"s": 18386,
"text": "Software Creation"
},
{
"code": null,
"e": 18432,
"s": 18404,
"text": "Software Project Management"
},
{
"code": null,
"e": 18626,
"s": 18432,
"text": "A project is well-defined task, which is a collection of several operations done in order to achieve a goal (for example, software development and delivery). A Project can be characterized as:"
},
{
"code": null,
"e": 18676,
"s": 18626,
"text": "Every project may has a unique and distinct goal."
},
{
"code": null,
"e": 18735,
"s": 18676,
"text": "Project is not routine activity or day-to-day operations."
},
{
"code": null,
"e": 18781,
"s": 18735,
"text": "Project comes with a start time and end time."
},
{
"code": null,
"e": 18886,
"s": 18781,
"text": "Project ends when its goal is achieved hence it is a temporary phase in the lifetime of an organization."
},
{
"code": null,
"e": 18985,
"s": 18886,
"text": "Project needs adequate resources in terms of time, manpower, finance, material and knowledge-bank."
},
{
"code": null,
"e": 19231,
"s": 18985,
"text": "A Software Project is the complete procedure of software development from requirement gathering to testing and maintenance, carried out according to the execution methodologies, in a specified period of time to achieve intended software product."
},
{
"code": null,
"e": 19794,
"s": 19231,
"text": "Software is said to be an intangible product. Software development is a kind of all new stream in world business and there’s very little experience in building software products. Most software products are tailor made to fit client’s requirements. The most important is that the underlying technology changes and advances so frequently and rapidly that experience of one product may not be applied to the other one. All such business and environmental constraints bring risk in software development hence it is essential to manage software projects efficiently."
},
{
"code": null,
"e": 20189,
"s": 19794,
"text": "The image above shows triple constraints for software projects. It is an essential part of software organization to deliver quality product, keeping the cost within client’s budget constrain and deliver the project as per scheduled. There are several factors, both internal and external, which may impact this triple constrain triangle. Any of three factor can severely impact the other two. "
},
{
"code": null,
"e": 20314,
"s": 20189,
"text": "Therefore, software project management is essential to incorporate user requirements along with budget and time constraints."
},
{
"code": null,
"e": 20669,
"s": 20314,
"text": "A software project manager is a person who undertakes the responsibility of executing the software project. Software project manager is thoroughly aware of all the phases of SDLC that the software would go through. Project manager may never directly involve in producing the end product but he controls and manages the activities involved in production."
},
{
"code": null,
"e": 20952,
"s": 20669,
"text": "A project manager closely monitors the development process, prepares and executes various plans, arranges necessary and adequate resources, maintains communication among all team members in order to address issues of cost, budget, resources, time, quality and customer satisfaction."
},
{
"code": null,
"e": 21019,
"s": 20952,
"text": "Let us see few responsibilities that a project manager shoulders -"
},
{
"code": null,
"e": 21041,
"s": 21019,
"text": "Act as project leader"
},
{
"code": null,
"e": 21066,
"s": 21041,
"text": "Lesion with stakeholders"
},
{
"code": null,
"e": 21091,
"s": 21066,
"text": "Managing human resources"
},
{
"code": null,
"e": 21127,
"s": 21091,
"text": "Setting up reporting hierarchy etc."
},
{
"code": null,
"e": 21165,
"s": 21127,
"text": "Defining and setting up project scope"
},
{
"code": null,
"e": 21204,
"s": 21165,
"text": "Managing project management activities"
},
{
"code": null,
"e": 21240,
"s": 21204,
"text": "Monitoring progress and performance"
},
{
"code": null,
"e": 21269,
"s": 21240,
"text": "Risk analysis at every phase"
},
{
"code": null,
"e": 21322,
"s": 21269,
"text": "Take necessary step to avoid or come out of problems"
},
{
"code": null,
"e": 21350,
"s": 21322,
"text": "Act as project spokesperson"
},
{
"code": null,
"e": 21625,
"s": 21350,
"text": "Software project management comprises of a number of activities, which contains planning of project, deciding scope of software product, estimation of cost in various terms, scheduling of tasks and events, and resource management. Project management activities may include:"
},
{
"code": null,
"e": 21642,
"s": 21625,
"text": "Project Planning"
},
{
"code": null,
"e": 21659,
"s": 21642,
"text": "Scope Management"
},
{
"code": null,
"e": 21678,
"s": 21659,
"text": "Project Estimation"
},
{
"code": null,
"e": 22045,
"s": 21678,
"text": "Software project planning is task, which is performed before the production of software actually starts. It is there for the software production but involves no concrete activity that has any direction connection with software production; rather it is a set of multiple processes, which facilitates software production. Project planning may include the following: "
},
{
"code": null,
"e": 22480,
"s": 22045,
"text": "It defines the scope of project; this includes all the activities, process need to be done in order to make a deliverable software product. Scope management is essential because it creates boundaries of the project by clearly defining what would be done in the project and what would not be done. This makes project to contain limited and quantifiable tasks, which can easily be documented and in turn avoids cost and time overrun. "
},
{
"code": null,
"e": 22534,
"s": 22480,
"text": "During Project Scope management, it is necessary to -"
},
{
"code": null,
"e": 22552,
"s": 22534,
"text": "Define the scope "
},
{
"code": null,
"e": 22588,
"s": 22552,
"text": "Decide its verification and control"
},
{
"code": null,
"e": 22658,
"s": 22588,
"text": "Divide the project into various smaller parts for ease of management."
},
{
"code": null,
"e": 22675,
"s": 22658,
"text": "Verify the scope"
},
{
"code": null,
"e": 22731,
"s": 22675,
"text": "Control the scope by incorporating changes to the scope"
},
{
"code": null,
"e": 22914,
"s": 22731,
"text": "For an effective management accurate estimation of various measures is a must. With correct estimation managers can manage and control the project more efficiently and effectively. "
},
{
"code": null,
"e": 22960,
"s": 22914,
"text": "Project estimation may involve the following:"
},
{
"code": null,
"e": 23236,
"s": 22960,
"text": "Software size estimation\nSoftware size may be estimated either in terms of KLOC (Kilo Line of Code) or by calculating number of function points in the software. Lines of code depend upon coding practices and Function points vary according to the user or software requirement."
},
{
"code": null,
"e": 23487,
"s": 23236,
"text": "Software size may be estimated either in terms of KLOC (Kilo Line of Code) or by calculating number of function points in the software. Lines of code depend upon coding practices and Function points vary according to the user or software requirement."
},
{
"code": null,
"e": 23834,
"s": 23487,
"text": "Effort estimation\nThe managers estimate efforts in terms of personnel requirement and man-hour required to produce the software. For effort estimation software size should be known. This can either be derived by managers’ experience, organization’s historical data or software size can be converted into efforts by using some standard formulae.\n"
},
{
"code": null,
"e": 24163,
"s": 23834,
"text": "The managers estimate efforts in terms of personnel requirement and man-hour required to produce the software. For effort estimation software size should be known. This can either be derived by managers’ experience, organization’s historical data or software size can be converted into efforts by using some standard formulae.\n"
},
{
"code": null,
"e": 24711,
"s": 24163,
"text": "Time estimation\nOnce size and efforts are estimated, the time required to produce the software can be estimated. Efforts required is segregated into sub categories as per the requirement specifications and interdependency of various components of software. Software tasks are divided into smaller tasks, activities or events by Work Breakthrough Structure (WBS). The tasks are scheduled on day-to-day basis or in calendar months.\nThe sum of time required to complete all tasks in hours or days is the total time invested to complete the project."
},
{
"code": null,
"e": 25127,
"s": 24711,
"text": "Once size and efforts are estimated, the time required to produce the software can be estimated. Efforts required is segregated into sub categories as per the requirement specifications and interdependency of various components of software. Software tasks are divided into smaller tasks, activities or events by Work Breakthrough Structure (WBS). The tasks are scheduled on day-to-day basis or in calendar months."
},
{
"code": null,
"e": 25243,
"s": 25127,
"text": "The sum of time required to complete all tasks in hours or days is the total time invested to complete the project."
},
{
"code": null,
"e": 25440,
"s": 25243,
"text": "Cost estimation\nThis might be considered as the most difficult of all because it depends on more elements than any of the previous ones. For estimating project cost, it is required to consider - "
},
{
"code": null,
"e": 25621,
"s": 25440,
"text": "This might be considered as the most difficult of all because it depends on more elements than any of the previous ones. For estimating project cost, it is required to consider - "
},
{
"code": null,
"e": 25638,
"s": 25621,
"text": "Size of software"
},
{
"code": null,
"e": 25655,
"s": 25638,
"text": "Software quality"
},
{
"code": null,
"e": 25664,
"s": 25655,
"text": "Hardware"
},
{
"code": null,
"e": 25708,
"s": 25664,
"text": "Additional software or tools, licenses etc."
},
{
"code": null,
"e": 25752,
"s": 25708,
"text": "Skilled personnel with task-specific skills"
},
{
"code": null,
"e": 25768,
"s": 25752,
"text": "Travel involved"
},
{
"code": null,
"e": 25782,
"s": 25768,
"text": "Communication"
},
{
"code": null,
"e": 25803,
"s": 25782,
"text": "Training and support"
},
{
"code": null,
"e": 25901,
"s": 25803,
"text": "We discussed various parameters involving project estimation such as size, effort, time and cost."
},
{
"code": null,
"e": 25991,
"s": 25901,
"text": "Project manager can estimate the listed factors using two broadly recognized techniques –"
},
{
"code": null,
"e": 26065,
"s": 25991,
"text": "This technique assumes the software as a product of various compositions."
},
{
"code": null,
"e": 26093,
"s": 26065,
"text": "There are two main models -"
},
{
"code": null,
"e": 26187,
"s": 26093,
"text": "Line of Code Estimation is done on behalf of number of line of codes in the software product."
},
{
"code": null,
"e": 26286,
"s": 26187,
"text": "Function Points Estimation is done on behalf of number of function points in the software product."
},
{
"code": null,
"e": 26394,
"s": 26286,
"text": "This technique uses empirically derived formulae to make estimation.These formulae are based on LOC or FPs."
},
{
"code": null,
"e": 26584,
"s": 26394,
"text": "Putnam Model\nThis model is made by Lawrence H. Putnam, which is based on Norden’s frequency distribution (Rayleigh curve). Putnam model maps time and efforts required with software size. "
},
{
"code": null,
"e": 26761,
"s": 26584,
"text": "This model is made by Lawrence H. Putnam, which is based on Norden’s frequency distribution (Rayleigh curve). Putnam model maps time and efforts required with software size. "
},
{
"code": null,
"e": 26945,
"s": 26761,
"text": "COCOMO\nCOCOMO stands for COnstructive COst MOdel, developed by Barry W. Boehm. It divides the software product into three categories of software: organic, semi-detached and embedded."
},
{
"code": null,
"e": 27122,
"s": 26945,
"text": "COCOMO stands for COnstructive COst MOdel, developed by Barry W. Boehm. It divides the software product into three categories of software: organic, semi-detached and embedded."
},
{
"code": null,
"e": 27697,
"s": 27122,
"text": "Project Scheduling in a project refers to roadmap of all activities to be done with specified order and within time slot allotted to each activity. Project managers tend to tend to define various tasks, and project milestones and arrange them keeping various factors in mind. They look for tasks lie in critical path in the schedule, which are necessary to complete in specific manner (because of task interdependency) and strictly within the time allocated. Arrangement of tasks which lies out of critical path are less likely to impact over all schedule of the project."
},
{
"code": null,
"e": 27746,
"s": 27699,
"text": "For scheduling a project, it is necessary to -"
},
{
"code": null,
"e": 27806,
"s": 27746,
"text": "Break down the project tasks into smaller, manageable form "
},
{
"code": null,
"e": 27848,
"s": 27806,
"text": "Find out various tasks and correlate them"
},
{
"code": null,
"e": 27891,
"s": 27848,
"text": "Estimate time frame required for each task"
},
{
"code": null,
"e": 27919,
"s": 27891,
"text": "Divide time into work-units"
},
{
"code": null,
"e": 27970,
"s": 27919,
"text": "Assign adequate number of work-units for each task"
},
{
"code": null,
"e": 28037,
"s": 27970,
"text": "Calculate total time required for the project from start to finish"
},
{
"code": null,
"e": 28205,
"s": 28037,
"text": "All elements used to develop a software product may be assumed as resource for that project. This may include human resource, productive tools and software libraries."
},
{
"code": null,
"e": 28553,
"s": 28205,
"text": "The resources are available in limited quantity and stay in the organization as a pool of assets. The shortage of resources hampers the development of project and it can lag behind the schedule. Allocating extra resources increases development cost in the end. It is therefore necessary to estimate and allocate adequate resources for the project."
},
{
"code": null,
"e": 28584,
"s": 28553,
"text": "Resource management includes -"
},
{
"code": null,
"e": 28700,
"s": 28584,
"text": "Defining proper organization project by creating a project team and allocating responsibilities to each team member"
},
{
"code": null,
"e": 28776,
"s": 28700,
"text": "Determining resources required at a particular stage and their availability"
},
{
"code": null,
"e": 28900,
"s": 28776,
"text": "Manage Resources by generating resource request when they are required and de-allocating them when they are no more needed."
},
{
"code": null,
"e": 29092,
"s": 28900,
"text": "Risk management involves all activities pertaining to identification, analyzing and making provision for predictable and non-predictable risks in the project. Risk may include the following:"
},
{
"code": null,
"e": 29155,
"s": 29092,
"text": "Experienced staff leaving the project and new staff coming in."
},
{
"code": null,
"e": 29192,
"s": 29155,
"text": "Change in organizational management."
},
{
"code": null,
"e": 29243,
"s": 29192,
"text": "Requirement change or misinterpreting requirement."
},
{
"code": null,
"e": 29292,
"s": 29243,
"text": "Under-estimation of required time and resources."
},
{
"code": null,
"e": 29360,
"s": 29292,
"text": "Technological changes, environmental changes, business competition."
},
{
"code": null,
"e": 29428,
"s": 29360,
"text": "There are following activities involved in risk management process:"
},
{
"code": null,
"e": 29511,
"s": 29428,
"text": "Identification - Make note of all possible risks, which may occur in the project."
},
{
"code": null,
"e": 29634,
"s": 29511,
"text": "Categorize - Categorize known risks into high, medium and low risk intensity as per their possible impact on the project."
},
{
"code": null,
"e": 29784,
"s": 29634,
"text": "Manage - Analyze the probability of occurrence of risks at various phases. Make plan to avoid or face risks. Attempt to minimize their side-effects."
},
{
"code": null,
"e": 29924,
"s": 29784,
"text": "Monitor - Closely monitor the potential risks and their early symptoms. Also monitor the effects of steps taken to mitigate or avoid them."
},
{
"code": null,
"e": 30019,
"s": 29924,
"text": "In this phase, the tasks described in project plans are executed according to their schedules."
},
{
"code": null,
"e": 30252,
"s": 30019,
"text": "Execution needs monitoring in order to check whether everything is going according to the plan. Monitoring is observing to check the probability of risk and taking measures to address the risk or report the status of various tasks."
},
{
"code": null,
"e": 30277,
"s": 30252,
"text": "These measures include -"
},
{
"code": null,
"e": 30455,
"s": 30277,
"text": "Activity Monitoring - All activities scheduled within some task can be monitored on day-to-day basis. When all activities in a task are completed, it is considered as complete."
},
{
"code": null,
"e": 30646,
"s": 30455,
"text": "Status Reports - The reports contain status of activities and tasks completed within a given time frame, generally a week. Status can be marked as finished, pending or work-in-progress etc."
},
{
"code": null,
"e": 30886,
"s": 30646,
"text": "Milestones Checklist - Every project is divided into multiple phases where major tasks are performed (milestones) based on the phases of SDLC. This milestone checklist is prepared once every few weeks and reports the status of milestones."
},
{
"code": null,
"e": 31106,
"s": 30886,
"text": "Effective communication plays vital role in the success of a project. It bridges gaps between client and the organization, among the team members as well as other stake holders in the project such as hardware suppliers."
},
{
"code": null,
"e": 31208,
"s": 31106,
"text": "Communication can be oral or written. Communication management process may have the following steps: "
},
{
"code": null,
"e": 31416,
"s": 31208,
"text": "Planning - This step includes the identifications of all the stakeholders in the project and the mode of communication among them. It also considers if any additional communication facilities are required."
},
{
"code": null,
"e": 31655,
"s": 31416,
"text": "Sharing - After determining various aspects of planning, manager focuses on sharing correct information with the correct person on correct time. This keeps every one involved the project up to date with project progress and its status."
},
{
"code": null,
"e": 31885,
"s": 31655,
"text": "Feedback - Project managers use various measures and feedback mechanism and create status and performance reports. This mechanism ensures that input from various stakeholders is coming to the project manager as their feedback."
},
{
"code": null,
"e": 32157,
"s": 31885,
"text": "Closure - At the end of each major event, end of a phase of SDLC or end of the project itself, administrative closure is formally announced to update every stakeholder by sending email, by distributing a hardcopy of document or by other mean of effective communication."
},
{
"code": null,
"e": 32213,
"s": 32157,
"text": "After closure, the team moves to next phase or project."
},
{
"code": null,
"e": 32383,
"s": 32213,
"text": "Configuration management is a process of tracking and controlling the changes in software in terms of the requirements, design, functions and development of the product."
},
{
"code": null,
"e": 32658,
"s": 32383,
"text": "IEEE defines it as “the process of identifying and defining the items in the system, controlling the change of these items throughout their life cycle, recording and reporting the status of items and change requests, and verifying the completeness and correctness of items”."
},
{
"code": null,
"e": 32893,
"s": 32658,
"text": "Generally, once the SRS is finalized there is less chance of requirement of changes from user. If they occur, the changes are addressed only with prior approval of higher management, as there is a possibility of cost and time overrun."
},
{
"code": null,
"e": 33186,
"s": 32893,
"text": "A phase of SDLC is assumed over if it baselined, i.e. baseline is a measurement that defines completeness of a phase. A phase is baselined when all activities pertaining to it are finished and well documented. If it was not the final phase, its output would be used in next immediate phase."
},
{
"code": null,
"e": 33437,
"s": 33186,
"text": "Configuration management is a discipline of organization administration, which takes care of occurrence of any change (process, requirement, technological, strategical etc.) after a phase is baselined. CM keeps check on any changes done in software."
},
{
"code": null,
"e": 33617,
"s": 33437,
"text": "Change control is function of configuration management, which ensures that all changes made to software system are consistent and made as per organizational rules and regulations."
},
{
"code": null,
"e": 33689,
"s": 33617,
"text": "A change in the configuration of product goes through following steps -"
},
{
"code": null,
"e": 33843,
"s": 33689,
"text": "Identification - A change request arrives from either internal or external source. When change request is identified formally, it is properly documented."
},
{
"code": null,
"e": 33997,
"s": 33843,
"text": "Identification - A change request arrives from either internal or external source. When change request is identified formally, it is properly documented."
},
{
"code": null,
"e": 34093,
"s": 33997,
"text": "Validation - Validity of the change request is checked and its handling procedure is confirmed."
},
{
"code": null,
"e": 34189,
"s": 34093,
"text": "Validation - Validity of the change request is checked and its handling procedure is confirmed."
},
{
"code": null,
"e": 34354,
"s": 34189,
"text": "Analysis - The impact of change request is analyzed in terms of schedule, cost and required efforts. Overall impact of the prospective change on system is analyzed."
},
{
"code": null,
"e": 34519,
"s": 34354,
"text": "Analysis - The impact of change request is analyzed in terms of schedule, cost and required efforts. Overall impact of the prospective change on system is analyzed."
},
{
"code": null,
"e": 34833,
"s": 34519,
"text": "Control - If the prospective change either impacts too many entities in the system or it is unavoidable, it is mandatory to take approval of high authorities before change is incorporated into the system. It is decided if the change is worth incorporation or not. If it is not, change request is refused formally."
},
{
"code": null,
"e": 35147,
"s": 34833,
"text": "Control - If the prospective change either impacts too many entities in the system or it is unavoidable, it is mandatory to take approval of high authorities before change is incorporated into the system. It is decided if the change is worth incorporation or not. If it is not, change request is refused formally."
},
{
"code": null,
"e": 35321,
"s": 35147,
"text": "Execution - If the previous phase determines to execute the change request, this phase take appropriate actions to execute the change, does a thorough revision if necessary."
},
{
"code": null,
"e": 35495,
"s": 35321,
"text": "Execution - If the previous phase determines to execute the change request, this phase take appropriate actions to execute the change, does a thorough revision if necessary."
},
{
"code": null,
"e": 35711,
"s": 35495,
"text": "Close request - The change is verified for correct implementation and merging with the rest of the system. This newly incorporated change in the software is documented properly and the request is formally is closed."
},
{
"code": null,
"e": 35927,
"s": 35711,
"text": "Close request - The change is verified for correct implementation and merging with the rest of the system. This newly incorporated change in the software is documented properly and the request is formally is closed."
},
{
"code": null,
"e": 36076,
"s": 35927,
"text": "The risk and uncertainty rises multifold with respect to the size of the project, even when the project is developed according to set methodologies."
},
{
"code": null,
"e": 36169,
"s": 36076,
"text": "There are tools available, which aid for effective project management. A few are described -"
},
{
"code": null,
"e": 36389,
"s": 36169,
"text": "Gantt charts was devised by Henry Gantt (1917). It represents project schedule with respect to time periods. It is a horizontal bar chart with bars representing activities and time scheduled for the project activities."
},
{
"code": null,
"e": 36693,
"s": 36389,
"text": "PERT (Program Evaluation & Review Technique) chart is a tool that depicts project as network diagram. It is capable of graphically representing main events of project in both parallel and consecutive way. Events, which occur one after another, show dependency of the later event over the previous one."
},
{
"code": null,
"e": 36810,
"s": 36693,
"text": "Events are shown as numbered nodes. They are connected by labeled arrows depicting sequence of tasks in the project."
},
{
"code": null,
"e": 37048,
"s": 36810,
"text": "This is a graphical tool that contains bar or chart representing number of resources (usually skilled staff) required over time for a project event (or phase). Resource Histogram is an effective tool for staff planning and coordination."
},
{
"code": null,
"e": 37398,
"s": 37048,
"text": "This tools is useful in recognizing interdependent tasks in the project. It also helps to find out the shortest path or critical path to complete the project successfully. Like PERT diagram, each event is allotted a specific time frame. This tool shows dependency of event assuming an event can proceed to next only if the previous one is completed."
},
{
"code": null,
"e": 37605,
"s": 37398,
"text": "The events are arranged according to their earliest possible start time. Path between start and end node is critical path which cannot be further reduced and all events require to be executed in same order."
},
{
"code": null,
"e": 37888,
"s": 37605,
"text": "The software requirements are description of features and functionalities of the target system. Requirements convey the expectations of users from the software product. The requirements can be obvious or hidden, known or unknown, expected or unexpected from client’s point of view."
},
{
"code": null,
"e": 38012,
"s": 37888,
"text": "The process to gather the software requirements from client, analyze and document them is known as requirement engineering."
},
{
"code": null,
"e": 38151,
"s": 38012,
"text": "The goal of requirement engineering is to develop and maintain sophisticated and descriptive ‘System Requirements Specification’ document."
},
{
"code": null,
"e": 38196,
"s": 38151,
"text": "It is a four step process, which includes – "
},
{
"code": null,
"e": 38214,
"s": 38196,
"text": "Feasibility Study"
},
{
"code": null,
"e": 38236,
"s": 38214,
"text": "Requirement Gathering"
},
{
"code": null,
"e": 38271,
"s": 38236,
"text": "Software Requirement Specification"
},
{
"code": null,
"e": 38304,
"s": 38271,
"text": "Software Requirement Validation "
},
{
"code": null,
"e": 38338,
"s": 38304,
"text": "Let us see the process briefly - "
},
{
"code": null,
"e": 38562,
"s": 38338,
"text": "When the client approaches the organization for getting the desired product developed, it comes up with rough idea about what all functions the software must perform and which all features are expected from the software. "
},
{
"code": null,
"e": 38713,
"s": 38562,
"text": "Referencing to this information, the analysts does a detailed study about whether the desired system and its functionality are feasible to develop. "
},
{
"code": null,
"e": 39135,
"s": 38713,
"text": "This feasibility study is focused towards goal of the organization. This study analyzes whether the software product can be practically materialized in terms of implementation, contribution of project to organization, cost constraints and as per values and objectives of the organization. It explores technical aspects of the project and product such as usability, maintainability, productivity and integration ability."
},
{
"code": null,
"e": 39325,
"s": 39135,
"text": "The output of this phase should be a feasibility study report that should contain adequate comments and recommendations for management about whether or not the project should be undertaken."
},
{
"code": null,
"e": 39633,
"s": 39325,
"text": "If the feasibility report is positive towards undertaking the project, next phase starts with gathering requirements from the user. Analysts and engineers communicate with the client and end-users to know their ideas on what the software should provide and which features they want the software to include. "
},
{
"code": null,
"e": 39742,
"s": 39633,
"text": "SRS is a document created by system analyst after the requirements are collected from various stakeholders. "
},
{
"code": null,
"e": 40013,
"s": 39742,
"text": "SRS defines how the intended software will interact with hardware, external interfaces, speed of operation, response time of system, portability of software across various platforms, maintainability, speed of recovery after crashing, Security, Quality, Limitations etc. "
},
{
"code": null,
"e": 40257,
"s": 40013,
"text": "The requirements received from client are written in natural language. It is the responsibility of system analyst to document the requirements in technical language so that they can be comprehended and useful by the software development team. "
},
{
"code": null,
"e": 40302,
"s": 40257,
"text": "SRS should come up with following features: "
},
{
"code": null,
"e": 40355,
"s": 40302,
"text": "User Requirements are expressed in natural language."
},
{
"code": null,
"e": 40455,
"s": 40355,
"text": "Technical requirements are expressed in structured language, which is used inside the organization."
},
{
"code": null,
"e": 40508,
"s": 40455,
"text": "Design description should be written in Pseudo code."
},
{
"code": null,
"e": 40547,
"s": 40508,
"text": "Format of Forms and GUI screen prints."
},
{
"code": null,
"e": 40600,
"s": 40547,
"text": "Conditional and mathematical notations for DFDs etc."
},
{
"code": null,
"e": 40935,
"s": 40600,
"text": "After requirement specifications are developed, the requirements mentioned in this document are validated. User might ask for illegal, impractical solution or experts may interpret the requirements incorrectly. This results in huge increase in cost if not nipped in the bud. Requirements can be checked against following conditions -"
},
{
"code": null,
"e": 40974,
"s": 40935,
"text": "If they can be practically implemented"
},
{
"code": null,
"e": 41040,
"s": 40974,
"text": "If they are valid and as per functionality and domain of software"
},
{
"code": null,
"e": 41069,
"s": 41040,
"text": "If there are any ambiguities"
},
{
"code": null,
"e": 41090,
"s": 41069,
"text": "If they are complete"
},
{
"code": null,
"e": 41118,
"s": 41090,
"text": "If they can be demonstrated"
},
{
"code": null,
"e": 41195,
"s": 41118,
"text": "Requirement elicitation process can be depicted using the folloiwng diagram:"
},
{
"code": null,
"e": 41321,
"s": 41195,
"text": "Requirements gathering - The developers discuss with the client and end users and know their expectations from the software. "
},
{
"code": null,
"e": 41451,
"s": 41321,
"text": "Organizing Requirements - The developers prioritize and arrange the requirements in order of importance, urgency and convenience."
},
{
"code": null,
"e": 41900,
"s": 41451,
"text": "Negotiation & discussion - If requirements are ambiguous or there are some conflicts in requirements of various stakeholders, if they are, it is then negotiated and discussed with stakeholders. Requirements may then be prioritized and reasonably compromised.\nThe requirements come from various stakeholders. To remove the ambiguity and conflicts, they are discussed for clarity and correctness. Unrealistic requirements are compromised reasonably."
},
{
"code": null,
"e": 42160,
"s": 41900,
"text": "Negotiation & discussion - If requirements are ambiguous or there are some conflicts in requirements of various stakeholders, if they are, it is then negotiated and discussed with stakeholders. Requirements may then be prioritized and reasonably compromised."
},
{
"code": null,
"e": 42349,
"s": 42160,
"text": "The requirements come from various stakeholders. To remove the ambiguity and conflicts, they are discussed for clarity and correctness. Unrealistic requirements are compromised reasonably."
},
{
"code": null,
"e": 42492,
"s": 42349,
"text": "Documentation - All formal & informal, functional and non-functional requirements are documented and made available for next phase processing."
},
{
"code": null,
"e": 42711,
"s": 42492,
"text": "Requirements Elicitation is the process to find out the requirements for an intended software system by communicating with client, end users, system users and others who have a stake in the software system development."
},
{
"code": null,
"e": 42759,
"s": 42711,
"text": "There are various ways to discover requirements"
},
{
"code": null,
"e": 42876,
"s": 42759,
"text": "Interviews are strong medium to collect requirements. Organization may conduct several types of interviews such as: "
},
{
"code": null,
"e": 43025,
"s": 42876,
"text": "Structured (closed) interviews, where every single information to gather is decided in advance, they follow pattern and matter of discussion firmly."
},
{
"code": null,
"e": 43145,
"s": 43025,
"text": "Non-structured (open) interviews, where information to gather is not decided in advance, more flexible and less biased."
},
{
"code": null,
"e": 43162,
"s": 43145,
"text": "Oral interviews "
},
{
"code": null,
"e": 43181,
"s": 43162,
"text": "Written interviews"
},
{
"code": null,
"e": 43256,
"s": 43181,
"text": "One-to-one interviews which are held between two persons across the table."
},
{
"code": null,
"e": 43398,
"s": 43256,
"text": "Group interviews which are held between groups of participants. They help to uncover any missing requirement as numerous people are involved."
},
{
"code": null,
"e": 43538,
"s": 43398,
"text": "Organization may conduct surveys among various stakeholders by querying about their expectation and requirements from the upcoming system. "
},
{
"code": null,
"e": 43696,
"s": 43538,
"text": "A document with pre-defined set of objective questions and respective options is handed over to all stakeholders to answer, which are collected and compiled."
},
{
"code": null,
"e": 43835,
"s": 43696,
"text": "A shortcoming of this technique is, if an option for some issue is not mentioned in the questionnaire, the issue might be left unattended."
},
{
"code": null,
"e": 44068,
"s": 43835,
"text": "Team of engineers and developers may analyze the operation for which the new system is required. If the client already has some software to perform certain operation, it is studied and requirements of proposed system are collected. "
},
{
"code": null,
"e": 44216,
"s": 44068,
"text": "Every software falls into some domain category. The expert people in the domain can be a great help to analyze general and specific requirements. "
},
{
"code": null,
"e": 44339,
"s": 44216,
"text": "An informal debate is held among various stakeholders and all their inputs are recorded for further requirements analysis."
},
{
"code": null,
"e": 44862,
"s": 44339,
"text": "Prototyping is building user interface without adding detail functionality for user to interpret the features of intended software product. It helps giving better idea of requirements. If there is no software installed at client’s end for developer’s reference and the client is not aware of its own requirements, the developer creates a prototype based on initially mentioned requirements. The prototype is shown to the client and the feedback is noted. The client feedback serves as an input for requirement gathering."
},
{
"code": null,
"e": 45169,
"s": 44862,
"text": "Team of experts visit the client’s organization or workplace. They observe the actual working of the existing installed systems. They observe the workflow at client’s end and how execution problems are dealt. The team itself draws some conclusions which aid to form requirements expected from the software."
},
{
"code": null,
"e": 45315,
"s": 45169,
"text": "Gathering software requirements is the foundation of the entire software development project. Hence they must be clear, correct and well-defined."
},
{
"code": null,
"e": 45372,
"s": 45315,
"text": "A complete Software Requirement Specifications must be: "
},
{
"code": null,
"e": 45378,
"s": 45372,
"text": "Clear"
},
{
"code": null,
"e": 45386,
"s": 45378,
"text": "Correct"
},
{
"code": null,
"e": 45397,
"s": 45386,
"text": "Consistent"
},
{
"code": null,
"e": 45406,
"s": 45397,
"text": "Coherent"
},
{
"code": null,
"e": 45421,
"s": 45406,
"text": "Comprehensible"
},
{
"code": null,
"e": 45432,
"s": 45421,
"text": "Modifiable"
},
{
"code": null,
"e": 45443,
"s": 45432,
"text": "Verifiable"
},
{
"code": null,
"e": 45455,
"s": 45443,
"text": "Prioritized"
},
{
"code": null,
"e": 45467,
"s": 45455,
"text": "Unambiguous"
},
{
"code": null,
"e": 45477,
"s": 45467,
"text": "Traceable"
},
{
"code": null,
"e": 45493,
"s": 45477,
"text": "Credible source"
},
{
"code": null,
"e": 45665,
"s": 45493,
"text": "We should try to understand what sort of requirements may arise in the requirement elicitation phase and what kinds of requirements are expected from the software system. "
},
{
"code": null,
"e": 45736,
"s": 45665,
"text": "Broadly software requirements should be categorized in two categories:"
},
{
"code": null,
"e": 45826,
"s": 45736,
"text": "Requirements, which are related to functional aspect of software fall into this category."
},
{
"code": null,
"e": 45903,
"s": 45826,
"text": "They define functions and functionality within and from the software system."
},
{
"code": null,
"e": 45964,
"s": 45903,
"text": "Search option given to user to search from various invoices."
},
{
"code": null,
"e": 46019,
"s": 45964,
"text": "\tUser should be able to mail any report to management."
},
{
"code": null,
"e": 46093,
"s": 46019,
"text": "Users can be divided into groups and groups can be given separate rights."
},
{
"code": null,
"e": 46152,
"s": 46093,
"text": "Should comply business rules and administrative functions."
},
{
"code": null,
"e": 46214,
"s": 46152,
"text": " Software is developed keeping downward compatibility intact."
},
{
"code": null,
"e": 46401,
"s": 46214,
"text": "Requirements, which are not related to functional aspect of software, fall into this category. They are implicit or expected characteristics of software, which users make assumption of."
},
{
"code": null,
"e": 46440,
"s": 46401,
"text": " Non-functional requirements include -"
},
{
"code": null,
"e": 46449,
"s": 46440,
"text": "Security"
},
{
"code": null,
"e": 46457,
"s": 46449,
"text": "Logging"
},
{
"code": null,
"e": 46465,
"s": 46457,
"text": "Storage"
},
{
"code": null,
"e": 46479,
"s": 46465,
"text": "Configuration"
},
{
"code": null,
"e": 46491,
"s": 46479,
"text": "Performance"
},
{
"code": null,
"e": 46496,
"s": 46491,
"text": "Cost"
},
{
"code": null,
"e": 46513,
"s": 46496,
"text": "Interoperability"
},
{
"code": null,
"e": 46525,
"s": 46513,
"text": "Flexibility"
},
{
"code": null,
"e": 46543,
"s": 46525,
"text": "Disaster recovery"
},
{
"code": null,
"e": 46557,
"s": 46543,
"text": "Accessibility"
},
{
"code": null,
"e": 46600,
"s": 46557,
"text": "Requirements are categorized logically as "
},
{
"code": null,
"e": 46662,
"s": 46600,
"text": "Must Have : Software cannot be said operational without them."
},
{
"code": null,
"e": 46717,
"s": 46662,
"text": "Should have : Enhancing the functionality of software."
},
{
"code": null,
"e": 46792,
"s": 46717,
"text": "Could have : Software can still properly function with these requirements."
},
{
"code": null,
"e": 46865,
"s": 46792,
"text": "Wish list : These requirements do not map to any objectives of software."
},
{
"code": null,
"e": 47064,
"s": 46865,
"text": "While developing software, ‘Must have’ must be implemented, ‘Should have’ is a matter of debate with stakeholders and negation, whereas ‘could have’ and ‘wish list’ can be kept for software updates."
},
{
"code": null,
"e": 47176,
"s": 47064,
"text": "UI is an important part of any software or hardware or hybrid system. A software is widely accepted if it is -"
},
{
"code": null,
"e": 47193,
"s": 47176,
"text": "easy to operate "
},
{
"code": null,
"e": 47212,
"s": 47193,
"text": "quick in response "
},
{
"code": null,
"e": 47253,
"s": 47212,
"text": "effectively handling operational errors "
},
{
"code": null,
"e": 47301,
"s": 47253,
"text": "providing simple yet consistent user interface "
},
{
"code": null,
"e": 47758,
"s": 47301,
"text": "User acceptance majorly depends upon how user can use the software. UI is the only way for users to perceive the system. A well performing software system must also be equipped with attractive, clear, consistent and responsive user interface. Otherwise the functionalities of software system can not be used in convenient way. A system is said be good if it provides means to use it efficiently. User interface requirements are briefly mentioned below -"
},
{
"code": null,
"e": 47779,
"s": 47758,
"text": "Content presentation"
},
{
"code": null,
"e": 47795,
"s": 47779,
"text": "Easy Navigation"
},
{
"code": null,
"e": 47812,
"s": 47795,
"text": "Simple interface"
},
{
"code": null,
"e": 47823,
"s": 47812,
"text": "Responsive"
},
{
"code": null,
"e": 47846,
"s": 47823,
"text": "Consistent UI elements"
},
{
"code": null,
"e": 47865,
"s": 47846,
"text": "Feedback mechanism"
},
{
"code": null,
"e": 47882,
"s": 47865,
"text": "Default settings"
},
{
"code": null,
"e": 47900,
"s": 47882,
"text": "Purposeful layout"
},
{
"code": null,
"e": 47938,
"s": 47900,
"text": "Strategical use of color and texture."
},
{
"code": null,
"e": 47964,
"s": 47938,
"text": "Provide help information "
},
{
"code": null,
"e": 47986,
"s": 47964,
"text": "User centric approach"
},
{
"code": null,
"e": 48013,
"s": 47986,
"text": "Group based view settings."
},
{
"code": null,
"e": 48373,
"s": 48013,
"text": "System analyst in an IT organization is a person, who analyzes the requirement of proposed system and ensures that requirements are conceived and documented properly & correctly. Role of an analyst starts during Software Analysis Phase of SDLC. It is the responsibility of analyst to make sure that the developed software meets the requirements of the client."
},
{
"code": null,
"e": 48426,
"s": 48373,
"text": "System Analysts have the following responsibilities:"
},
{
"code": null,
"e": 48488,
"s": 48426,
"text": "Analyzing and understanding requirements of intended software"
},
{
"code": null,
"e": 48565,
"s": 48488,
"text": "Understanding how the project will contribute in the organization objectives"
},
{
"code": null,
"e": 48597,
"s": 48565,
"text": "Identify sources of requirement"
},
{
"code": null,
"e": 48623,
"s": 48597,
"text": "Validation of requirement"
},
{
"code": null,
"e": 48673,
"s": 48623,
"text": "Develop and implement requirement management plan"
},
{
"code": null,
"e": 48744,
"s": 48673,
"text": "Documentation of business, technical, process and product requirements"
},
{
"code": null,
"e": 48822,
"s": 48744,
"text": "Coordination with clients to prioritize requirements and remove and ambiguity"
},
{
"code": null,
"e": 48888,
"s": 48822,
"text": "Finalizing acceptance criteria with client and other stakeholders"
},
{
"code": null,
"e": 49012,
"s": 48888,
"text": "Software Measures can be understood as a process of quantifying and symbolizing various attributes and aspects of software."
},
{
"code": null,
"e": 49108,
"s": 49012,
"text": "Software Metrics provide measures for various aspects of software process and software product."
},
{
"code": null,
"e": 49302,
"s": 49108,
"text": "Software measures are fundamental requirement of software engineering. They not only help to control the software development process but also aid to keep quality of ultimate product excellent."
},
{
"code": null,
"e": 49466,
"s": 49302,
"text": "According to Tom DeMarco, a (Software Engineer), “You cannot control what you cannot measure.” By his saying, it is very clear how important software measures are."
},
{
"code": null,
"e": 49500,
"s": 49466,
"text": "Let us see some software metrics:"
},
{
"code": null,
"e": 49768,
"s": 49500,
"text": "Size Metrics - LOC (Lines of Code), mostly calculated in thousands of delivered source code lines, denoted as KLOC.\nFunction Point Count is measure of the functionality provided by the software. Function Point count defines the size of functional aspect of software."
},
{
"code": null,
"e": 49884,
"s": 49768,
"text": "Size Metrics - LOC (Lines of Code), mostly calculated in thousands of delivered source code lines, denoted as KLOC."
},
{
"code": null,
"e": 50036,
"s": 49884,
"text": "Function Point Count is measure of the functionality provided by the software. Function Point count defines the size of functional aspect of software."
},
{
"code": null,
"e": 50310,
"s": 50036,
"text": "Complexity Metrics - McCabe’s Cyclomatic complexity quantifies the upper bound of the number of independent paths in a program, which is perceived as complexity of the program or its modules. It is represented in terms of graph theory concepts by using control flow graph."
},
{
"code": null,
"e": 50633,
"s": 50310,
"text": "Quality Metrics - Defects, their types and causes, consequence, intensity of severity and their implications define the quality of product. \nThe number of defects found in development process and number of defects reported by the client after the product is installed or delivered at client-end, define quality of product."
},
{
"code": null,
"e": 50774,
"s": 50633,
"text": "Quality Metrics - Defects, their types and causes, consequence, intensity of severity and their implications define the quality of product. "
},
{
"code": null,
"e": 50956,
"s": 50774,
"text": "The number of defects found in development process and number of defects reported by the client after the product is installed or delivered at client-end, define quality of product."
},
{
"code": null,
"e": 51116,
"s": 50956,
"text": "Process Metrics - In various phases of SDLC, the methods and tools used, the company standards and the performance of development are software process metrics."
},
{
"code": null,
"e": 51221,
"s": 51116,
"text": "Resource Metrics - Effort, time and various resources used, represents metrics for resource measurement."
},
{
"code": null,
"e": 51372,
"s": 51221,
"text": "Software design is a process to transform user requirements into some suitable form, which helps the programmer in software coding and implementation."
},
{
"code": null,
"e": 51681,
"s": 51372,
"text": "For assessing user requirements, an SRS (Software Requirement Specification) document is created whereas for coding and implementation, there is a need of more specific and detailed requirements in software terms. The output of this process can directly be used into implementation in programming languages."
},
{
"code": null,
"e": 51893,
"s": 51681,
"text": "Software design is the first step in SDLC (Software Design Life Cycle), which moves the concentration from problem domain to solution domain. It tries to specify how to fulfill the requirements mentioned in SRS."
},
{
"code": null,
"e": 51941,
"s": 51893,
"text": "Software design yields three levels of results:"
},
{
"code": null,
"e": 52197,
"s": 51941,
"text": "Architectural Design - The architectural design is the highest abstract version of the system. It identifies the software as a system with many components interacting with each other. At this level, the designers get the idea of proposed solution domain."
},
{
"code": null,
"e": 52640,
"s": 52197,
"text": "High-level Design- The high-level design breaks the ‘single entity-multiple component’ concept of architectural design into less-abstracted view of sub-systems and modules and depicts their interaction with each other. High-level design focuses on how the system along with all of its components can be implemented in forms of modules. It recognizes modular structure of each sub-system and their relation and interaction among each other."
},
{
"code": null,
"e": 52950,
"s": 52640,
"text": "Detailed Design- Detailed design deals with the implementation part of what is seen as a system and its sub-systems in the previous two designs. It is more detailed towards modules and their implementations. It defines logical structure of each module and their interfaces to communicate with other modules."
},
{
"code": null,
"e": 53306,
"s": 52950,
"text": "Modularization is a technique to divide a software system into multiple discrete and independent modules, which are expected to be capable of carrying out task(s) independently. These modules may work as basic constructs for the entire software. Designers tend to design modules such that they can be executed and/or compiled separately and independently."
},
{
"code": null,
"e": 53498,
"s": 53306,
"text": "Modular design unintentionally follows the rules of ‘divide and conquer’ problem-solving strategy this is because there are many other benefits attached with the modular design of a software."
},
{
"code": null,
"e": 53527,
"s": 53498,
"text": "Advantage of modularization:"
},
{
"code": null,
"e": 53569,
"s": 53527,
"text": "Smaller components are easier to maintain"
},
{
"code": null,
"e": 53620,
"s": 53569,
"text": "Program can be divided based on functional aspects"
},
{
"code": null,
"e": 53679,
"s": 53620,
"text": "Desired level of abstraction can be brought in the program"
},
{
"code": null,
"e": 53730,
"s": 53679,
"text": "Components with high cohesion can be re-used again"
},
{
"code": null,
"e": 53772,
"s": 53730,
"text": "Concurrent execution can be made possible"
},
{
"code": null,
"e": 53801,
"s": 53772,
"text": "Desired from security aspect"
},
{
"code": null,
"e": 54152,
"s": 53801,
"text": "Back in time, all software are meant to be executed sequentially. By sequential execution we mean that the coded instruction will be executed one after another implying only one portion of program being activated at any given time. Say, a software has multiple modules, then only one of all the modules can be found active at any time of execution."
},
{
"code": null,
"e": 54446,
"s": 54152,
"text": "In software design, concurrency is implemented by splitting the software into multiple independent units of execution, like modules and executing them in parallel. In other words, concurrency provides capability to the software to execute more than one part of code in parallel to each other."
},
{
"code": null,
"e": 54563,
"s": 54446,
"text": "It is necessary for the programmers and designers to recognize those modules, which can be made parallel execution. "
},
{
"code": null,
"e": 54680,
"s": 54563,
"text": "The spell check feature in word processor is a module of software, which runs along side the word processor itself."
},
{
"code": null,
"e": 55139,
"s": 54680,
"text": "When a software program is modularized, its tasks are divided into several modules based on some characteristics. As we know, modules are set of instructions put together in order to achieve some tasks. They are though, considered as single entity but may refer to each other to work together. There are measures by which the quality of a design of modules and their interaction among them can be measured. These measures are called coupling and cohesion."
},
{
"code": null,
"e": 55298,
"s": 55139,
"text": "Cohesion is a measure that defines the degree of intra-dependability within elements of a module. The greater the cohesion, the better is the program design."
},
{
"code": null,
"e": 55342,
"s": 55298,
"text": "There are seven types of cohesion, namely –"
},
{
"code": null,
"e": 55606,
"s": 55342,
"text": "Co-incidental cohesion - It is unplanned and random cohesion, which might be the result of breaking the program into smaller modules for the sake of modularization. Because it is unplanned, it may serve confusion to the programmers and is generally not-accepted."
},
{
"code": null,
"e": 55724,
"s": 55606,
"text": "Logical cohesion - When logically categorized elements are put together into a module, it is called logical cohesion."
},
{
"code": null,
"e": 55871,
"s": 55724,
"text": "emporal Cohesion - When elements of module are organized such that they are processed at a similar point in time, it is called temporal cohesion."
},
{
"code": null,
"e": 56034,
"s": 55871,
"text": "Procedural cohesion - When elements of module are grouped together, which are executed sequentially in order to perform a task, it is called procedural cohesion."
},
{
"code": null,
"e": 56216,
"s": 56034,
"text": "Communicational cohesion - When elements of module are grouped together, which are executed sequentially and work on same data (information), it is called communicational cohesion."
},
{
"code": null,
"e": 56381,
"s": 56216,
"text": "Sequential cohesion - When elements of module are grouped because the output of one element serves as input to another and so on, it is called sequential cohesion."
},
{
"code": null,
"e": 56626,
"s": 56381,
"text": "Functional cohesion - It is considered to be the highest degree of cohesion, and it is highly expected. Elements of module in functional cohesion are grouped because they all contribute to a single well-defined function. It can also be reused."
},
{
"code": null,
"e": 56847,
"s": 56626,
"text": "Coupling is a measure that defines the level of inter-dependability among modules of a program. It tells at what level the modules interfere and interact with each other. The lower the coupling, the better the program."
},
{
"code": null,
"e": 56891,
"s": 56847,
"text": "There are five levels of coupling, namely -"
},
{
"code": null,
"e": 57035,
"s": 56891,
"text": "Content coupling - When a module can directly access or modify or refer to the content of another module, it is called content level coupling."
},
{
"code": null,
"e": 57163,
"s": 57035,
"text": "Common coupling- When multiple modules have read and write access to some global data, it is called common or global coupling."
},
{
"code": null,
"e": 57312,
"s": 57163,
"text": "Control coupling- Two modules are called control-coupled if one of them decides the function of the other module or changes its flow of execution."
},
{
"code": null,
"e": 57443,
"s": 57312,
"text": "Stamp coupling- When multiple modules share common data structure and work on different part of it, it is called stamp coupling."
},
{
"code": null,
"e": 57665,
"s": 57443,
"text": "Data coupling- Data coupling is when two modules interact with each other by means of passing data (as parameter). If a module passes data structure as parameter, then the receiving module should use all its components."
},
{
"code": null,
"e": 57716,
"s": 57665,
"text": "Ideally, no coupling is considered to be the best."
},
{
"code": null,
"e": 57912,
"s": 57716,
"text": "The output of software design process is design documentation, pseudo codes, detailed logic diagrams, process diagrams, and detailed description of all functional or non-functional requirements. "
},
{
"code": null,
"e": 58012,
"s": 57912,
"text": "The next phase, which is the implementation of software, depends on all outputs mentioned above. "
},
{
"code": null,
"e": 58410,
"s": 58012,
"text": "It is then becomes necessary to verify the output before proceeding to the next phase. The early any mistake is detected, the better it is or it might not be detected until testing of the product. If the outputs of design phase are in formal notation form, then their associated tools for verification should be used otherwise a thorough design review can be used for verification and validation."
},
{
"code": null,
"e": 58612,
"s": 58410,
"text": "By structured verification approach, reviewers can detect defects that might be caused by overlooking some conditions. A good design review is important for good software design, accuracy and quality."
},
{
"code": null,
"e": 58988,
"s": 58612,
"text": "Software analysis and design includes all activities, which help the transformation of requirement specification into implementation. Requirement specifications specify all functional and non-functional expectations from the software. These requirement specifications come in the shape of human readable and understandable documents, to which a computer has nothing to do. "
},
{
"code": null,
"e": 59120,
"s": 58988,
"text": "Software analysis and design is the intermediate stage, which helps human-readable requirements to be transformed into actual code."
},
{
"code": null,
"e": 59189,
"s": 59120,
"text": "Let us see few analysis and design tools used by software designers:"
},
{
"code": null,
"e": 59435,
"s": 59189,
"text": "Data flow diagram is graphical representation of flow of data in an information system. It is capable of depicting incoming data flow, outgoing data flow and stored data. The DFD does not mention anything about how data flows through the system."
},
{
"code": null,
"e": 59663,
"s": 59435,
"text": "There is a prominent difference between DFD and Flowchart. The flowchart depicts flow of control in program modules. DFDs depict flow of data in the system at various levels. DFD does not contain any control or branch elements."
},
{
"code": null,
"e": 59714,
"s": 59663,
"text": "Data Flow Diagrams are either Logical or Physical."
},
{
"code": null,
"e": 59900,
"s": 59714,
"text": "Logical DFD - This type of DFD concentrates on the system process, and flow of data in the system.For example in a Banking software system, how data is moved between different entities."
},
{
"code": null,
"e": 60049,
"s": 59900,
"text": "Physical DFD - This type of DFD shows how the data flow is actually implemented in the system. It is more specific and close to the implementation."
},
{
"code": null,
"e": 60153,
"s": 60049,
"text": "DFD can represent Source, destination, storage and flow of data using the following set of components -"
},
{
"code": null,
"e": 60292,
"s": 60153,
"text": "Entities - Entities are source and destination of information data. Entities are represented by a rectangles with their respective names."
},
{
"code": null,
"e": 60395,
"s": 60292,
"text": "Process - Activities and action taken on the data are represented by Circle or Round-edged rectangles."
},
{
"code": null,
"e": 60590,
"s": 60395,
"text": "Data Storage - There are two variants of data storage - it can either be represented as a rectangle with absence of both smaller sides or as an open-sided rectangle with only one side missing."
},
{
"code": null,
"e": 60750,
"s": 60590,
"text": "Data Flow - Movement of data is shown by pointed arrows. Data movement is shown from the base of arrow as its source towards head of the arrow as destination."
},
{
"code": null,
"e": 60965,
"s": 60750,
"text": "Level 0 - Highest abstraction level DFD is known as Level 0 DFD, which depicts the entire information system as one diagram concealing all the underlying details. Level 0 DFDs are also known as context level DFDs."
},
{
"code": null,
"e": 61198,
"s": 60965,
"text": "Level 1 - The Level 0 DFD is broken down into more specific, Level 1 DFD. Level 1 DFD depicts basic modules in the system and flow of data among various modules. Level 1 DFD also mentions basic processes and sources of information."
},
{
"code": null,
"e": 61452,
"s": 61198,
"text": "Level 2 - At this level, DFD shows how data flows inside the modules mentioned in Level 1.\nHigher level DFDs can be transformed into more specific lower level DFDs with deeper level of understanding unless the desired level of specification is achieved."
},
{
"code": null,
"e": 61543,
"s": 61452,
"text": "Level 2 - At this level, DFD shows how data flows inside the modules mentioned in Level 1."
},
{
"code": null,
"e": 61706,
"s": 61543,
"text": "Higher level DFDs can be transformed into more specific lower level DFDs with deeper level of understanding unless the desired level of specification is achieved."
},
{
"code": null,
"e": 61981,
"s": 61706,
"text": "Structure chart is a chart derived from Data Flow Diagram. It represents the system in more detail than DFD. It breaks down the entire system into lowest functional modules, describes functions and sub-functions of each module of the system to a greater detail than DFD."
},
{
"code": null,
"e": 62087,
"s": 61981,
"text": "Structure chart represents hierarchical structure of modules. At each layer a specific task is performed."
},
{
"code": null,
"e": 62152,
"s": 62087,
"text": "Here are the symbols used in construction of structure charts -"
},
{
"code": null,
"e": 62324,
"s": 62152,
"text": "Module - It represents process or subroutine or task. A control module branches to more than one sub-module. Library Modules are re-usable and invokable from any module.\n"
},
{
"code": null,
"e": 62483,
"s": 62324,
"text": "Condition - It is represented by small diamond at the base of module. It depicts that control module can select any of sub-routine based on some condition.\n"
},
{
"code": null,
"e": 62606,
"s": 62483,
"text": "Jump - An arrow is shown pointing inside the module to depict that the control will jump in the middle of the sub-module.\n"
},
{
"code": null,
"e": 62722,
"s": 62606,
"text": "Loop - A curved arrow represents loop in the module. All sub-modules covered by loop repeat execution of module.\n"
},
{
"code": null,
"e": 62803,
"s": 62722,
"text": "Data flow - A directed arrow with empty circle at the end represents data flow.\n"
},
{
"code": null,
"e": 62892,
"s": 62803,
"text": "Control flow - A directed arrow with filled circle at the end represents control flow.\n"
},
{
"code": null,
"e": 63090,
"s": 62892,
"text": "HIPO (Hierarchical Input Process Output) diagram is a combination of two organized method to analyze the system and provide the means of documentation. HIPO model was developed by IBM in year 1970."
},
{
"code": null,
"e": 63366,
"s": 63090,
"text": "HIPO diagram represents the hierarchy of modules in the software system. Analyst uses HIPO diagram in order to obtain high-level view of system functions. It decomposes functions into sub-functions in a hierarchical manner. It depicts the functions performed by system. "
},
{
"code": null,
"e": 63543,
"s": 63366,
"text": "HIPO diagrams are good for documentation purpose. Their graphical representation makes it easier for designers and managers to get the pictorial idea of the system structure. "
},
{
"code": null,
"e": 63722,
"s": 63543,
"text": "In contrast to IPO (Input Process Output) diagram, which depicts the flow of control and data in a module, HIPO does not provide any information about data flow or control flow."
},
{
"code": null,
"e": 63878,
"s": 63722,
"text": "Both parts of HIPO diagram, Hierarchical presentation and IPO Chart are used for structure design of software program as well as documentation of the same."
},
{
"code": null,
"e": 64140,
"s": 63878,
"text": "Most programmers are unaware of the large picture of software so they only rely on what their managers tell them to do. It is the responsibility of higher software management to provide accurate information to the programmers to develop accurate yet fast code."
},
{
"code": null,
"e": 64257,
"s": 64140,
"text": "Other forms of methods, which use graphs or diagrams, may are sometimes interpreted differently by different people."
},
{
"code": null,
"e": 64499,
"s": 64257,
"text": "Hence, analysts and designers of the software come up with tools such as Structured English. It is nothing but the description of what is required to code and how to code it. Structured English helps the programmer to write error-free code. "
},
{
"code": null,
"e": 64703,
"s": 64499,
"text": "Other form of methods, which use graphs or diagrams, may are sometimes interpreted differently by different people. Here, both Structured English and Pseudo-Code tries to mitigate that understanding gap."
},
{
"code": null,
"e": 64950,
"s": 64703,
"text": "Structured English is the It uses plain English words in structured programming paradigm. It is not the ultimate code but a kind of description what is required to code and how to code it. The following are some tokens of structured programming."
},
{
"code": null,
"e": 64981,
"s": 64950,
"text": "IF-THEN-ELSE, \nDO-WHILE-UNTIL"
},
{
"code": null,
"e": 65121,
"s": 64981,
"text": "Analyst uses the same variable and data name, which are stored in Data Dictionary, making it much simpler to write and understand the code."
},
{
"code": null,
"e": 65290,
"s": 65121,
"text": "We take the same example of Customer Authentication in the online shopping environment. This procedure to authenticate customer can be written in Structured English as:"
},
{
"code": null,
"e": 65504,
"s": 65290,
"text": "Enter Customer_Name\nSEEK Customer_Name in Customer_Name_DB file\nIF Customer_Name found THEN\n Call procedure USER_PASSWORD_AUTHENTICATE()\nELSE\n PRINT error message\n Call procedure NEW_CUSTOMER_REQUEST()\nENDIF"
},
{
"code": null,
"e": 65701,
"s": 65504,
"text": "The code written in Structured English is more like day-to-day spoken English. It can not be implemented directly as a code of software. Structured English is independent of programming language."
},
{
"code": null,
"e": 65854,
"s": 65701,
"text": "Pseudo code is written more close to programming language. It may be considered as augmented programming language, full of comments and descriptions. "
},
{
"code": null,
"e": 65997,
"s": 65854,
"text": "Pseudo code avoids variable declaration but they are written using some actual programming language’s constructs, like C, Fortran, Pascal etc."
},
{
"code": null,
"e": 66151,
"s": 65997,
"text": "Pseudo code contains more programming details than Structured English. It provides a method to perform the task, as if a computer is executing the code."
},
{
"code": null,
"e": 66195,
"s": 66151,
"text": "Program to print Fibonacci up to n numbers."
},
{
"code": null,
"e": 66469,
"s": 66195,
"text": "void function Fibonacci\nGet value of n;\nSet value of a to 1;\nSet value of b to 1;\nInitialize I to 0\nfor (i=0; i< n; i++)\n{\n if a greater than b \n {\n Increase b by a;\n Print b;\n } \n else if b greater than a\n {\n increase a by b;\n print a;\n }\n}"
},
{
"code": null,
"e": 66596,
"s": 66469,
"text": "A Decision table represents conditions and the respective actions to be taken to address them, in a structured tabular format."
},
{
"code": null,
"e": 66780,
"s": 66596,
"text": "It is a powerful tool to debug and prevent errors. It helps group similar information into a single table and then by combining tables it delivers easy and convenient decision-making."
},
{
"code": null,
"e": 66854,
"s": 66780,
"text": "To create the decision table, the developer must follow basic four steps:"
},
{
"code": null,
"e": 66903,
"s": 66854,
"text": "Identify all possible conditions to be addressed"
},
{
"code": null,
"e": 66951,
"s": 66903,
"text": "Determine actions for all identified conditions"
},
{
"code": null,
"e": 66981,
"s": 66951,
"text": "Create Maximum possible rules"
},
{
"code": null,
"e": 67009,
"s": 66981,
"text": "Define action for each rule"
},
{
"code": null,
"e": 67130,
"s": 67009,
"text": "Decision Tables should be verified by end-users and can lately be simplified by eliminating duplicate rules and actions."
},
{
"code": null,
"e": 67336,
"s": 67130,
"text": "Let us take a simple example of day-to-day problem with our Internet connectivity. We begin by identifying all problems that can arise while starting the internet and their respective possible solutions. "
},
{
"code": null,
"e": 67440,
"s": 67336,
"text": "We list all possible problems under column conditions and the prospective actions under column Actions."
},
{
"code": null,
"e": 67726,
"s": 67440,
"text": "Entity-Relationship model is a type of database model based on the notion of real world entities and relationship among them. We can map real world scenario onto ER database model. ER Model creates a set of entities with their attributes, a set of constraints and relation among them."
},
{
"code": null,
"e": 67828,
"s": 67726,
"text": "ER Model is best used for the conceptual design of database. ER Model can be represented as follows :"
},
{
"code": null,
"e": 68145,
"s": 67828,
"text": "Entity - An entity in ER Model is a real world being, which has some properties called attributes. Every attribute is defined by its corresponding set of values, called domain.\nFor example, Consider a school database. Here, a student is an entity. Student has various attributes like name, id, age and class etc."
},
{
"code": null,
"e": 68324,
"s": 68145,
"text": "Entity - An entity in ER Model is a real world being, which has some properties called attributes. Every attribute is defined by its corresponding set of values, called domain."
},
{
"code": null,
"e": 68462,
"s": 68324,
"text": "For example, Consider a school database. Here, a student is an entity. Student has various attributes like name, id, age and class etc."
},
{
"code": null,
"e": 68749,
"s": 68462,
"text": "Relationship - The logical association among entities is called relationship. Relationships are mapped with entities in various ways. Mapping cardinalities define the number of associations between two entities.\nMapping cardinalities:\n\none to one\none to many\nmany to one\nmany to many\n\n"
},
{
"code": null,
"e": 68962,
"s": 68749,
"text": "Relationship - The logical association among entities is called relationship. Relationships are mapped with entities in various ways. Mapping cardinalities define the number of associations between two entities."
},
{
"code": null,
"e": 68985,
"s": 68962,
"text": "Mapping cardinalities:"
},
{
"code": null,
"e": 68996,
"s": 68985,
"text": "one to one"
},
{
"code": null,
"e": 69008,
"s": 68996,
"text": "one to many"
},
{
"code": null,
"e": 69020,
"s": 69008,
"text": "many to one"
},
{
"code": null,
"e": 69033,
"s": 69020,
"text": "many to many"
},
{
"code": null,
"e": 69312,
"s": 69033,
"text": "Data dictionary is the centralized collection of information about data. It stores meaning and origin of data, its relationship with other data, data format for usage etc. Data dictionary has rigorous definitions of all names in order to facilitate user and software designers."
},
{
"code": null,
"e": 69534,
"s": 69312,
"text": "Data dictionary is often referenced as meta-data (data about data) repository. It is created along with DFD (Data Flow Diagram) model of software program and is expected to be updated whenever DFD is changed or updated."
},
{
"code": null,
"e": 69797,
"s": 69534,
"text": "The data is referenced via data dictionary while designing and implementing software. Data dictionary removes any chances of ambiguity. It helps keeping work of programmers and designers synchronized while using same object reference everywhere in the program."
},
{
"code": null,
"e": 69950,
"s": 69797,
"text": "Data dictionary provides a way of documentation for the complete database system in one place. Validation of DFD is carried out using data dictionary."
},
{
"code": null,
"e": 70014,
"s": 69950,
"text": "Data dictionary should contain information about the following "
},
{
"code": null,
"e": 70024,
"s": 70014,
"text": "Data Flow"
},
{
"code": null,
"e": 70039,
"s": 70024,
"text": "Data Structure"
},
{
"code": null,
"e": 70053,
"s": 70039,
"text": "Data Elements"
},
{
"code": null,
"e": 70065,
"s": 70053,
"text": "Data Stores"
},
{
"code": null,
"e": 70081,
"s": 70065,
"text": "Data Processing"
},
{
"code": null,
"e": 70188,
"s": 70081,
"text": "Data Flow is described by means of DFDs as studied earlier and represented in algebraic form as described."
},
{
"code": null,
"e": 70240,
"s": 70188,
"text": "Address = House No + (Street / Area) + City + State"
},
{
"code": null,
"e": 70311,
"s": 70240,
"text": "Course ID = Course Number + Course Name + Course Level + Course Grades"
},
{
"code": null,
"e": 70451,
"s": 70311,
"text": "Data elements consist of Name and descriptions of Data and Control Items, Internal or External data stores etc. with the following details:"
},
{
"code": null,
"e": 70464,
"s": 70451,
"text": "Primary Name"
},
{
"code": null,
"e": 70487,
"s": 70464,
"text": "Secondary Name (Alias)"
},
{
"code": null,
"e": 70520,
"s": 70487,
"text": "Use-case (How and where to use)"
},
{
"code": null,
"e": 70557,
"s": 70520,
"text": "Content Description (Notation etc. )"
},
{
"code": null,
"e": 70617,
"s": 70557,
"text": "Supplementary Information (preset values, constraints etc.)"
},
{
"code": null,
"e": 70746,
"s": 70617,
"text": "It stores the information from where the data enters into the system and exists out of the system. The Data Store may include -"
},
{
"code": null,
"e": 70886,
"s": 70746,
"text": "Files\n\nInternal to software.\nExternal to software but on the same machine.\nExternal to software and system, located on different machine.\n\n"
},
{
"code": null,
"e": 70908,
"s": 70886,
"text": "Internal to software."
},
{
"code": null,
"e": 70954,
"s": 70908,
"text": "External to software but on the same machine."
},
{
"code": null,
"e": 71017,
"s": 70954,
"text": "External to software and system, located on different machine."
},
{
"code": null,
"e": 71065,
"s": 71017,
"text": "Tables\n\nNaming convention\n Indexing property\n\n"
},
{
"code": null,
"e": 71083,
"s": 71065,
"text": "Naming convention"
},
{
"code": null,
"e": 71103,
"s": 71083,
"text": " Indexing property"
},
{
"code": null,
"e": 71143,
"s": 71103,
"text": "There are two types of Data Processing:"
},
{
"code": null,
"e": 71168,
"s": 71143,
"text": "Logical: As user sees it"
},
{
"code": null,
"e": 71198,
"s": 71168,
"text": "Physical: As software sees it"
},
{
"code": null,
"e": 71535,
"s": 71198,
"text": "Software design is a process to conceptualize the software requirements into software implementation. Software design takes the user requirements as challenges and tries to find optimum solution. While the software is being conceptualized, a plan is chalked out to find the best possible design for implementing the intended solution. "
},
{
"code": null,
"e": 71610,
"s": 71535,
"text": "There are multiple variants of software design. Let us study them briefly:"
},
{
"code": null,
"e": 71967,
"s": 71610,
"text": "Structured design is a conceptualization of problem into several well-organized elements of solution. It is basically concerned with the solution design. Benefit of structured design is, it gives better understanding of how the problem is being solved. Structured design also makes it simpler for designer to concentrate on the problem more accurately. "
},
{
"code": null,
"e": 72169,
"s": 71967,
"text": "Structured design is mostly based on ‘divide and conquer’ strategy where a problem is broken into several small problems and each small problem is individually solved until the whole problem is solved."
},
{
"code": null,
"e": 72343,
"s": 72169,
"text": "The small pieces of problem are solved by means of solution modules. Structured design emphasis that these modules be well organized in order to achieve precise solution. "
},
{
"code": null,
"e": 72520,
"s": 72343,
"text": "These modules are arranged in hierarchy. They communicate with each other. A good structured design always follows some rules for communication among multiple modules, namely -"
},
{
"code": null,
"e": 72579,
"s": 72520,
"text": "Cohesion - grouping of all functionally related elements."
},
{
"code": null,
"e": 72631,
"s": 72579,
"text": "Coupling - communication between different modules."
},
{
"code": null,
"e": 72705,
"s": 72631,
"text": "A good structured design has high cohesion and low coupling arrangements."
},
{
"code": null,
"e": 72936,
"s": 72705,
"text": "In function-oriented design, the system is comprised of many smaller sub-systems known as functions. These functions are capable of performing significant task in the system. The system is considered as top view of all functions."
},
{
"code": null,
"e": 73053,
"s": 72936,
"text": "Function oriented design inherits some properties of structured design where divide and conquer methodology is used."
},
{
"code": null,
"e": 73350,
"s": 73053,
"text": "This design mechanism divides the whole system into smaller functions, which provides means of abstraction by concealing the information and their operation.. These functional modules can share information among themselves by means of information passing and using information available globally."
},
{
"code": null,
"e": 73661,
"s": 73350,
"text": "Another characteristic of functions is that when a program calls a function, the function changes the state of the program, which sometimes is not acceptable by other modules. Function oriented design works well where the system state does not matter and program/functions work on input rather than on a state."
},
{
"code": null,
"e": 73749,
"s": 73661,
"text": "The whole system is seen as how data flows in the system by means of data flow diagram."
},
{
"code": null,
"e": 73817,
"s": 73749,
"text": "DFD depicts how functions changes data and state of entire system."
},
{
"code": null,
"e": 73945,
"s": 73817,
"text": "The entire system is logically broken down into smaller units known as functions on the basis of their operation in the system."
},
{
"code": null,
"e": 73987,
"s": 73945,
"text": "Each function is then described at large."
},
{
"code": null,
"e": 74263,
"s": 73987,
"text": "Object oriented design works around the entities and their characteristics instead of functions involved in the software system. This design strategies focuses on entities and its characteristics. The whole concept of software solution revolves around the engaged entities."
},
{
"code": null,
"e": 74324,
"s": 74263,
"text": "Let us see the important concepts of Object Oriented Design:"
},
{
"code": null,
"e": 74578,
"s": 74324,
"text": "Objects - All entities involved in the solution design are known as objects. For example, person, banks, company and customers are treated as objects. Every entity has some attributes associated to it and has some methods to perform on the attributes."
},
{
"code": null,
"e": 74923,
"s": 74578,
"text": "Classes - A class is a generalized description of an object. An object is an instance of a class. Class defines all the attributes, which an object can have and methods, which defines the functionality of the object.\nIn the solution design, attributes are stored as variables and functionalities are defined by means of methods or procedures."
},
{
"code": null,
"e": 75142,
"s": 74923,
"text": "Classes - A class is a generalized description of an object. An object is an instance of a class. Class defines all the attributes, which an object can have and methods, which defines the functionality of the object."
},
{
"code": null,
"e": 75268,
"s": 75142,
"text": "In the solution design, attributes are stored as variables and functionalities are defined by means of methods or procedures."
},
{
"code": null,
"e": 75591,
"s": 75268,
"text": "Encapsulation - In OOD, the attributes (data variables) and methods (operation on the data) are bundled together is called encapsulation. Encapsulation not only bundles important information of an object together, but also restricts access of the data and methods from the outside world. This is called information hiding."
},
{
"code": null,
"e": 75945,
"s": 75591,
"text": "Inheritance - OOD allows similar classes to stack up in hierarchical manner where the lower or sub-classes can import, implement and re-use allowed variables and methods from their immediate super classes. This property of OOD is known as inheritance. This makes it easier to define specific class and to create generalized classes from specific ones."
},
{
"code": null,
"e": 76274,
"s": 75945,
"text": "Polymorphism - OOD languages provide a mechanism where methods performing similar tasks but vary in arguments, can be assigned same name. This is called polymorphism, which allows a single interface performing tasks for different types. Depending upon how the function is invoked, respective portion of the code gets executed. "
},
{
"code": null,
"e": 76480,
"s": 76274,
"text": "Software design process can be perceived as series of well-defined steps. Though it varies according to design approach (function oriented or object oriented, yet It may have the following steps involved:"
},
{
"code": null,
"e": 76582,
"s": 76480,
"text": "A solution design is created from requirement or previous used system and/or system sequence diagram."
},
{
"code": null,
"e": 76684,
"s": 76582,
"text": "Objects are identified and grouped into classes on behalf of similarity in attribute characteristics."
},
{
"code": null,
"e": 76736,
"s": 76684,
"text": "Class hierarchy and relation among them is defined."
},
{
"code": null,
"e": 76770,
"s": 76736,
"text": "Application framework is defined."
},
{
"code": null,
"e": 76826,
"s": 76770,
"text": "Here are two generic approaches for software designing:"
},
{
"code": null,
"e": 77073,
"s": 76826,
"text": "We know that a system is composed of more than one sub-systems and it contains a number of components. Further, these sub-systems and components may have their on set of sub-system and components and creates hierarchical structure in the system."
},
{
"code": null,
"e": 77423,
"s": 77073,
"text": "Top-down design takes the whole software system as one entity and then decomposes it to achieve more than one sub-system or component based on some characteristics. Each sub-system or component is then treated as a system and decomposed further. This process keeps on running until the lowest level of system in the top-down hierarchy is achieved."
},
{
"code": null,
"e": 77606,
"s": 77423,
"text": "Top-down design starts with a generalized model of system and keeps on defining the more specific part of it. When all components are composed the whole system comes into existence."
},
{
"code": null,
"e": 77734,
"s": 77606,
"text": "Top-down design is more suitable when the software solution needs to be designed from scratch and specific details are unknown."
},
{
"code": null,
"e": 78078,
"s": 77734,
"text": "The bottom up design model starts with most specific and basic components. It proceeds with composing higher level of components by using basic or lower level components. It keeps creating higher level components until the desired system is not evolved as one single component. With each higher level, the amount of abstraction is increased."
},
{
"code": null,
"e": 78236,
"s": 78078,
"text": "Bottom-up strategy is more suitable when a system needs to be created from some existing system, where the basic primitives can be used in the newer system."
},
{
"code": null,
"e": 78353,
"s": 78236,
"text": "Both, top-down and bottom-up approaches are not practical individually. Instead, a good combination of both is used."
},
{
"code": null,
"e": 78717,
"s": 78353,
"text": "User interface is the front-end application view to which user interacts in order to use the software. User can manipulate and control the software as well as hardware by means of user interface. Today, user interface is found at almost every place where digital technology exists, right from computers, mobile phones, cars, music players, airplanes, ships etc."
},
{
"code": null,
"e": 78912,
"s": 78717,
"text": "User interface is part of software and is designed such a way that it is expected to provide the user insight of the software. UI provides fundamental platform for human-computer interaction. "
},
{
"code": null,
"e": 79087,
"s": 78912,
"text": "UI can be graphical, text-based, audio-video based, depending upon the underlying hardware and software combination. UI can be hardware or software or a combination of both."
},
{
"code": null,
"e": 79147,
"s": 79087,
"text": "The software becomes more popular if its user interface is:"
},
{
"code": null,
"e": 79158,
"s": 79147,
"text": "Attractive"
},
{
"code": null,
"e": 79172,
"s": 79158,
"text": "Simple to use"
},
{
"code": null,
"e": 79197,
"s": 79172,
"text": "Responsive in short time"
},
{
"code": null,
"e": 79217,
"s": 79197,
"text": "Clear to understand"
},
{
"code": null,
"e": 79255,
"s": 79217,
"text": "Consistent on all interfacing screens"
},
{
"code": null,
"e": 79298,
"s": 79255,
"text": "UI is broadly divided into two categories:"
},
{
"code": null,
"e": 79321,
"s": 79298,
"text": "Command Line Interface"
},
{
"code": null,
"e": 79346,
"s": 79321,
"text": "Graphical User Interface"
},
{
"code": null,
"e": 79579,
"s": 79346,
"text": "CLI has been a great tool of interaction with computers until the video display monitors came into existence. CLI is first choice of many technical users and programmers. CLI is minimum interface a software can provide to its users."
},
{
"code": null,
"e": 79812,
"s": 79579,
"text": "CLI provides a command prompt, the place where the user types the command and feeds to the system. The user needs to remember the syntax of command and its use. Earlier CLI were not programmed to handle the user errors effectively."
},
{
"code": null,
"e": 80003,
"s": 79812,
"text": "A command is a text-based reference to set of instructions, which are expected to be executed by the system. There are methods like macros, scripts that make it easy for the user to operate."
},
{
"code": null,
"e": 80065,
"s": 80003,
"text": "CLI uses less amount of computer resource as compared to GUI."
},
{
"code": null,
"e": 80134,
"s": 80065,
"text": "A text-based command line interface can have the following elements:"
},
{
"code": null,
"e": 80282,
"s": 80134,
"text": "Command Prompt - It is text-based notifier that is mostly shows the context in which the user is working. It is generated by the software system."
},
{
"code": null,
"e": 80430,
"s": 80282,
"text": "Command Prompt - It is text-based notifier that is mostly shows the context in which the user is working. It is generated by the software system."
},
{
"code": null,
"e": 80652,
"s": 80430,
"text": "Cursor - It is a small horizontal line or a vertical bar of the height of line, to represent position of character while typing. Cursor is mostly found in blinking state. It moves as the user writes or deletes something."
},
{
"code": null,
"e": 80874,
"s": 80652,
"text": "Cursor - It is a small horizontal line or a vertical bar of the height of line, to represent position of character while typing. Cursor is mostly found in blinking state. It moves as the user writes or deletes something."
},
{
"code": null,
"e": 81091,
"s": 80874,
"text": "Command - A command is an executable instruction. It may have one or more parameters. Output on command execution is shown inline on the screen. When output is produced, command prompt is displayed on the next line."
},
{
"code": null,
"e": 81308,
"s": 81091,
"text": "Command - A command is an executable instruction. It may have one or more parameters. Output on command execution is shown inline on the screen. When output is produced, command prompt is displayed on the next line."
},
{
"code": null,
"e": 81491,
"s": 81308,
"text": "Graphical User Interface provides the user graphical means to interact with the system. GUI can be combination of both hardware and software. Using GUI, user interprets the software."
},
{
"code": null,
"e": 81687,
"s": 81491,
"text": "Typically, GUI is more resource consuming than that of CLI. With advancing technology, the programmers and designers create complex GUI designs that work with more efficiency, accuracy and speed."
},
{
"code": null,
"e": 81759,
"s": 81687,
"text": "GUI provides a set of components to interact with software or hardware."
},
{
"code": null,
"e": 81870,
"s": 81759,
"text": "Every graphical component provides a way to work with the system. A GUI system has following elements such as:"
},
{
"code": null,
"e": 82315,
"s": 81870,
"text": "Window - An area where contents of application are displayed. Contents in a window can be displayed in the form of icons or lists, if the window represents file structure. It is easier for a user to navigate in the file system in an exploring window. Windows can be minimized, resized or maximized to the size of screen. They can be moved anywhere on the screen. A window may contain another window of the same application, called child window."
},
{
"code": null,
"e": 82760,
"s": 82315,
"text": "Window - An area where contents of application are displayed. Contents in a window can be displayed in the form of icons or lists, if the window represents file structure. It is easier for a user to navigate in the file system in an exploring window. Windows can be minimized, resized or maximized to the size of screen. They can be moved anywhere on the screen. A window may contain another window of the same application, called child window."
},
{
"code": null,
"e": 83076,
"s": 82760,
"text": "Tabs - If an application allows executing multiple instances of itself, they appear on the screen as separate windows. Tabbed Document Interface has come up to open multiple documents in the same window. This interface also helps in viewing preference panel in application. All modern web-browsers use this feature."
},
{
"code": null,
"e": 83392,
"s": 83076,
"text": "Tabs - If an application allows executing multiple instances of itself, they appear on the screen as separate windows. Tabbed Document Interface has come up to open multiple documents in the same window. This interface also helps in viewing preference panel in application. All modern web-browsers use this feature."
},
{
"code": null,
"e": 83592,
"s": 83392,
"text": "Menu - Menu is an array of standard commands, grouped together and placed at a visible place (usually top) inside the application window. The menu can be programmed to appear or hide on mouse clicks."
},
{
"code": null,
"e": 83792,
"s": 83592,
"text": "Menu - Menu is an array of standard commands, grouped together and placed at a visible place (usually top) inside the application window. The menu can be programmed to appear or hide on mouse clicks."
},
{
"code": null,
"e": 84038,
"s": 83792,
"text": "Icon - An icon is small picture representing an associated application. When these icons are clicked or double clicked, the application window is opened. Icon displays application and programs installed on a system in the form of small pictures."
},
{
"code": null,
"e": 84284,
"s": 84038,
"text": "Icon - An icon is small picture representing an associated application. When these icons are clicked or double clicked, the application window is opened. Icon displays application and programs installed on a system in the form of small pictures."
},
{
"code": null,
"e": 84582,
"s": 84284,
"text": "Cursor - Interacting devices such as mouse, touch pad, digital pen are represented in GUI as cursors. On screen cursor follows the instructions from hardware in almost real-time. Cursors are also named pointers in GUI systems. They are used to select menus, windows and other application features."
},
{
"code": null,
"e": 84880,
"s": 84582,
"text": "Cursor - Interacting devices such as mouse, touch pad, digital pen are represented in GUI as cursors. On screen cursor follows the instructions from hardware in almost real-time. Cursors are also named pointers in GUI systems. They are used to select menus, windows and other application features."
},
{
"code": null,
"e": 84953,
"s": 84880,
"text": "A GUI of an application contains one or more of the listed GUI elements:"
},
{
"code": null,
"e": 85137,
"s": 84953,
"text": "Application Window - Most application windows uses the constructs supplied by operating systems but many use their own customer created windows to contain the contents of application."
},
{
"code": null,
"e": 85321,
"s": 85137,
"text": "Application Window - Most application windows uses the constructs supplied by operating systems but many use their own customer created windows to contain the contents of application."
},
{
"code": null,
"e": 85528,
"s": 85321,
"text": "Dialogue Box - It is a child window that contains message for the user and request for some action to be taken. For Example: Application generate a dialogue to get confirmation from user to delete a file.\n"
},
{
"code": null,
"e": 85734,
"s": 85528,
"text": "Dialogue Box - It is a child window that contains message for the user and request for some action to be taken. For Example: Application generate a dialogue to get confirmation from user to delete a file."
},
{
"code": null,
"e": 85807,
"s": 85734,
"text": "Text-Box - Provides an area for user to type and enter text-based data."
},
{
"code": null,
"e": 85880,
"s": 85807,
"text": "Text-Box - Provides an area for user to type and enter text-based data."
},
{
"code": null,
"e": 85969,
"s": 85880,
"text": "Buttons - They imitate real life buttons and are used to submit inputs to the software.\n"
},
{
"code": null,
"e": 86057,
"s": 85969,
"text": "Buttons - They imitate real life buttons and are used to submit inputs to the software."
},
{
"code": null,
"e": 86158,
"s": 86057,
"text": "Radio-button - Displays available options for selection. Only one can be selected among all offered."
},
{
"code": null,
"e": 86259,
"s": 86158,
"text": "Radio-button - Displays available options for selection. Only one can be selected among all offered."
},
{
"code": null,
"e": 86421,
"s": 86259,
"text": "Check-box - Functions similar to list-box. When an option is selected, the box is marked as checked. Multiple options represented by check boxes can be selected."
},
{
"code": null,
"e": 86583,
"s": 86421,
"text": "Check-box - Functions similar to list-box. When an option is selected, the box is marked as checked. Multiple options represented by check boxes can be selected."
},
{
"code": null,
"e": 86680,
"s": 86583,
"text": "List-box - Provides list of available items for selection. More than one item can be selected.\n"
},
{
"code": null,
"e": 86776,
"s": 86680,
"text": "List-box - Provides list of available items for selection. More than one item can be selected."
},
{
"code": null,
"e": 86813,
"s": 86776,
"text": "Other impressive GUI components are:"
},
{
"code": null,
"e": 86821,
"s": 86813,
"text": "Sliders"
},
{
"code": null,
"e": 86831,
"s": 86821,
"text": "Combo-box"
},
{
"code": null,
"e": 86841,
"s": 86831,
"text": "Data-grid"
},
{
"code": null,
"e": 86856,
"s": 86841,
"text": "Drop-down list"
},
{
"code": null,
"e": 87078,
"s": 86856,
"text": "There are a number of activities performed for designing user interface. The process of GUI design and implementation is alike SDLC. Any model can be used for GUI implementation among Waterfall, Iterative or Spiral Model."
},
{
"code": null,
"e": 87163,
"s": 87078,
"text": "A model used for GUI design and development should fulfill these GUI specific steps."
},
{
"code": null,
"e": 87351,
"s": 87163,
"text": "GUI Requirement Gathering - The designers may like to have list of all functional and non-functional requirements of GUI. This can be taken from user and their existing software solution."
},
{
"code": null,
"e": 87539,
"s": 87351,
"text": "GUI Requirement Gathering - The designers may like to have list of all functional and non-functional requirements of GUI. This can be taken from user and their existing software solution."
},
{
"code": null,
"e": 87877,
"s": 87539,
"text": "User Analysis - The designer studies who is going to use the software GUI. The target audience matters as the design details change according to the knowledge and competency level of the user. If user is technical savvy, advanced and complex GUI can be incorporated. For a novice user, more information is included on how-to of software."
},
{
"code": null,
"e": 88215,
"s": 87877,
"text": "User Analysis - The designer studies who is going to use the software GUI. The target audience matters as the design details change according to the knowledge and competency level of the user. If user is technical savvy, advanced and complex GUI can be incorporated. For a novice user, more information is included on how-to of software."
},
{
"code": null,
"e": 88612,
"s": 88215,
"text": "Task Analysis - Designers have to analyze what task is to be done by the software solution. Here in GUI, it does not matter how it will be done. Tasks can be represented in hierarchical manner taking one major task and dividing it further into smaller sub-tasks. Tasks provide goals for GUI presentation. Flow of information among sub-tasks determines the flow of GUI contents in the software."
},
{
"code": null,
"e": 89009,
"s": 88612,
"text": "Task Analysis - Designers have to analyze what task is to be done by the software solution. Here in GUI, it does not matter how it will be done. Tasks can be represented in hierarchical manner taking one major task and dividing it further into smaller sub-tasks. Tasks provide goals for GUI presentation. Flow of information among sub-tasks determines the flow of GUI contents in the software."
},
{
"code": null,
"e": 89273,
"s": 89009,
"text": "GUI Design & implementation - Designers after having information about requirements, tasks and user environment, design the GUI and implements into code and embed the GUI with working or dummy software in the background. It is then self-tested by the developers."
},
{
"code": null,
"e": 89537,
"s": 89273,
"text": "GUI Design & implementation - Designers after having information about requirements, tasks and user environment, design the GUI and implements into code and embed the GUI with working or dummy software in the background. It is then self-tested by the developers."
},
{
"code": null,
"e": 89773,
"s": 89537,
"text": "Testing - GUI testing can be done in various ways. Organization can have in-house inspection, direct involvement of users and release of beta version are few of them. Testing may include usability, compatibility, user acceptance etc."
},
{
"code": null,
"e": 90009,
"s": 89773,
"text": "Testing - GUI testing can be done in various ways. Organization can have in-house inspection, direct involvement of users and release of beta version are few of them. Testing may include usability, compatibility, user acceptance etc."
},
{
"code": null,
"e": 90173,
"s": 90009,
"text": "There are several tools available using which the designers can create entire GUI on a mouse click. Some tools can be embedded into the software environment (IDE)."
},
{
"code": null,
"e": 90309,
"s": 90173,
"text": "GUI implementation tools provide powerful array of GUI controls. For software customization, designers can change the code accordingly."
},
{
"code": null,
"e": 90398,
"s": 90309,
"text": "There are different segments of GUI tools according to their different use and platform."
},
{
"code": null,
"e": 90505,
"s": 90398,
"text": "Mobile GUI, Computer GUI, Touch-Screen GUI etc. Here is a list of few tools which come handy to build GUI:"
},
{
"code": null,
"e": 90511,
"s": 90505,
"text": "FLUID"
},
{
"code": null,
"e": 90533,
"s": 90511,
"text": "AppInventor (Android)"
},
{
"code": null,
"e": 90544,
"s": 90533,
"text": "LucidChart"
},
{
"code": null,
"e": 90554,
"s": 90544,
"text": "Wavemaker"
},
{
"code": null,
"e": 90568,
"s": 90554,
"text": "Visual Studio"
},
{
"code": null,
"e": 90725,
"s": 90568,
"text": "The following rules are mentioned to be the golden rules for GUI design, described by Shneiderman and Plaisant in their book (Designing the User Interface)."
},
{
"code": null,
"e": 90949,
"s": 90725,
"text": "Strive for consistency - Consistent sequences of actions should be required in similar situations. Identical terminology should be used in prompts, menus, and help screens. Consistent commands should be employed throughout."
},
{
"code": null,
"e": 91173,
"s": 90949,
"text": "Strive for consistency - Consistent sequences of actions should be required in similar situations. Identical terminology should be used in prompts, menus, and help screens. Consistent commands should be employed throughout."
},
{
"code": null,
"e": 91412,
"s": 91173,
"text": "Enable frequent users to use short-cuts - The user’s desire to reduce the number of interactions increases with the frequency of use. Abbreviations, function keys, hidden commands, and macro facilities are very helpful to an expert user."
},
{
"code": null,
"e": 91651,
"s": 91412,
"text": "Enable frequent users to use short-cuts - The user’s desire to reduce the number of interactions increases with the frequency of use. Abbreviations, function keys, hidden commands, and macro facilities are very helpful to an expert user."
},
{
"code": null,
"e": 91885,
"s": 91651,
"text": "Offer informative feedback - For every operator action, there should be some system feedback. For frequent and minor actions, the response must be modest, while for infrequent and major actions, the response must be more substantial."
},
{
"code": null,
"e": 92119,
"s": 91885,
"text": "Offer informative feedback - For every operator action, there should be some system feedback. For frequent and minor actions, the response must be modest, while for infrequent and major actions, the response must be more substantial."
},
{
"code": null,
"e": 92537,
"s": 92119,
"text": "Design dialog to yield closure - Sequences of actions should be organized into groups with a beginning, middle, and end. The informative feedback at the completion of a group of actions gives the operators the satisfaction of accomplishment, a sense of relief, the signal to drop contingency plans and options from their minds, and this indicates that the way ahead is clear to prepare for the next group of actions."
},
{
"code": null,
"e": 92955,
"s": 92537,
"text": "Design dialog to yield closure - Sequences of actions should be organized into groups with a beginning, middle, and end. The informative feedback at the completion of a group of actions gives the operators the satisfaction of accomplishment, a sense of relief, the signal to drop contingency plans and options from their minds, and this indicates that the way ahead is clear to prepare for the next group of actions."
},
{
"code": null,
"e": 93196,
"s": 92955,
"text": "Offer simple error handling - As much as possible, design the system so the user will not make a serious error. If an error is made, the system should be able to detect it and offer simple, comprehensible mechanisms for handling the error."
},
{
"code": null,
"e": 93437,
"s": 93196,
"text": "Offer simple error handling - As much as possible, design the system so the user will not make a serious error. If an error is made, the system should be able to detect it and offer simple, comprehensible mechanisms for handling the error."
},
{
"code": null,
"e": 93719,
"s": 93437,
"text": "Permit easy reversal of actions - This feature relieves anxiety, since the user knows that errors can be undone. Easy reversal of actions encourages exploration of unfamiliar options. The units of reversibility may be a single action, a data entry, or a complete group of actions."
},
{
"code": null,
"e": 94001,
"s": 93719,
"text": "Permit easy reversal of actions - This feature relieves anxiety, since the user knows that errors can be undone. Easy reversal of actions encourages exploration of unfamiliar options. The units of reversibility may be a single action, a data entry, or a complete group of actions."
},
{
"code": null,
"e": 94256,
"s": 94001,
"text": "Support internal locus of control - Experienced operators strongly desire the sense that they are in charge of the system and that the system responds to their actions. Design the system to make users the initiators of actions rather than the responders."
},
{
"code": null,
"e": 94511,
"s": 94256,
"text": "Support internal locus of control - Experienced operators strongly desire the sense that they are in charge of the system and that the system responds to their actions. Design the system to make users the initiators of actions rather than the responders."
},
{
"code": null,
"e": 94819,
"s": 94511,
"text": "Reduce short-term memory load - The limitation of human information processing in short-term memory requires the displays to be kept simple, multiple page displays be consolidated, window-motion frequency be reduced, and sufficient training time be allotted for codes, mnemonics, and sequences of actions. "
},
{
"code": null,
"e": 95127,
"s": 94819,
"text": "Reduce short-term memory load - The limitation of human information processing in short-term memory requires the displays to be kept simple, multiple page displays be consolidated, window-motion frequency be reduced, and sufficient training time be allotted for codes, mnemonics, and sequences of actions. "
},
{
"code": null,
"e": 95456,
"s": 95127,
"text": "The term complexity stands for state of events or things, which have multiple interconnected links and highly complicated structures. In software programming, as the design of software is realized, the number of elements and their interconnections gradually emerge to be huge, which becomes too difficult to understand at once."
},
{
"code": null,
"e": 95611,
"s": 95456,
"text": "Software design complexity is difficult to assess without using complexity metrics and measures. Let us see three important software complexity measures."
},
{
"code": null,
"e": 95997,
"s": 95611,
"text": "In 1977, Mr. Maurice Howard Halstead introduced metrics to measure software complexity. Halstead’s metrics depends upon the actual implementation of program and its measures, which are computed directly from the operators and operands from source code, in static manner. It allows to evaluate testing time, vocabulary, size, difficulty, errors, and efforts for C/C++/Java source code."
},
{
"code": null,
"e": 96265,
"s": 95997,
"text": "According to Halstead, “A computer program is an implementation of an algorithm considered to be a collection of tokens which can be classified as either operators or operands”. Halstead metrics think a program as sequence of operators and their associated operands."
},
{
"code": null,
"e": 96326,
"s": 96265,
"text": "He defines various indicators to check complexity of module."
},
{
"code": null,
"e": 96449,
"s": 96326,
"text": "When we select source file to view its complexity details in Metric Viewer, the following result is seen in Metric Report:"
},
{
"code": null,
"e": 96680,
"s": 96449,
"text": "Every program encompasses statements to execute in order to perform some task and other decision-making statements that decide, what statements need to be executed. These decision-making constructs change the flow of the program. "
},
{
"code": null,
"e": 96831,
"s": 96680,
"text": "If we compare two programs of same size, the one with more decision-making statements will be more complex as the control of program jumps frequently."
},
{
"code": null,
"e": 97086,
"s": 96831,
"text": "McCabe, in 1976, proposed Cyclomatic Complexity Measure to quantify complexity of a given software. It is graph driven model that is based on decision-making constructs of program such as if-else, do-while, repeat-until, switch-case and goto statements."
},
{
"code": null,
"e": 97122,
"s": 97086,
"text": "Process to make flow control graph:"
},
{
"code": null,
"e": 97196,
"s": 97122,
"text": "Break program in smaller blocks, delimited by decision-making constructs."
},
{
"code": null,
"e": 97243,
"s": 97196,
"text": "Create nodes representing each of these nodes."
},
{
"code": null,
"e": 97270,
"s": 97243,
"text": "Connect nodes as follows: "
},
{
"code": null,
"e": 97328,
"s": 97270,
"text": "If control can branch from block i to block j\nDraw an arc"
},
{
"code": null,
"e": 97374,
"s": 97328,
"text": "If control can branch from block i to block j"
},
{
"code": null,
"e": 97386,
"s": 97374,
"text": "Draw an arc"
},
{
"code": null,
"e": 97428,
"s": 97386,
"text": "From exit node to entry node\nDraw an arc."
},
{
"code": null,
"e": 97457,
"s": 97428,
"text": "From exit node to entry node"
},
{
"code": null,
"e": 97470,
"s": 97457,
"text": "Draw an arc."
},
{
"code": null,
"e": 97547,
"s": 97470,
"text": "To calculate Cyclomatic complexity of a program module, we use the formula -"
},
{
"code": null,
"e": 97625,
"s": 97547,
"text": "V(G) = e – n + 2\n\nWhere\ne is total number of edges\nn is total number of nodes"
},
{
"code": null,
"e": 97674,
"s": 97625,
"text": "The Cyclomatic complexity of the above module is"
},
{
"code": null,
"e": 97748,
"s": 97674,
"text": "e = 10\nn = 8\nCyclomatic Complexity = 10 - 8 + 2\n = 4"
},
{
"code": null,
"e": 97831,
"s": 97748,
"text": "According to P. Jorgensen, Cyclomatic Complexity of a module should not exceed 10."
},
{
"code": null,
"e": 98039,
"s": 97831,
"text": "It is widely used to measure the size of software. Function Point concentrates on functionality provided by the system. Features and functionality of the system are used to measure the software complexity."
},
{
"code": null,
"e": 98306,
"s": 98039,
"text": "Function point counts on five parameters, named as External Input, External Output, Logical Internal Files, External Interface Files, and External Inquiry. To consider the complexity of software each parameter is further categorized as simple, average or complex. "
},
{
"code": null,
"e": 98347,
"s": 98306,
"text": "Let us see parameters of function point:"
},
{
"code": null,
"e": 98561,
"s": 98347,
"text": "Every unique input to the system, from outside, is considered as external input. Uniqueness of input is measured, as no two inputs should have same formats. These inputs can either be data or control parameters."
},
{
"code": null,
"e": 98624,
"s": 98561,
"text": "Simple - if input count is low and affects less internal files"
},
{
"code": null,
"e": 98687,
"s": 98624,
"text": "Simple - if input count is low and affects less internal files"
},
{
"code": null,
"e": 98752,
"s": 98687,
"text": "Complex - if input count is high and affects more internal files"
},
{
"code": null,
"e": 98817,
"s": 98752,
"text": "Complex - if input count is high and affects more internal files"
},
{
"code": null,
"e": 98858,
"s": 98817,
"text": "Average - in-between simple and complex."
},
{
"code": null,
"e": 98899,
"s": 98858,
"text": "Average - in-between simple and complex."
},
{
"code": null,
"e": 99051,
"s": 98899,
"text": " All output types provided by the system are counted in this category. Output is considered unique if their output format and/or processing are unique."
},
{
"code": null,
"e": 99083,
"s": 99051,
"text": "Simple - if output count is low"
},
{
"code": null,
"e": 99115,
"s": 99083,
"text": "Simple - if output count is low"
},
{
"code": null,
"e": 99149,
"s": 99115,
"text": "Complex - if output count is high"
},
{
"code": null,
"e": 99183,
"s": 99149,
"text": "Complex - if output count is high"
},
{
"code": null,
"e": 99224,
"s": 99183,
"text": "Average - in between simple and complex."
},
{
"code": null,
"e": 99265,
"s": 99224,
"text": "Average - in between simple and complex."
},
{
"code": null,
"e": 99502,
"s": 99265,
"text": " Every software system maintains internal files in order to maintain its functional information and to function properly. These files hold logical data of the system. This logical data may contain both functional data and control data."
},
{
"code": null,
"e": 99545,
"s": 99502,
"text": "Simple - if number of record types are low"
},
{
"code": null,
"e": 99588,
"s": 99545,
"text": "Simple - if number of record types are low"
},
{
"code": null,
"e": 99633,
"s": 99588,
"text": "Complex - if number of record types are high"
},
{
"code": null,
"e": 99678,
"s": 99633,
"text": "Complex - if number of record types are high"
},
{
"code": null,
"e": 99719,
"s": 99678,
"text": "Average - in between simple and complex."
},
{
"code": null,
"e": 99760,
"s": 99719,
"text": "Average - in between simple and complex."
},
{
"code": null,
"e": 99971,
"s": 99760,
"text": " Software system may need to share its files with some external software or it may need to pass the file for processing or as parameter to some function. All these files are counted as external interface files."
},
{
"code": null,
"e": 100029,
"s": 99971,
"text": "Simple - if number of record types in shared file are low"
},
{
"code": null,
"e": 100087,
"s": 100029,
"text": "Simple - if number of record types in shared file are low"
},
{
"code": null,
"e": 100147,
"s": 100087,
"text": "Complex - if number of record types in shared file are high"
},
{
"code": null,
"e": 100207,
"s": 100147,
"text": "Complex - if number of record types in shared file are high"
},
{
"code": null,
"e": 100248,
"s": 100207,
"text": "Average - in between simple and complex."
},
{
"code": null,
"e": 100289,
"s": 100248,
"text": "Average - in between simple and complex."
},
{
"code": null,
"e": 100634,
"s": 100289,
"text": " An inquiry is a combination of input and output, where user sends some data to inquire about as input and the system responds to the user with the output of inquiry processed. The complexity of a query is more than External Input and External Output. Query is said to be unique if its input and output are unique in terms of format and data."
},
{
"code": null,
"e": 100712,
"s": 100634,
"text": "Simple - if query needs low processing and yields small amount of output data"
},
{
"code": null,
"e": 100790,
"s": 100712,
"text": "Simple - if query needs low processing and yields small amount of output data"
},
{
"code": null,
"e": 100867,
"s": 100790,
"text": "Complex - if query needs high process and yields large amount of output data"
},
{
"code": null,
"e": 100944,
"s": 100867,
"text": "Complex - if query needs high process and yields large amount of output data"
},
{
"code": null,
"e": 100985,
"s": 100944,
"text": "Average - in between simple and complex."
},
{
"code": null,
"e": 101026,
"s": 100985,
"text": "Average - in between simple and complex."
},
{
"code": null,
"e": 101190,
"s": 101026,
"text": "Each of these parameters in the system is given weightage according to their class and complexity. The table below mentions the weightage given to each parameter:"
},
{
"code": null,
"e": 101374,
"s": 101190,
"text": "The table above yields raw Function Points. These function points are adjusted according to the environment complexity. System is described using fourteen different characteristics:"
},
{
"code": null,
"e": 101394,
"s": 101374,
"text": "Data communications"
},
{
"code": null,
"e": 101417,
"s": 101394,
"text": "Distributed processing"
},
{
"code": null,
"e": 101440,
"s": 101417,
"text": "Performance objectives"
},
{
"code": null,
"e": 101469,
"s": 101440,
"text": "Operation configuration load"
},
{
"code": null,
"e": 101486,
"s": 101469,
"text": "Transaction rate"
},
{
"code": null,
"e": 101505,
"s": 101486,
"text": "Online data entry,"
},
{
"code": null,
"e": 101525,
"s": 101505,
"text": "End user efficiency"
},
{
"code": null,
"e": 101539,
"s": 101525,
"text": "Online update"
},
{
"code": null,
"e": 101564,
"s": 101539,
"text": "Complex processing logic"
},
{
"code": null,
"e": 101577,
"s": 101564,
"text": "Re-usability"
},
{
"code": null,
"e": 101595,
"s": 101577,
"text": "Installation ease"
},
{
"code": null,
"e": 101612,
"s": 101595,
"text": "Operational ease"
},
{
"code": null,
"e": 101627,
"s": 101612,
"text": "Multiple sites"
},
{
"code": null,
"e": 101656,
"s": 101627,
"text": "Desire to facilitate changes"
},
{
"code": null,
"e": 101734,
"s": 101656,
"text": "These characteristics factors are then rated from 0 to 5, as mentioned below:"
},
{
"code": null,
"e": 101747,
"s": 101734,
"text": "No influence"
},
{
"code": null,
"e": 101758,
"s": 101747,
"text": "Incidental"
},
{
"code": null,
"e": 101767,
"s": 101758,
"text": "Moderate"
},
{
"code": null,
"e": 101775,
"s": 101767,
"text": "Average"
},
{
"code": null,
"e": 101787,
"s": 101775,
"text": "Significant"
},
{
"code": null,
"e": 101797,
"s": 101787,
"text": "Essential"
},
{
"code": null,
"e": 102013,
"s": 101797,
"text": "All ratings are then summed up as N. The value of N ranges from 0 to 70 (14 types of characteristics x 5 types of ratings). It is used to calculate Complexity Adjustment Factors (CAF), using the following formulae:"
},
{
"code": null,
"e": 102032,
"s": 102013,
"text": "CAF = 0.65 + 0.01N"
},
{
"code": null,
"e": 102038,
"s": 102032,
"text": "Then,"
},
{
"code": null,
"e": 102083,
"s": 102038,
"text": "Delivered Function Points (FP)= CAF x Raw FP"
},
{
"code": null,
"e": 102137,
"s": 102083,
"text": "This FP can then be used in various metrics, such as:"
},
{
"code": null,
"e": 102151,
"s": 102137,
"text": "Cost = $ / FP"
},
{
"code": null,
"e": 102173,
"s": 102151,
"text": "Quality = Errors / FP"
},
{
"code": null,
"e": 102206,
"s": 102173,
"text": "Productivity = FP / person-month"
},
{
"code": null,
"e": 102321,
"s": 102206,
"text": "In this chapter, we will study about programming methods, documentation and challenges in software implementation."
},
{
"code": null,
"e": 102966,
"s": 102321,
"text": "In the process of coding, the lines of code keep multiplying, thus, size of the software increases. Gradually, it becomes next to impossible to remember the flow of program. If one forgets how software and its underlying programs, files, procedures are constructed it then becomes very difficult to share, debug and modify the program. The solution to this is structured programming. It encourages the developer to use subroutines and loops instead of using simple jumps in the code, thereby bringing clarity in the code and improving its efficiency Structured programming also helps programmer to reduce coding time and organize code properly."
},
{
"code": null,
"e": 103078,
"s": 102966,
"text": "Structured programming states how the program shall be coded. Structured programming uses three main concepts:"
},
{
"code": null,
"e": 103496,
"s": 103078,
"text": "Top-down analysis - A software is always made to perform some rational work. This rational work is known as problem in the software parlance. Thus it is very important that we understand how to solve the problem. Under top-down analysis, the problem is broken down into small pieces where each one has some significance. Each problem is individually solved and steps are clearly stated about how to solve the problem."
},
{
"code": null,
"e": 103914,
"s": 103496,
"text": "Top-down analysis - A software is always made to perform some rational work. This rational work is known as problem in the software parlance. Thus it is very important that we understand how to solve the problem. Under top-down analysis, the problem is broken down into small pieces where each one has some significance. Each problem is individually solved and steps are clearly stated about how to solve the problem."
},
{
"code": null,
"e": 104340,
"s": 103914,
"text": "Modular Programming - While programming, the code is broken down into smaller group of instructions. These groups are known as modules, subprograms or subroutines. Modular programming based on the understanding of top-down analysis. It discourages jumps using ‘goto’ statements in the program, which often makes the program flow non-traceable. Jumps are prohibited and modular format is encouraged in structured programming. "
},
{
"code": null,
"e": 104766,
"s": 104340,
"text": "Modular Programming - While programming, the code is broken down into smaller group of instructions. These groups are known as modules, subprograms or subroutines. Modular programming based on the understanding of top-down analysis. It discourages jumps using ‘goto’ statements in the program, which often makes the program flow non-traceable. Jumps are prohibited and modular format is encouraged in structured programming. "
},
{
"code": null,
"e": 105122,
"s": 104766,
"text": "Structured Coding - In reference with top-down analysis, structured coding sub-divides the modules into further smaller units of code in the order of their execution. Structured programming uses control structure, which controls the flow of the program, whereas structured coding uses control structure to organize its instructions in definable patterns."
},
{
"code": null,
"e": 105478,
"s": 105122,
"text": "Structured Coding - In reference with top-down analysis, structured coding sub-divides the modules into further smaller units of code in the order of their execution. Structured programming uses control structure, which controls the flow of the program, whereas structured coding uses control structure to organize its instructions in definable patterns."
},
{
"code": null,
"e": 105921,
"s": 105478,
"text": "Functional programming is style of programming language, which uses the concepts of mathematical functions. A function in mathematics should always produce the same result on receiving the same argument. In procedural languages, the flow of the program runs through procedures, i.e. the control of program is transferred to the called procedure. While control flow is transferring from one procedure to another, the program changes its state."
},
{
"code": null,
"e": 106262,
"s": 105921,
"text": "In procedural programming, it is possible for a procedure to produce different results when it is called with the same argument, as the program itself can be in different state while calling it. This is a property as well as a drawback of procedural programming, in which the sequence or timing of the procedure execution becomes important."
},
{
"code": null,
"e": 106459,
"s": 106262,
"text": "Functional programming provides means of computation as mathematical functions, which produces results irrespective of program state. This makes it possible to predict the behavior of the program."
},
{
"code": null,
"e": 106511,
"s": 106459,
"text": "Functional programming uses the following concepts:"
},
{
"code": null,
"e": 106664,
"s": 106511,
"text": "First class and High-order functions - These functions have capability to accept another function as argument or they return other functions as results."
},
{
"code": null,
"e": 106817,
"s": 106664,
"text": "First class and High-order functions - These functions have capability to accept another function as argument or they return other functions as results."
},
{
"code": null,
"e": 107030,
"s": 106817,
"text": "Pure functions - These functions do not include destructive updates, that is, they do not affect any I/O or memory and if they are not in use, they can easily be removed without hampering the rest of the program."
},
{
"code": null,
"e": 107243,
"s": 107030,
"text": "Pure functions - These functions do not include destructive updates, that is, they do not affect any I/O or memory and if they are not in use, they can easily be removed without hampering the rest of the program."
},
{
"code": null,
"e": 107466,
"s": 107243,
"text": "Recursion - Recursion is a programming technique where a function calls itself and repeats the program code in it unless some pre-defined condition matches. Recursion is the way of creating loops in functional programming."
},
{
"code": null,
"e": 107689,
"s": 107466,
"text": "Recursion - Recursion is a programming technique where a function calls itself and repeats the program code in it unless some pre-defined condition matches. Recursion is the way of creating loops in functional programming."
},
{
"code": null,
"e": 108043,
"s": 107689,
"text": "Strict evaluation - It is a method of evaluating the expression passed to a function as an argument. Functional programming has two types of evaluation methods, strict (eager) or non-strict (lazy). Strict evaluation always evaluates the expression before invoking the function. Non-strict evaluation does not evaluate the expression unless it is needed."
},
{
"code": null,
"e": 108397,
"s": 108043,
"text": "Strict evaluation - It is a method of evaluating the expression passed to a function as an argument. Functional programming has two types of evaluation methods, strict (eager) or non-strict (lazy). Strict evaluation always evaluates the expression before invoking the function. Non-strict evaluation does not evaluate the expression unless it is needed."
},
{
"code": null,
"e": 108547,
"s": 108397,
"text": "λ-calculus - Most functional programming languages use λ-calculus as their type systems. λ-expressions are executed by evaluating them as they occur."
},
{
"code": null,
"e": 108697,
"s": 108547,
"text": "λ-calculus - Most functional programming languages use λ-calculus as their type systems. λ-expressions are executed by evaluating them as they occur."
},
{
"code": null,
"e": 108795,
"s": 108697,
"text": "Common Lisp, Scala, Haskell, Erlang and F# are some examples of functional programming languages."
},
{
"code": null,
"e": 109163,
"s": 108795,
"text": "Programming style is set of coding rules followed by all the programmers to write the code. When multiple programmers work on the same software project, they frequently need to work with the program code written by some other developer. This becomes tedious or at times impossible, if all developers do not follow some standard programming style to code the program. "
},
{
"code": null,
"e": 109570,
"s": 109163,
"text": "An appropriate programming style includes using function and variable names relevant to the intended task, using well-placed indentation, commenting code for the convenience of reader and overall presentation of code. This makes the program code readable and understandable by all, which in turn makes debugging and error solving easier. Also, proper coding style helps ease the documentation and updation."
},
{
"code": null,
"e": 109672,
"s": 109570,
"text": "Practice of coding style varies with organizations, operating systems and language of coding itself. "
},
{
"code": null,
"e": 109761,
"s": 109672,
"text": "The following coding elements may be defined under coding guidelines of an organization:"
},
{
"code": null,
"e": 109869,
"s": 109761,
"text": "Naming conventions - This section defines how to name functions, variables, constants and global variables."
},
{
"code": null,
"e": 109977,
"s": 109869,
"text": "Naming conventions - This section defines how to name functions, variables, constants and global variables."
},
{
"code": null,
"e": 110076,
"s": 109977,
"text": "Indenting - This is the space left at the beginning of line, usually 2-8 whitespace or single tab."
},
{
"code": null,
"e": 110175,
"s": 110076,
"text": "Indenting - This is the space left at the beginning of line, usually 2-8 whitespace or single tab."
},
{
"code": null,
"e": 110232,
"s": 110175,
"text": "Whitespace - It is generally omitted at the end of line."
},
{
"code": null,
"e": 110289,
"s": 110232,
"text": "Whitespace - It is generally omitted at the end of line."
},
{
"code": null,
"e": 110469,
"s": 110289,
"text": "Operators - Defines the rules of writing mathematical, assignment and logical operators. For example, assignment operator ‘=’ should have space before and after it, as in “x = 2”."
},
{
"code": null,
"e": 110649,
"s": 110469,
"text": "Operators - Defines the rules of writing mathematical, assignment and logical operators. For example, assignment operator ‘=’ should have space before and after it, as in “x = 2”."
},
{
"code": null,
"e": 110792,
"s": 110649,
"text": "Control Structures - The rules of writing if-then-else, case-switch, while-until and for control flow statements solely and in nested fashion."
},
{
"code": null,
"e": 110935,
"s": 110792,
"text": "Control Structures - The rules of writing if-then-else, case-switch, while-until and for control flow statements solely and in nested fashion."
},
{
"code": null,
"e": 111119,
"s": 110935,
"text": "Line length and wrapping - Defines how many characters should be there in one line, mostly a line is 80 characters long. Wrapping defines how a line should be wrapped, if is too long."
},
{
"code": null,
"e": 111303,
"s": 111119,
"text": "Line length and wrapping - Defines how many characters should be there in one line, mostly a line is 80 characters long. Wrapping defines how a line should be wrapped, if is too long."
},
{
"code": null,
"e": 111403,
"s": 111303,
"text": "Functions - This defines how functions should be declared and invoked, with and without parameters."
},
{
"code": null,
"e": 111503,
"s": 111403,
"text": "Functions - This defines how functions should be declared and invoked, with and without parameters."
},
{
"code": null,
"e": 111593,
"s": 111503,
"text": "Variables - This mentions how variables of different data types are declared and defined."
},
{
"code": null,
"e": 111683,
"s": 111593,
"text": "Variables - This mentions how variables of different data types are declared and defined."
},
{
"code": null,
"e": 111930,
"s": 111683,
"text": "Comments - This is one of the important coding components, as the comments included in the code describe what the code actually does and all other associated descriptions. This section also helps creating help documentations for other developers."
},
{
"code": null,
"e": 112177,
"s": 111930,
"text": "Comments - This is one of the important coding components, as the comments included in the code describe what the code actually does and all other associated descriptions. This section also helps creating help documentations for other developers."
},
{
"code": null,
"e": 112445,
"s": 112177,
"text": "Software documentation is an important part of software process. A well written document provides a great tool and means of information repository necessary to know about software process. Software documentation also provides information about how to use the product."
},
{
"code": null,
"e": 112517,
"s": 112445,
"text": "A well-maintained documentation should involve the following documents:"
},
{
"code": null,
"e": 113273,
"s": 112517,
"text": "Requirement documentation - This documentation works as key tool for software designer, developer and the test team to carry out their respective tasks. This document contains all the functional, non-functional and behavioral description of the intended software. \nSource of this document can be previously stored data about the software, already running software at the client’s end, client’s interview, questionnaires and research. Generally it is stored in the form of spreadsheet or word processing document with the high-end software management team.\nThis documentation works as foundation for the software to be developed and is majorly used in verification and validation phases. Most test-cases are built directly from requirement documentation."
},
{
"code": null,
"e": 113540,
"s": 113273,
"text": "Requirement documentation - This documentation works as key tool for software designer, developer and the test team to carry out their respective tasks. This document contains all the functional, non-functional and behavioral description of the intended software. "
},
{
"code": null,
"e": 113831,
"s": 113540,
"text": "Source of this document can be previously stored data about the software, already running software at the client’s end, client’s interview, questionnaires and research. Generally it is stored in the form of spreadsheet or word processing document with the high-end software management team."
},
{
"code": null,
"e": 114029,
"s": 113831,
"text": "This documentation works as foundation for the software to be developed and is majorly used in verification and validation phases. Most test-cases are built directly from requirement documentation."
},
{
"code": null,
"e": 114523,
"s": 114029,
"text": "Software Design documentation - These documentations contain all the necessary information, which are needed to build the software. It contains: (a) High-level software architecture, (b) Software design details, (c) Data flow diagrams, (d) Database design\nThese documents work as repository for developers to implement the software. Though these documents do not give any details on how to code the program, they give all necessary information that is required for coding and implementation. "
},
{
"code": null,
"e": 114780,
"s": 114523,
"text": "Software Design documentation - These documentations contain all the necessary information, which are needed to build the software. It contains: (a) High-level software architecture, (b) Software design details, (c) Data flow diagrams, (d) Database design"
},
{
"code": null,
"e": 115017,
"s": 114780,
"text": "These documents work as repository for developers to implement the software. Though these documents do not give any details on how to code the program, they give all necessary information that is required for coding and implementation. "
},
{
"code": null,
"e": 115741,
"s": 115017,
"text": "Technical documentation - These documentations are maintained by the developers and actual coders. These documents, as a whole, represent information about the code. While writing the code, the programmers also mention objective of the code, who wrote it, where will it be required, what it does and how it does, what other resources the code uses, etc.\nThe technical documentation increases the understanding between various programmers working on the same code. It enhances re-use capability of the code. It makes debugging easy and traceable.\nThere are various automated tools available and some comes with the programming language itself. For example java comes JavaDoc tool to generate technical documentation of code."
},
{
"code": null,
"e": 116095,
"s": 115741,
"text": "Technical documentation - These documentations are maintained by the developers and actual coders. These documents, as a whole, represent information about the code. While writing the code, the programmers also mention objective of the code, who wrote it, where will it be required, what it does and how it does, what other resources the code uses, etc."
},
{
"code": null,
"e": 116287,
"s": 116095,
"text": "The technical documentation increases the understanding between various programmers working on the same code. It enhances re-use capability of the code. It makes debugging easy and traceable."
},
{
"code": null,
"e": 116465,
"s": 116287,
"text": "There are various automated tools available and some comes with the programming language itself. For example java comes JavaDoc tool to generate technical documentation of code."
},
{
"code": null,
"e": 116977,
"s": 116465,
"text": "User documentation - This documentation is different from all the above explained. All previous documentations are maintained to provide information about the software and its development process. But user documentation explains how the software product should work and how it should be used to get the desired results.\nThese documentations may include, software installation procedures, how-to guides, user-guides, uninstallation method and special references to get more information like license updation etc."
},
{
"code": null,
"e": 117297,
"s": 116977,
"text": "User documentation - This documentation is different from all the above explained. All previous documentations are maintained to provide information about the software and its development process. But user documentation explains how the software product should work and how it should be used to get the desired results."
},
{
"code": null,
"e": 117489,
"s": 117297,
"text": "These documentations may include, software installation procedures, how-to guides, user-guides, uninstallation method and special references to get more information like license updation etc."
},
{
"code": null,
"e": 117612,
"s": 117489,
"text": "There are some challenges faced by the development team while implementing the software. Some of them are mentioned below:"
},
{
"code": null,
"e": 117996,
"s": 117612,
"text": "Code-reuse - Programming interfaces of present-day languages are very sophisticated and are equipped huge library functions. Still, to bring the cost down of end product, the organization management prefers to re-use the code, which was created earlier for some other software. There are huge issues faced by programmers for compatibility checks and deciding how much code to re-use."
},
{
"code": null,
"e": 118380,
"s": 117996,
"text": "Code-reuse - Programming interfaces of present-day languages are very sophisticated and are equipped huge library functions. Still, to bring the cost down of end product, the organization management prefers to re-use the code, which was created earlier for some other software. There are huge issues faced by programmers for compatibility checks and deciding how much code to re-use."
},
{
"code": null,
"e": 118601,
"s": 118380,
"text": "Version Management - Every time a new software is issued to the customer, developers have to maintain version and configuration related documentation. This documentation needs to be highly accurate and available on time."
},
{
"code": null,
"e": 118822,
"s": 118601,
"text": "Version Management - Every time a new software is issued to the customer, developers have to maintain version and configuration related documentation. This documentation needs to be highly accurate and available on time."
},
{
"code": null,
"e": 119052,
"s": 118822,
"text": "Target-Host - The software program, which is being developed in the organization, needs to be designed for host machines at the customers end. But at times, it is impossible to design a software that works on the target machines."
},
{
"code": null,
"e": 119282,
"s": 119052,
"text": "Target-Host - The software program, which is being developed in the organization, needs to be designed for host machines at the customers end. But at times, it is impossible to design a software that works on the target machines."
},
{
"code": null,
"e": 119567,
"s": 119282,
"text": "Software Testing is evaluation of the software against requirements gathered from users and system specifications. Testing is conducted at the phase level in software development life cycle or at module level in program code. Software testing comprises of Validation and Verification."
},
{
"code": null,
"e": 119782,
"s": 119567,
"text": "Validation is process of examining whether or not the software satisfies the user requirements. It is carried out at the end of the SDLC. If the software matches requirements for which it was made, it is validated."
},
{
"code": null,
"e": 119864,
"s": 119782,
"text": "Validation ensures the product under development is as per the user requirements."
},
{
"code": null,
"e": 119987,
"s": 119864,
"text": "Validation answers the question – \"Are we developing the product which attempts all that user needs from this software ?\"."
},
{
"code": null,
"e": 120031,
"s": 119987,
"text": "Validation emphasizes on user requirements."
},
{
"code": null,
"e": 120202,
"s": 120031,
"text": "Verification is the process of confirming if the software is meeting the business requirements, and is developed adhering to the proper specifications and methodologies. "
},
{
"code": null,
"e": 120290,
"s": 120202,
"text": "Verification ensures the product being developed is according to design specifications."
},
{
"code": null,
"e": 120406,
"s": 120290,
"text": "Verification answers the question– \"Are we developing this product by firmly following all design specifications ?\""
},
{
"code": null,
"e": 120474,
"s": 120406,
"text": "Verifications concentrates on the design and system specifications."
},
{
"code": null,
"e": 120500,
"s": 120474,
"text": "Target of the test are - "
},
{
"code": null,
"e": 120666,
"s": 120500,
"text": "Errors - These are actual coding mistakes made by developers. In addition, there is a difference in output of software and desired output, is considered as an error."
},
{
"code": null,
"e": 120832,
"s": 120666,
"text": "Errors - These are actual coding mistakes made by developers. In addition, there is a difference in output of software and desired output, is considered as an error."
},
{
"code": null,
"e": 120958,
"s": 120832,
"text": "Fault - When error exists fault occurs. A fault, also known as a bug, is a result of an error which can cause system to fail."
},
{
"code": null,
"e": 121084,
"s": 120958,
"text": "Fault - When error exists fault occurs. A fault, also known as a bug, is a result of an error which can cause system to fail."
},
{
"code": null,
"e": 121223,
"s": 121084,
"text": "Failure - failure is said to be the inability of the system to perform the desired task. Failure occurs when fault exists in the system."
},
{
"code": null,
"e": 121362,
"s": 121223,
"text": "Failure - failure is said to be the inability of the system to perform the desired task. Failure occurs when fault exists in the system."
},
{
"code": null,
"e": 121434,
"s": 121362,
"text": "Testing can either be done manually or using an automated testing tool:"
},
{
"code": null,
"e": 121830,
"s": 121434,
"text": "Manual - This testing is performed without taking help of automated testing tools. The software tester prepares test cases for different sections and levels of the code, executes the tests and reports the result to the manager. \nManual testing is time and resource consuming. The tester needs to confirm whether or not right test cases are used. Major portion of testing involves manual testing."
},
{
"code": null,
"e": 122059,
"s": 121830,
"text": "Manual - This testing is performed without taking help of automated testing tools. The software tester prepares test cases for different sections and levels of the code, executes the tests and reports the result to the manager. "
},
{
"code": null,
"e": 122226,
"s": 122059,
"text": "Manual testing is time and resource consuming. The tester needs to confirm whether or not right test cases are used. Major portion of testing involves manual testing."
},
{
"code": null,
"e": 122394,
"s": 122226,
"text": "Automated This testing is a testing procedure done with aid of automated testing tools. The limitations with manual testing can be overcome using automated test tools."
},
{
"code": null,
"e": 122562,
"s": 122394,
"text": "Automated This testing is a testing procedure done with aid of automated testing tools. The limitations with manual testing can be overcome using automated test tools."
},
{
"code": null,
"e": 122789,
"s": 122562,
"text": "A test needs to check if a webpage can be opened in Internet Explorer. This can be easily done with manual testing. But to check if the web-server can take the load of 1 million users, it is quite impossible to test manually. "
},
{
"code": null,
"e": 122910,
"s": 122789,
"text": "There are software and hardware tools which helps tester in conducting load testing, stress testing, regression testing."
},
{
"code": null,
"e": 122960,
"s": 122910,
"text": "Tests can be conducted based on two approaches – "
},
{
"code": null,
"e": 122983,
"s": 122960,
"text": "Functionality testing "
},
{
"code": null,
"e": 123006,
"s": 122983,
"text": "Implementation testing"
},
{
"code": null,
"e": 123260,
"s": 123006,
"text": "When functionality is being tested without taking the actual implementation in concern it is known as black-box testing. The other side is known as white-box testing where not only functionality is tested but the way it is implemented is also analyzed."
},
{
"code": null,
"e": 123515,
"s": 123260,
"text": "Exhaustive tests are the best-desired method for a perfect testing. Every single possible value in the range of the input and output values is tested. It is not possible to test each and every value in real world scenario if the range of values is large."
},
{
"code": null,
"e": 123818,
"s": 123515,
"text": "It is carried out to test functionality of the program. It is also called ‘Behavioral’ testing. The tester in this case, has a set of input values and respective desired results. On providing input, if the output matches with the desired results, the program is tested ‘ok’, and problematic otherwise. "
},
{
"code": null,
"e": 123979,
"s": 123818,
"text": "In this testing method, the design and structure of the code are not known to the tester, and testing engineers and end users conduct this test on the software."
},
{
"code": null,
"e": 124009,
"s": 123979,
"text": "Black-box testing techniques:"
},
{
"code": null,
"e": 124160,
"s": 124009,
"text": "Equivalence class - The input is divided into similar classes. If one element of a class passes the test, it is assumed that all the class is passed."
},
{
"code": null,
"e": 124311,
"s": 124160,
"text": "Equivalence class - The input is divided into similar classes. If one element of a class passes the test, it is assumed that all the class is passed."
},
{
"code": null,
"e": 124471,
"s": 124311,
"text": "Boundary values - The input is divided into higher and lower end values. If these values pass the test, it is assumed that all values in between may pass too."
},
{
"code": null,
"e": 124631,
"s": 124471,
"text": "Boundary values - The input is divided into higher and lower end values. If these values pass the test, it is assumed that all values in between may pass too."
},
{
"code": null,
"e": 124845,
"s": 124631,
"text": "Cause-effect graphing - In both previous methods, only one input value at a time is tested. Cause (input) – Effect (output) is a testing technique where combinations of input values are tested in a systematic way."
},
{
"code": null,
"e": 125059,
"s": 124845,
"text": "Cause-effect graphing - In both previous methods, only one input value at a time is tested. Cause (input) – Effect (output) is a testing technique where combinations of input values are tested in a systematic way."
},
{
"code": null,
"e": 125230,
"s": 125059,
"text": "Pair-wise Testing - The behavior of software depends on multiple parameters. In pairwise testing, the multiple parameters are tested pair-wise for their different values."
},
{
"code": null,
"e": 125401,
"s": 125230,
"text": "Pair-wise Testing - The behavior of software depends on multiple parameters. In pairwise testing, the multiple parameters are tested pair-wise for their different values."
},
{
"code": null,
"e": 125529,
"s": 125401,
"text": "State-based testing - The system changes state on provision of input. These systems are tested based on their states and input."
},
{
"code": null,
"e": 125657,
"s": 125529,
"text": "State-based testing - The system changes state on provision of input. These systems are tested based on their states and input."
},
{
"code": null,
"e": 125806,
"s": 125657,
"text": " It is conducted to test program and its implementation, in order to improve code efficiency or structure. It is also known as ‘Structural’ testing."
},
{
"code": null,
"e": 125947,
"s": 125806,
"text": "In this testing method, the design and structure of the code are known to the tester. Programmers of the code conduct this test on the code."
},
{
"code": null,
"e": 125996,
"s": 125947,
"text": "The below are some White-box testing techniques:"
},
{
"code": null,
"e": 126235,
"s": 125996,
"text": "Control-flow testing - The purpose of the control-flow testing to set up test cases which covers all statements and branch conditions. The branch conditions are tested for both being true and false, so that all statements can be covered."
},
{
"code": null,
"e": 126474,
"s": 126235,
"text": "Control-flow testing - The purpose of the control-flow testing to set up test cases which covers all statements and branch conditions. The branch conditions are tested for both being true and false, so that all statements can be covered."
},
{
"code": null,
"e": 126676,
"s": 126474,
"text": "Data-flow testing - This testing technique emphasis to cover all the data variables included in the program. It tests where the variables were declared and defined and where they were used or changed."
},
{
"code": null,
"e": 126878,
"s": 126676,
"text": "Data-flow testing - This testing technique emphasis to cover all the data variables included in the program. It tests where the variables were declared and defined and where they were used or changed."
},
{
"code": null,
"e": 127071,
"s": 126878,
"text": "Testing itself may be defined at various levels of SDLC. The testing process runs parallel to software development. Before jumping on the next stage, a stage is tested, validated and verified."
},
{
"code": null,
"e": 127218,
"s": 127071,
"text": "Testing separately is done just to make sure that there are no hidden bugs or issues left in the software. Software is tested on various levels -"
},
{
"code": null,
"e": 127502,
"s": 127218,
"text": " While coding, the programmer performs some tests on that unit of program to know if it is error free. Testing is performed under white-box testing approach. Unit testing helps developers decide that individual units of the program are working as per requirement and are error free."
},
{
"code": null,
"e": 127712,
"s": 127502,
"text": "Even if the units of software are working fine individually, there is a need to find out if the units if integrated together would also work without errors. For example, argument passing and data updation etc."
},
{
"code": null,
"e": 127850,
"s": 127712,
"text": "The software is compiled as product and then it is tested as a whole. This can be accomplished using one or more of the following tests:"
},
{
"code": null,
"e": 127941,
"s": 127850,
"text": "Functionality testing - Tests all functionalities of the software against the requirement."
},
{
"code": null,
"e": 128032,
"s": 127941,
"text": "Functionality testing - Tests all functionalities of the software against the requirement."
},
{
"code": null,
"e": 128356,
"s": 128032,
"text": "Performance testing - This test proves how efficient the software is. It tests the effectiveness and average time taken by the software to do desired task. Performance testing is done by means of load testing and stress testing where the software is put under high user and data load under various environment conditions."
},
{
"code": null,
"e": 128680,
"s": 128356,
"text": "Performance testing - This test proves how efficient the software is. It tests the effectiveness and average time taken by the software to do desired task. Performance testing is done by means of load testing and stress testing where the software is put under high user and data load under various environment conditions."
},
{
"code": null,
"e": 128817,
"s": 128680,
"text": "Security & Portability - These tests are done when the software is meant to work on various platforms and accessed by number of persons."
},
{
"code": null,
"e": 128954,
"s": 128817,
"text": "Security & Portability - These tests are done when the software is meant to work on various platforms and accessed by number of persons."
},
{
"code": null,
"e": 129261,
"s": 128954,
"text": " When the software is ready to hand over to the customer it has to go through last phase of testing where it is tested for user-interaction and response. This is important because even if the software matches all user requirements and if user does not like the way it appears or works, it may be rejected."
},
{
"code": null,
"e": 129510,
"s": 129261,
"text": "Alpha testing - The team of developer themselves perform alpha testing by using the system as if it is being used in work environment. They try to find out how user would react to some action in software and how the system should respond to inputs."
},
{
"code": null,
"e": 129759,
"s": 129510,
"text": "Alpha testing - The team of developer themselves perform alpha testing by using the system as if it is being used in work environment. They try to find out how user would react to some action in software and how the system should respond to inputs."
},
{
"code": null,
"e": 130060,
"s": 129759,
"text": "Beta testing - After the software is tested internally, it is handed over to the users to use it under their production environment only for testing purpose. This is not as yet the delivered product. Developers expect that users at this stage will bring minute problems, which were skipped to attend."
},
{
"code": null,
"e": 130361,
"s": 130060,
"text": "Beta testing - After the software is tested internally, it is handed over to the users to use it under their production environment only for testing purpose. This is not as yet the delivered product. Developers expect that users at this stage will bring minute problems, which were skipped to attend."
},
{
"code": null,
"e": 130563,
"s": 130361,
"text": "Whenever a software product is updated with new code, feature or functionality, it is tested thoroughly to detect if there is any negative impact of the added code. This is known as regression testing."
},
{
"code": null,
"e": 130616,
"s": 130563,
"text": "Testing documents are prepared at different stages -"
},
{
"code": null,
"e": 130706,
"s": 130616,
"text": "Testing starts with test cases generation. Following documents are needed for reference –"
},
{
"code": null,
"e": 130754,
"s": 130706,
"text": "SRS document - Functional Requirements document"
},
{
"code": null,
"e": 130802,
"s": 130754,
"text": "SRS document - Functional Requirements document"
},
{
"code": null,
"e": 130904,
"s": 130802,
"text": "Test Policy document - This describes how far testing should take place before releasing the product."
},
{
"code": null,
"e": 131006,
"s": 130904,
"text": "Test Policy document - This describes how far testing should take place before releasing the product."
},
{
"code": null,
"e": 131157,
"s": 131006,
"text": "Test Strategy document - This mentions detail aspects of test team, responsibility matrix and rights/responsibility of test manager and test engineer."
},
{
"code": null,
"e": 131308,
"s": 131157,
"text": "Test Strategy document - This mentions detail aspects of test team, responsibility matrix and rights/responsibility of test manager and test engineer."
},
{
"code": null,
"e": 131572,
"s": 131308,
"text": "Traceability Matrix document - This is SDLC document, which is related to requirement gathering process. As new requirements come, they are added to this matrix. These matrices help testers know the source of requirement. They can be traced forward and backward."
},
{
"code": null,
"e": 131836,
"s": 131572,
"text": "Traceability Matrix document - This is SDLC document, which is related to requirement gathering process. As new requirements come, they are added to this matrix. These matrices help testers know the source of requirement. They can be traced forward and backward."
},
{
"code": null,
"e": 131920,
"s": 131836,
"text": "The following documents may be required while testing is started and is being done:"
},
{
"code": null,
"e": 132099,
"s": 131920,
"text": "Test Case document - This document contains list of tests required to be conducted. It includes Unit test plan, Integration test plan, System test plan and Acceptance test plan."
},
{
"code": null,
"e": 132278,
"s": 132099,
"text": "Test Case document - This document contains list of tests required to be conducted. It includes Unit test plan, Integration test plan, System test plan and Acceptance test plan."
},
{
"code": null,
"e": 132387,
"s": 132278,
"text": "Test description - This document is a detailed description of all test cases and procedures to execute them."
},
{
"code": null,
"e": 132496,
"s": 132387,
"text": "Test description - This document is a detailed description of all test cases and procedures to execute them."
},
{
"code": null,
"e": 132580,
"s": 132496,
"text": "Test case report - This document contains test case report as a result of the test."
},
{
"code": null,
"e": 132664,
"s": 132580,
"text": "Test case report - This document contains test case report as a result of the test."
},
{
"code": null,
"e": 132737,
"s": 132664,
"text": "Test logs - This document contains test logs for every test case report."
},
{
"code": null,
"e": 132810,
"s": 132737,
"text": "Test logs - This document contains test logs for every test case report."
},
{
"code": null,
"e": 132867,
"s": 132810,
"text": "The following documents may be generated after testing :"
},
{
"code": null,
"e": 133103,
"s": 132867,
"text": "Test summary - This test summary is collective analysis of all test reports and logs. It summarizes and concludes if the software is ready to be launched. The software is released under version control system if it is ready to launch."
},
{
"code": null,
"e": 133339,
"s": 133103,
"text": "Test summary - This test summary is collective analysis of all test reports and logs. It summarizes and concludes if the software is ready to be launched. The software is released under version control system if it is ready to launch."
},
{
"code": null,
"e": 133477,
"s": 133339,
"text": "We need to understand that software testing is different from software quality assurance, software quality control and software auditing."
},
{
"code": null,
"e": 133750,
"s": 133477,
"text": "Software quality assurance - These are software development process monitoring means, by which it is assured that all the measures are taken as per the standards of organization. This monitoring is done to make sure that proper software development methods were followed.\n"
},
{
"code": null,
"e": 134022,
"s": 133750,
"text": "Software quality assurance - These are software development process monitoring means, by which it is assured that all the measures are taken as per the standards of organization. This monitoring is done to make sure that proper software development methods were followed."
},
{
"code": null,
"e": 134370,
"s": 134022,
"text": "Software quality control - This is a system to maintain the quality of software product. It may include functional and non-functional aspects of software product, which enhance the goodwill of the organization. This system makes sure that the customer is receiving quality product for their requirement and the product certified as ‘fit for use’.\n"
},
{
"code": null,
"e": 134717,
"s": 134370,
"text": "Software quality control - This is a system to maintain the quality of software product. It may include functional and non-functional aspects of software product, which enhance the goodwill of the organization. This system makes sure that the customer is receiving quality product for their requirement and the product certified as ‘fit for use’."
},
{
"code": null,
"e": 135083,
"s": 134717,
"text": "Software audit - This is a review of procedure used by the organization to develop the software. A team of auditors, independent of development team examines the software process, procedure, requirements and other aspects of SDLC. The purpose of software audit is to check that software and its development process, both conform standards, rules and regulations.\n"
},
{
"code": null,
"e": 135448,
"s": 135083,
"text": "Software audit - This is a review of procedure used by the organization to develop the software. A team of auditors, independent of development team examines the software process, procedure, requirements and other aspects of SDLC. The purpose of software audit is to check that software and its development process, both conform standards, rules and regulations."
},
{
"code": null,
"e": 135713,
"s": 135448,
"text": "Software maintenance is widely accepted part of SDLC now a days. It stands for all the modifications and updations done after the delivery of software product. There are number of reasons, why modifications are required, some of them are briefly mentioned below:"
},
{
"code": null,
"e": 135893,
"s": 135713,
"text": "Market Conditions - Policies, which changes over the time, such as taxation and newly introduced constraints like, how to maintain bookkeeping, may trigger need for modification."
},
{
"code": null,
"e": 136073,
"s": 135893,
"text": "Market Conditions - Policies, which changes over the time, such as taxation and newly introduced constraints like, how to maintain bookkeeping, may trigger need for modification."
},
{
"code": null,
"e": 136174,
"s": 136073,
"text": "Client Requirements - Over the time, customer may ask for new features or functions in the software."
},
{
"code": null,
"e": 136275,
"s": 136174,
"text": "Client Requirements - Over the time, customer may ask for new features or functions in the software."
},
{
"code": null,
"e": 136441,
"s": 136275,
"text": "Host Modifications - If any of the hardware and/or platform (such as operating system) of the target host changes, software changes are needed to keep adaptability."
},
{
"code": null,
"e": 136607,
"s": 136441,
"text": "Host Modifications - If any of the hardware and/or platform (such as operating system) of the target host changes, software changes are needed to keep adaptability."
},
{
"code": null,
"e": 136847,
"s": 136607,
"text": "Organization Changes - If there is any business level change at client end, such as reduction of organization strength, acquiring another company, organization venturing into new business, need to modify in the original software may arise."
},
{
"code": null,
"e": 137087,
"s": 136847,
"text": "Organization Changes - If there is any business level change at client end, such as reduction of organization strength, acquiring another company, organization venturing into new business, need to modify in the original software may arise."
},
{
"code": null,
"e": 137388,
"s": 137087,
"text": "In a software lifetime, type of maintenance may vary based on its nature. It may be just a routine maintenance tasks as some bug discovered by some user or it may be a large event in itself based on maintenance size or nature. Following are some types of maintenance based on their characteristics:"
},
{
"code": null,
"e": 137569,
"s": 137388,
"text": "Corrective Maintenance - This includes modifications and updations done in order to correct or fix problems, which are either discovered by user or concluded by user error reports."
},
{
"code": null,
"e": 137750,
"s": 137569,
"text": "Corrective Maintenance - This includes modifications and updations done in order to correct or fix problems, which are either discovered by user or concluded by user error reports."
},
{
"code": null,
"e": 137940,
"s": 137750,
"text": "Adaptive Maintenance - This includes modifications and updations applied to keep the software product up-to date and tuned to the ever changing world of technology and business environment."
},
{
"code": null,
"e": 138130,
"s": 137940,
"text": "Adaptive Maintenance - This includes modifications and updations applied to keep the software product up-to date and tuned to the ever changing world of technology and business environment."
},
{
"code": null,
"e": 138384,
"s": 138130,
"text": "Perfective Maintenance - This includes modifications and updates done in order to keep the software usable over long period of time. It includes new features, new user requirements for refining the software and improve its reliability and performance."
},
{
"code": null,
"e": 138638,
"s": 138384,
"text": "Perfective Maintenance - This includes modifications and updates done in order to keep the software usable over long period of time. It includes new features, new user requirements for refining the software and improve its reliability and performance."
},
{
"code": null,
"e": 138858,
"s": 138638,
"text": "Preventive Maintenance - This includes modifications and updations to prevent future problems of the software. It aims to attend problems, which are not significant at this moment but may cause serious issues in future."
},
{
"code": null,
"e": 139078,
"s": 138858,
"text": "Preventive Maintenance - This includes modifications and updations to prevent future problems of the software. It aims to attend problems, which are not significant at this moment but may cause serious issues in future."
},
{
"code": null,
"e": 139274,
"s": 139078,
"text": "Reports suggest that the cost of maintenance is high. A study on estimating software maintenance found that the cost of maintenance is as high as 67% of the cost of entire software process cycle."
},
{
"code": null,
"e": 139436,
"s": 139274,
"text": "On an average, the cost of software maintenance is more than 50% of all SDLC phases. There are various factors, which trigger maintenance cost go high, such as: "
},
{
"code": null,
"e": 139505,
"s": 139436,
"text": "The standard age of any software is considered up to 10 to 15 years."
},
{
"code": null,
"e": 139697,
"s": 139505,
"text": "Older softwares, which were meant to work on slow machines with less memory and storage capacity cannot keep themselves challenging against newly coming enhanced softwares on modern hardware."
},
{
"code": null,
"e": 139765,
"s": 139697,
"text": "As technology advances, it becomes costly to maintain old software."
},
{
"code": null,
"e": 139854,
"s": 139765,
"text": "Most maintenance engineers are newbie and use trial and error method to rectify problem."
},
{
"code": null,
"e": 139973,
"s": 139854,
"text": "Often, changes made can easily hurt the original structure of the software, making it hard for any subsequent changes."
},
{
"code": null,
"e": 140051,
"s": 139973,
"text": "Changes are often left undocumented which may cause more conflicts in future."
},
{
"code": null,
"e": 140081,
"s": 140051,
"text": "Structure of Software Program"
},
{
"code": null,
"e": 140103,
"s": 140081,
"text": "Programming Language "
},
{
"code": null,
"e": 140138,
"s": 140103,
"text": "Dependence on external environment"
},
{
"code": null,
"e": 140173,
"s": 140138,
"text": "Staff reliability and availability"
},
{
"code": null,
"e": 140359,
"s": 140173,
"text": "IEEE provides a framework for sequential maintenance process activities. It can be used in iterative manner and can be extended so that customized items and processes can be included. "
},
{
"code": null,
"e": 140426,
"s": 140359,
"text": "These activities go hand-in-hand with each of the following phase:"
},
{
"code": null,
"e": 140680,
"s": 140426,
"text": "Identification & Tracing - It involves activities pertaining to identification of requirement of modification or maintenance. It is generated by user or system may itself report via logs or error messages.Here, the maintenance type is classified also."
},
{
"code": null,
"e": 140934,
"s": 140680,
"text": "Identification & Tracing - It involves activities pertaining to identification of requirement of modification or maintenance. It is generated by user or system may itself report via logs or error messages.Here, the maintenance type is classified also."
},
{
"code": null,
"e": 141277,
"s": 140934,
"text": "Analysis - The modification is analyzed for its impact on the system including safety and security implications. If probable impact is severe, alternative solution is looked for. A set of required modifications is then materialized into requirement specifications. The cost of modification/maintenance is analyzed and estimation is concluded."
},
{
"code": null,
"e": 141620,
"s": 141277,
"text": "Analysis - The modification is analyzed for its impact on the system including safety and security implications. If probable impact is severe, alternative solution is looked for. A set of required modifications is then materialized into requirement specifications. The cost of modification/maintenance is analyzed and estimation is concluded."
},
{
"code": null,
"e": 141812,
"s": 141620,
"text": "Design - New modules, which need to be replaced or modified, are designed against requirement specifications set in the previous stage. Test cases are created for validation and verification."
},
{
"code": null,
"e": 142004,
"s": 141812,
"text": "Design - New modules, which need to be replaced or modified, are designed against requirement specifications set in the previous stage. Test cases are created for validation and verification."
},
{
"code": null,
"e": 142170,
"s": 142004,
"text": "Implementation - The new modules are coded with the help of structured design created in the design step.Every programmer is expected to do unit testing in parallel."
},
{
"code": null,
"e": 142336,
"s": 142170,
"text": "Implementation - The new modules are coded with the help of structured design created in the design step.Every programmer is expected to do unit testing in parallel."
},
{
"code": null,
"e": 142569,
"s": 142336,
"text": "System Testing - Integration testing is done among newly created modules. Integration testing is also carried out between new modules and the system. Finally the system is tested as a whole, following regressive testing procedures."
},
{
"code": null,
"e": 142802,
"s": 142569,
"text": "System Testing - Integration testing is done among newly created modules. Integration testing is also carried out between new modules and the system. Finally the system is tested as a whole, following regressive testing procedures."
},
{
"code": null,
"e": 143016,
"s": 142802,
"text": "Acceptance Testing - After testing the system internally, it is tested for acceptance with the help of users. If at this state, user complaints some issues they are addressed or noted to address in next iteration."
},
{
"code": null,
"e": 143230,
"s": 143016,
"text": "Acceptance Testing - After testing the system internally, it is tested for acceptance with the help of users. If at this state, user complaints some issues they are addressed or noted to address in next iteration."
},
{
"code": null,
"e": 143547,
"s": 143230,
"text": "Delivery - After acceptance test, the system is deployed all over the organization either by small update package or fresh installation of the system. The final testing takes place at client end after the software is delivered. \nTraining facility is provided if required, in addition to the hard copy of user manual."
},
{
"code": null,
"e": 143776,
"s": 143547,
"text": "Delivery - After acceptance test, the system is deployed all over the organization either by small update package or fresh installation of the system. The final testing takes place at client end after the software is delivered. "
},
{
"code": null,
"e": 143864,
"s": 143776,
"text": "Training facility is provided if required, in addition to the hard copy of user manual."
},
{
"code": null,
"e": 144052,
"s": 143864,
"text": "Maintenance management - Configuration management is an essential part of system maintenance. It is aided with version control tools to control versions, semi-version or patch management."
},
{
"code": null,
"e": 144240,
"s": 144052,
"text": "Maintenance management - Configuration management is an essential part of system maintenance. It is aided with version control tools to control versions, semi-version or patch management."
},
{
"code": null,
"e": 144480,
"s": 144240,
"text": "When we need to update the software to keep it to the current market, without impacting its functionality, it is called software re-engineering. It is a thorough process where the design of software is changed and programs are re-written."
},
{
"code": null,
"e": 144710,
"s": 144480,
"text": "Legacy software cannot keep tuning with the latest technology available in the market. As the hardware become obsolete, updating of software becomes a headache. Even if software grows old with time, its functionality does not. "
},
{
"code": null,
"e": 144892,
"s": 144710,
"text": "For example, initially Unix was developed in assembly language. When language C came into existence, Unix was re-engineered in C, because working in assembly language was difficult."
},
{
"code": null,
"e": 145036,
"s": 144892,
"text": "Other than this, sometimes programmers notice that few parts of software need more maintenance than others and they also need re-engineering."
},
{
"code": null,
"e": 145103,
"s": 145036,
"text": "Decide what to re-engineer. Is it whole software or a part of it?"
},
{
"code": null,
"e": 145188,
"s": 145103,
"text": "Perform Reverse Engineering, in order to obtain specifications of existing software."
},
{
"code": null,
"e": 145301,
"s": 145188,
"text": "Restructure Program if required. For example, changing function-oriented programs into object-oriented programs."
},
{
"code": null,
"e": 145332,
"s": 145301,
"text": "Re-structure data as required."
},
{
"code": null,
"e": 145407,
"s": 145332,
"text": "Apply Forward engineering concepts in order to get re-engineered software."
},
{
"code": null,
"e": 145469,
"s": 145407,
"text": "There are few important terms used in Software re-engineering"
},
{
"code": null,
"e": 145709,
"s": 145469,
"text": "It is a process to achieve system specification by thoroughly analyzing, understanding the existing system. This process can be seen as reverse SDLC model, i.e. we try to get higher abstraction level by analyzing lower abstraction levels."
},
{
"code": null,
"e": 146002,
"s": 145709,
"text": "An existing system is previously implemented design, about which we know nothing. Designers then do reverse engineering by looking at the code and try to get the design. With design in hand, they try to conclude the specifications. Thus, going in reverse from code to system specification."
},
{
"code": null,
"e": 146299,
"s": 146002,
"text": "It is a process to re-structure and re-construct the existing software. It is all about re-arranging the source code, either in same programming language or from one programming language to a different one. Restructuring can have either source code-restructuring and data-restructuring or both."
},
{
"code": null,
"e": 146514,
"s": 146299,
"text": "Re-structuring does not impact the functionality of the software but enhance reliability and maintainability. Program components, which cause errors very frequently can be changed, or updated with re-structuring."
},
{
"code": null,
"e": 146609,
"s": 146514,
"text": "The dependability of software on obsolete hardware platform can be removed via re-structuring."
},
{
"code": null,
"e": 146839,
"s": 146609,
"text": "Forward engineering is a process of obtaining desired software from the specifications in hand which were brought down by means of reverse engineering. It assumes that there was some software engineering already done in the past."
},
{
"code": null,
"e": 146979,
"s": 146839,
"text": " Forward engineering is same as software engineering process with only one difference – it is carried out always after reverse engineering."
},
{
"code": null,
"e": 147125,
"s": 146979,
"text": "A component is a part of software program code, which executes an independent task in the system. It can be a small module or sub-system itself."
},
{
"code": null,
"e": 147267,
"s": 147125,
"text": "The login procedures used on the web can be considered as components, printing system in software can be seen as a component of the software."
},
{
"code": null,
"e": 147430,
"s": 147267,
"text": "Components have high cohesion of functionality and lower rate of coupling, i.e. they work independently and can perform tasks without depending on other modules."
},
{
"code": null,
"e": 147557,
"s": 147430,
"text": "In OOP, the objects are designed are very specific to their concern and have fewer chances to be used in some other software. "
},
{
"code": null,
"e": 147689,
"s": 147557,
"text": "In modular programming, the modules are coded to perform specific tasks which can be used across number of other software programs."
},
{
"code": null,
"e": 147829,
"s": 147689,
"text": "There is a whole new vertical, which is based on re-use of software component, and is known as Component Based Software Engineering (CBSE)."
},
{
"code": null,
"e": 147866,
"s": 147829,
"text": "Re-use can be done at various levels"
},
{
"code": null,
"e": 147954,
"s": 147866,
"text": "Application level - Where an entire application is used as sub-system of new software."
},
{
"code": null,
"e": 148042,
"s": 147954,
"text": "Application level - Where an entire application is used as sub-system of new software."
},
{
"code": null,
"e": 148106,
"s": 148042,
"text": "Component level - Where sub-system of an application is used."
},
{
"code": null,
"e": 148170,
"s": 148106,
"text": "Component level - Where sub-system of an application is used."
},
{
"code": null,
"e": 148338,
"s": 148170,
"text": "Modules level - Where functional modules are re-used.\nSoftware components provide interfaces, which can be used to establish communication among different components."
},
{
"code": null,
"e": 148393,
"s": 148338,
"text": "Modules level - Where functional modules are re-used."
},
{
"code": null,
"e": 148506,
"s": 148393,
"text": "Software components provide interfaces, which can be used to establish communication among different components."
},
{
"code": null,
"e": 148661,
"s": 148506,
"text": "Two kinds of method can be adopted: either by keeping requirements same and adjusting components or by keeping components same and modifying requirements."
},
{
"code": null,
"e": 148847,
"s": 148661,
"text": "Requirement Specification - The functional and non-functional requirements are specified, which a software product must comply to, with the help of existing system, user input or both. "
},
{
"code": null,
"e": 149033,
"s": 148847,
"text": "Requirement Specification - The functional and non-functional requirements are specified, which a software product must comply to, with the help of existing system, user input or both. "
},
{
"code": null,
"e": 149221,
"s": 149033,
"text": "Design - This is also a standard SDLC process step, where requirements are defined in terms of software parlance. Basic architecture of system as a whole and its sub-systems are created."
},
{
"code": null,
"e": 149409,
"s": 149221,
"text": "Design - This is also a standard SDLC process step, where requirements are defined in terms of software parlance. Basic architecture of system as a whole and its sub-systems are created."
},
{
"code": null,
"e": 149646,
"s": 149409,
"text": "Specify Components - By studying the software design, the designers segregate the entire system into smaller components or sub-systems. One complete software design turns into a collection of a huge set of components working together."
},
{
"code": null,
"e": 149883,
"s": 149646,
"text": "Specify Components - By studying the software design, the designers segregate the entire system into smaller components or sub-systems. One complete software design turns into a collection of a huge set of components working together."
},
{
"code": null,
"e": 150076,
"s": 149883,
"text": "Search Suitable Components - The software component repository is referred by designers to search for the matching component, on the basis of functionality and intended software requirements.."
},
{
"code": null,
"e": 150269,
"s": 150076,
"text": "Search Suitable Components - The software component repository is referred by designers to search for the matching component, on the basis of functionality and intended software requirements.."
},
{
"code": null,
"e": 150373,
"s": 150269,
"text": "Incorporate Components - All matched components are packed together to shape them as complete software."
},
{
"code": null,
"e": 150477,
"s": 150373,
"text": "Incorporate Components - All matched components are packed together to shape them as complete software."
},
{
"code": null,
"e": 150638,
"s": 150477,
"text": "CASE stands for Computer Aided Software Engineering. It means, development and maintenance of software projects with help of various automated software tools.\n"
},
{
"code": null,
"e": 150838,
"s": 150638,
"text": "CASE tools are set of software application programs, which are used to automate SDLC activities. CASE tools are used by software project managers, analysts and engineers to develop software system. "
},
{
"code": null,
"e": 151072,
"s": 150838,
"text": "There are number of CASE tools available to simplify various stages of Software Development Life Cycle such as Analysis tools, Design tools, Project management tools, Database Management tools, Documentation tools are to name a few. "
},
{
"code": null,
"e": 151244,
"s": 151072,
"text": "Use of CASE tools accelerates the development of project to produce desired result and helps to uncover flaws before moving ahead with next stage in software development. "
},
{
"code": null,
"e": 151350,
"s": 151244,
"text": "CASE tools can be broadly divided into the following parts based on their use at a particular SDLC stage:"
},
{
"code": null,
"e": 151735,
"s": 151350,
"text": "Central Repository - CASE tools require a central repository, which can serve as a source of common, integrated and consistent information. Central repository is a central place of storage where product specifications, requirement documents, related reports and diagrams, other useful information regarding management is stored. Central repository also serves as data dictionary.\n"
},
{
"code": null,
"e": 152119,
"s": 151735,
"text": "Central Repository - CASE tools require a central repository, which can serve as a source of common, integrated and consistent information. Central repository is a central place of storage where product specifications, requirement documents, related reports and diagrams, other useful information regarding management is stored. Central repository also serves as data dictionary."
},
{
"code": null,
"e": 152213,
"s": 152119,
"text": "Upper Case Tools - Upper CASE tools are used in planning, analysis and design stages of SDLC."
},
{
"code": null,
"e": 152307,
"s": 152213,
"text": "Upper Case Tools - Upper CASE tools are used in planning, analysis and design stages of SDLC."
},
{
"code": null,
"e": 152396,
"s": 152307,
"text": "Lower Case Tools - Lower CASE tools are used in implementation, testing and maintenance."
},
{
"code": null,
"e": 152485,
"s": 152396,
"text": "Lower Case Tools - Lower CASE tools are used in implementation, testing and maintenance."
},
{
"code": null,
"e": 152627,
"s": 152485,
"text": "Integrated Case Tools - Integrated CASE tools are helpful in all the stages of SDLC, from Requirement gathering to Testing and documentation."
},
{
"code": null,
"e": 152769,
"s": 152627,
"text": "Integrated Case Tools - Integrated CASE tools are helpful in all the stages of SDLC, from Requirement gathering to Testing and documentation."
},
{
"code": null,
"e": 152915,
"s": 152769,
"text": "CASE tools can be grouped together if they have similar functionality, process activities and capability of getting integrated with other tools. "
},
{
"code": null,
"e": 152965,
"s": 152915,
"text": "The scope of CASE tools goes throughout the SDLC."
},
{
"code": null,
"e": 153010,
"s": 152965,
"text": "Now we briefly go through various CASE tools"
},
{
"code": null,
"e": 153240,
"s": 153010,
"text": "These tools are used to represent system components, data and control flow among various software components and system structure in a graphical form. For example, Flow Chart Maker tool for creating state-of-the-art flowcharts."
},
{
"code": null,
"e": 153491,
"s": 153240,
"text": "Process modeling is method to create software process model, which is used to develop the software. Process modeling tools help the managers to choose a process model or modify it as per the requirement of software product. For example, EPF Composer"
},
{
"code": null,
"e": 153886,
"s": 153491,
"text": "These tools are used for project planning, cost and effort estimation, project scheduling and resource planning. Managers have to strictly comply project execution with every mentioned step in software project management. Project management tools help in storing and sharing project information in real-time throughout the organization. For example, Creative Pro Office, Trac Project, Basecamp."
},
{
"code": null,
"e": 154037,
"s": 153886,
"text": "Documentation in a software project starts prior to the software process, goes throughout all phases of SDLC and after the completion of the project. "
},
{
"code": null,
"e": 154435,
"s": 154037,
"text": "Documentation tools generate documents for technical users and end users. Technical users are mostly in-house professionals of the development team who refer to system manual, reference manual, training manual, installation manuals etc. The end user documents describe the functioning and how-to of the system such as user manual. For example, Doxygen, DrExplain, Adobe RoboHelp for documentation."
},
{
"code": null,
"e": 154698,
"s": 154435,
"text": "These tools help to gather requirements, automatically check for any inconsistency, inaccuracy in the diagrams, data redundancies or erroneous omissions. For example, Accept 360, Accompa, CaseComplete for requirement analysis, Visible Analyst for total analysis."
},
{
"code": null,
"e": 154982,
"s": 154698,
"text": "These tools help software designers to design the block structure of the software, which may further be broken down in smaller modules using refinement techniques. These tools provides detailing of each module and interconnections among modules. For example, Animated Software Design"
},
{
"code": null,
"e": 155081,
"s": 154982,
"text": "An instance of software is released under one version. Configuration Management tools deal with –"
},
{
"code": null,
"e": 155114,
"s": 155081,
"text": "Version and revision management "
},
{
"code": null,
"e": 155149,
"s": 155114,
"text": "Baseline configuration management "
},
{
"code": null,
"e": 155175,
"s": 155149,
"text": "Change control management"
},
{
"code": null,
"e": 155302,
"s": 155175,
"text": "CASE tools help in this by automatic tracking, version management and release management. For example, Fossil, Git, Accu REV."
},
{
"code": null,
"e": 155628,
"s": 155302,
"text": "These tools are considered as a part of configuration management tools. They deal with changes made to the software after its baseline is fixed or when the software is first released. CASE tools automate change tracking, file management, code management and more. It also helps in enforcing change policy of the organization."
},
{
"code": null,
"e": 155937,
"s": 155628,
"text": "These tools consist of programming environments like IDE (Integrated Development Environment), in-built modules library and simulation tools. These tools provide comprehensive aid in building software product and include features for simulation and testing. For example, Cscope to search code in C, Eclipse."
},
{
"code": null,
"e": 156113,
"s": 155937,
"text": "Software prototype is simulated version of the intended software product. Prototype provides initial look and feel of the product and simulates few aspect of actual product. "
},
{
"code": null,
"e": 156438,
"s": 156113,
"text": "Prototyping CASE tools essentially come with graphical libraries. They can create hardware independent user interfaces and design. These tools help us to build rapid prototypes based on existing information. In addition, they provide simulation of software prototype. For example, Serena prototype composer, Mockup Builder."
},
{
"code": null,
"e": 156721,
"s": 156438,
"text": "These tools assist in designing web pages with all allied elements like forms, text, script, graphic and so on. Web tools also provide live preview of what is being developed and how will it look after completion. For example, Fontello, Adobe Edge Inspect, Foundation 3, Brackets."
},
{
"code": null,
"e": 157059,
"s": 156721,
"text": "Quality assurance in a software organization is monitoring the engineering process and methods adopted to develop the software product in order to ensure conformance of quality as per organization standards. QA tools consist of configuration and change control tools and software testing tools. For example, SoapTest, AppsWatch, JMeter."
},
{
"code": null,
"e": 157405,
"s": 157059,
"text": "Software maintenance includes modifications in the software product after it is delivered. Automatic logging and error reporting techniques, automatic error ticket generation and root cause Analysis are few CASE tools, which help software organization in maintenance phase of SDLC. For example, Bugzilla for defect tracking, HP Quality Center."
},
{
"code": null,
"e": 157440,
"s": 157405,
"text": "\n 80 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 157459,
"s": 157440,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 157492,
"s": 157459,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 157505,
"s": 157492,
"text": " Zach Miller"
},
{
"code": null,
"e": 157540,
"s": 157505,
"text": "\n 17 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 157553,
"s": 157540,
"text": " Zach Miller"
},
{
"code": null,
"e": 157586,
"s": 157553,
"text": "\n 60 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 157597,
"s": 157586,
"text": " John Shea"
},
{
"code": null,
"e": 157631,
"s": 157597,
"text": "\n 99 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 157642,
"s": 157631,
"text": " Daniel IT"
},
{
"code": null,
"e": 157675,
"s": 157642,
"text": "\n 62 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 157692,
"s": 157675,
"text": " GlobalETraining"
},
{
"code": null,
"e": 157699,
"s": 157692,
"text": " Print"
},
{
"code": null,
"e": 157710,
"s": 157699,
"text": " Add Notes"
}
] |
How to Mitigate Overfitting with Feature Selection | by Rukshan Pramoditha | Towards Data Science | This is the final part of the “Addressing the problem of overfitting” article series. Today, we’re continuing from Part 4. Last time, in the 3rd step of Part 4, we’ve built a random forest model on the “heart disease” dataset. There, we used all 13 features of the dataset. Today, we’ll modify that model by considering only the most important features.
First, we visualize the feature importances of that random forest model by using the feature_importances_ attribute.
It is very clear that not all features contribute to the model. Some features are not important to the model and we can remove them.
When we remove the least important features from the model, we reduce the model’s complexity and some noise in the data. Doing so will help to further mitigate overfitting — By author
The x-axis of the above graph contains the feature importance scores for each feature. We can specify a threshold value (here, we choose 0.025) for the importance score such that all features that have scores under that threshold value to be eliminated. For that, we can use the Scikit-learn SelectFromModel class.
from sklearn.feature_selection import SelectFromModelselector = SelectFromModel(rfclf, threshold=0.025)features_important = selector.fit_transform(X, y)
This returns a 2D-Numpy array that has values of only the important features decided by the threshold value. By converting it to a Pandas dataframe,
pd.DataFrame(features_important).head()
We can obtain the following table:
If we also get the original dataframe,
X.head()
We’ve removed 4 features: fbs, restecg, trestbps and chol. These features do not give enough contribution to the model. Keeping them in the model will increase the model’s complexity and that will result in the model overfitting the data.
The order of the importance scores of removed features is:
fbs < restecg < trestbps < chol
If we consider the feature “sex”, its importance value is more than twice the value of “chol”. If we also remove the feature “sex”, the model will lose some important data. That will result in the model underfitting. That’s why we’ve chosen 0.025 for the threshold value that selects the features that we want to keep in the model. You can easily decide the value for the threshold by looking at the feature importance graph.
Finally, we can use the modified dataframe with removed features (Dataframe 1) to build the random forest model again. This time, we use only 9 features. In other words, we can say that we’ve reduced the dimensionality of data. But, keep in mind that the original values in the dataset remain unchanged. You can compare this with Part 3 of the series where we’ve discussed a dimensionality reduction method that finds a new set of features that contains different values than in the original dataset.
The feature selection method that we discussed today can be applied to tree-based models such as decision trees, random forests, etc. For linear regression and logistic regression models, backward elimination and forward selection are mostly preferred. If you want to learn them in detail, read this article written by me.
This is the end of today’s part and also the “Addressing the problem of overfitting” article series. We’ve discussed 5 different techniques to address the problem of overfitting under 5 articles. As additional content, I’ll add some guidelines to select the best technique.
So far, we’ve discussed the following techniques that can be used to mitigate overfitting:
Cross-validation
Regularization
Dimensionality Reduction
Creating Ensembles
Feature Selection
You do not need to apply all these techniques to mitigate overfitting. Here are some guidelines that will help you to select the best technique.
First, you need to realize that your model is overfitting before applying any technique. If you get a higher train score and relatively a much lower test score, your model overfits the data.
It is always better to evaluate the model by using Cross-validation that helps you to detect plenty of options to mitigate overfitting.
It is better to combine Cross-validation with a hyperparameter tuning technique like Grid Search or Random Search that finds a set of optimal values for defined hyperparameters. That will help you to mitigate overfitting. Hyperparameter tuning can be done with any model. For example, we can use it to limit the growth of a decision tree. That process is a type of Regularization discussed in Part 2.
The other type of regularization is adding a regularization term to the loss function. This works well for linear models such as logistic regression, linear regression as well for tree-based models such as XGBoost. For logistic regression, the L2 variant of regularization is applied by default in Scikit-learn. L1 variant is also available. For linear regression, there is no option to specify the regularization in the model itself. However, Scikit-learn provides 3 different options for that. When we apply L1 regularization to linear regression, it is called Lasso regression. When we apply L2 regularization to linear regression, it is called Ridge regression. When we apply both L1 and L2 variants at the same time to linear regression, it is called ElasticNet regression.
Dimensionality reduction techniques can be applied to almost any dataset. The most popular DR technique is the Principal Component Analysis (PCA). It has many advantages other than addressing the problem of overfitting.
If you want to find non-linear patterns in the data, you can use Ensemble techniques such as random forests and XGBoost models rather than using a single decision tree.
You can also combine two techniques together for better results. For example, you can create Ensemble models while applying regularization to limit the growth of individual trees. You can create Ensemble models while selecting the most important features in the dataset.
After creating a model, you can identify the most important features and remove the unnecessary features from the dataset and rebuild the model by using only the most important features. For Ensemble models like the random forest, XGBoost, this can be easily done using the feature_importances_ attribute. For linear regression and logistic regression models, backward elimination and forward selection can be done using separate classes.
Now, you’ll have hands-on experience for applying 5 different techniques to address the problem of overfitting. I suggest you apply them to different datasets. You can apply more than one technique to a dataset and see the outputs and then choose the best one by looking at the outputs.
For your convenience, I’ve decided to make a list that consists of all the parts of this article series plus another useful post. Now, you can access all of them in one place by clicking on the following image.
This is the end of today’s post. My readers can sign up for a membership through the following link to get full access to every story I write and I will receive a portion of your membership fee.
Sign-up link: https://rukshanpramoditha.medium.com/membership
Thank you so much for your continuous support! See you in the next story. Happy learning to everyone!
Special credit goes to Mockup Photos on Unsplash, who provides me with a nice cover image for this post (I did some modifications to the image: added some text on it and removed some parts). | [
{
"code": null,
"e": 400,
"s": 46,
"text": "This is the final part of the “Addressing the problem of overfitting” article series. Today, we’re continuing from Part 4. Last time, in the 3rd step of Part 4, we’ve built a random forest model on the “heart disease” dataset. There, we used all 13 features of the dataset. Today, we’ll modify that model by considering only the most important features."
},
{
"code": null,
"e": 517,
"s": 400,
"text": "First, we visualize the feature importances of that random forest model by using the feature_importances_ attribute."
},
{
"code": null,
"e": 650,
"s": 517,
"text": "It is very clear that not all features contribute to the model. Some features are not important to the model and we can remove them."
},
{
"code": null,
"e": 834,
"s": 650,
"text": "When we remove the least important features from the model, we reduce the model’s complexity and some noise in the data. Doing so will help to further mitigate overfitting — By author"
},
{
"code": null,
"e": 1149,
"s": 834,
"text": "The x-axis of the above graph contains the feature importance scores for each feature. We can specify a threshold value (here, we choose 0.025) for the importance score such that all features that have scores under that threshold value to be eliminated. For that, we can use the Scikit-learn SelectFromModel class."
},
{
"code": null,
"e": 1302,
"s": 1149,
"text": "from sklearn.feature_selection import SelectFromModelselector = SelectFromModel(rfclf, threshold=0.025)features_important = selector.fit_transform(X, y)"
},
{
"code": null,
"e": 1451,
"s": 1302,
"text": "This returns a 2D-Numpy array that has values of only the important features decided by the threshold value. By converting it to a Pandas dataframe,"
},
{
"code": null,
"e": 1491,
"s": 1451,
"text": "pd.DataFrame(features_important).head()"
},
{
"code": null,
"e": 1526,
"s": 1491,
"text": "We can obtain the following table:"
},
{
"code": null,
"e": 1565,
"s": 1526,
"text": "If we also get the original dataframe,"
},
{
"code": null,
"e": 1574,
"s": 1565,
"text": "X.head()"
},
{
"code": null,
"e": 1813,
"s": 1574,
"text": "We’ve removed 4 features: fbs, restecg, trestbps and chol. These features do not give enough contribution to the model. Keeping them in the model will increase the model’s complexity and that will result in the model overfitting the data."
},
{
"code": null,
"e": 1872,
"s": 1813,
"text": "The order of the importance scores of removed features is:"
},
{
"code": null,
"e": 1904,
"s": 1872,
"text": "fbs < restecg < trestbps < chol"
},
{
"code": null,
"e": 2330,
"s": 1904,
"text": "If we consider the feature “sex”, its importance value is more than twice the value of “chol”. If we also remove the feature “sex”, the model will lose some important data. That will result in the model underfitting. That’s why we’ve chosen 0.025 for the threshold value that selects the features that we want to keep in the model. You can easily decide the value for the threshold by looking at the feature importance graph."
},
{
"code": null,
"e": 2831,
"s": 2330,
"text": "Finally, we can use the modified dataframe with removed features (Dataframe 1) to build the random forest model again. This time, we use only 9 features. In other words, we can say that we’ve reduced the dimensionality of data. But, keep in mind that the original values in the dataset remain unchanged. You can compare this with Part 3 of the series where we’ve discussed a dimensionality reduction method that finds a new set of features that contains different values than in the original dataset."
},
{
"code": null,
"e": 3154,
"s": 2831,
"text": "The feature selection method that we discussed today can be applied to tree-based models such as decision trees, random forests, etc. For linear regression and logistic regression models, backward elimination and forward selection are mostly preferred. If you want to learn them in detail, read this article written by me."
},
{
"code": null,
"e": 3428,
"s": 3154,
"text": "This is the end of today’s part and also the “Addressing the problem of overfitting” article series. We’ve discussed 5 different techniques to address the problem of overfitting under 5 articles. As additional content, I’ll add some guidelines to select the best technique."
},
{
"code": null,
"e": 3519,
"s": 3428,
"text": "So far, we’ve discussed the following techniques that can be used to mitigate overfitting:"
},
{
"code": null,
"e": 3536,
"s": 3519,
"text": "Cross-validation"
},
{
"code": null,
"e": 3551,
"s": 3536,
"text": "Regularization"
},
{
"code": null,
"e": 3576,
"s": 3551,
"text": "Dimensionality Reduction"
},
{
"code": null,
"e": 3595,
"s": 3576,
"text": "Creating Ensembles"
},
{
"code": null,
"e": 3613,
"s": 3595,
"text": "Feature Selection"
},
{
"code": null,
"e": 3758,
"s": 3613,
"text": "You do not need to apply all these techniques to mitigate overfitting. Here are some guidelines that will help you to select the best technique."
},
{
"code": null,
"e": 3949,
"s": 3758,
"text": "First, you need to realize that your model is overfitting before applying any technique. If you get a higher train score and relatively a much lower test score, your model overfits the data."
},
{
"code": null,
"e": 4085,
"s": 3949,
"text": "It is always better to evaluate the model by using Cross-validation that helps you to detect plenty of options to mitigate overfitting."
},
{
"code": null,
"e": 4486,
"s": 4085,
"text": "It is better to combine Cross-validation with a hyperparameter tuning technique like Grid Search or Random Search that finds a set of optimal values for defined hyperparameters. That will help you to mitigate overfitting. Hyperparameter tuning can be done with any model. For example, we can use it to limit the growth of a decision tree. That process is a type of Regularization discussed in Part 2."
},
{
"code": null,
"e": 5265,
"s": 4486,
"text": "The other type of regularization is adding a regularization term to the loss function. This works well for linear models such as logistic regression, linear regression as well for tree-based models such as XGBoost. For logistic regression, the L2 variant of regularization is applied by default in Scikit-learn. L1 variant is also available. For linear regression, there is no option to specify the regularization in the model itself. However, Scikit-learn provides 3 different options for that. When we apply L1 regularization to linear regression, it is called Lasso regression. When we apply L2 regularization to linear regression, it is called Ridge regression. When we apply both L1 and L2 variants at the same time to linear regression, it is called ElasticNet regression."
},
{
"code": null,
"e": 5485,
"s": 5265,
"text": "Dimensionality reduction techniques can be applied to almost any dataset. The most popular DR technique is the Principal Component Analysis (PCA). It has many advantages other than addressing the problem of overfitting."
},
{
"code": null,
"e": 5654,
"s": 5485,
"text": "If you want to find non-linear patterns in the data, you can use Ensemble techniques such as random forests and XGBoost models rather than using a single decision tree."
},
{
"code": null,
"e": 5925,
"s": 5654,
"text": "You can also combine two techniques together for better results. For example, you can create Ensemble models while applying regularization to limit the growth of individual trees. You can create Ensemble models while selecting the most important features in the dataset."
},
{
"code": null,
"e": 6364,
"s": 5925,
"text": "After creating a model, you can identify the most important features and remove the unnecessary features from the dataset and rebuild the model by using only the most important features. For Ensemble models like the random forest, XGBoost, this can be easily done using the feature_importances_ attribute. For linear regression and logistic regression models, backward elimination and forward selection can be done using separate classes."
},
{
"code": null,
"e": 6651,
"s": 6364,
"text": "Now, you’ll have hands-on experience for applying 5 different techniques to address the problem of overfitting. I suggest you apply them to different datasets. You can apply more than one technique to a dataset and see the outputs and then choose the best one by looking at the outputs."
},
{
"code": null,
"e": 6862,
"s": 6651,
"text": "For your convenience, I’ve decided to make a list that consists of all the parts of this article series plus another useful post. Now, you can access all of them in one place by clicking on the following image."
},
{
"code": null,
"e": 7057,
"s": 6862,
"text": "This is the end of today’s post. My readers can sign up for a membership through the following link to get full access to every story I write and I will receive a portion of your membership fee."
},
{
"code": null,
"e": 7119,
"s": 7057,
"text": "Sign-up link: https://rukshanpramoditha.medium.com/membership"
},
{
"code": null,
"e": 7221,
"s": 7119,
"text": "Thank you so much for your continuous support! See you in the next story. Happy learning to everyone!"
}
] |
factorial() in Python | Finding the factorial of a number is a frequent requirement in data analysis and other mathematical analysis involving python. The factorial is always found for a positive integer by multiplying all the integers starting from 1 till the given number. There can be three approaches to find this as shown below.
We can use a for loop to iterate through number 1 till the designated number and keep multiplying at each step. In the below program we ask the user to enter the number and convert the input to an integer before using it in the loop. This way we ensure we get positive integers in the calculation.
Live Demo
n = input("Enter a number: ")
factorial = 1
if int(n) >= 1:
for i in range (1,int(n)+1):
factorial = factorial * i
print("Factorail of ",n , " is : ",factorial)
Running the above code gives us the following result −
Enter a number: 5
Factorail of 5 is : 120
Live Demo
num = input("Enter a number: ")
def recur_factorial(n):
if n == 1:
return n
elif n < 1:
return ("NA")
else:
return n*recur_factorial(n-1)
print (recur_factorial(int(num)))
Running the above code gives us the following result −
#Run1:
Enter a number: 5
120
#Run2:
Enter a number: -2
NA
In this case we can directly use factorial function which is available in math module. We need not write the code for factorial functionality rather directly use the math.factorial(). That also takes care of negative numbers and fractional numbers scenario.
Live Demo
import math
num = input("Enter a number: ")
print("The factorial of ", num, " is : ")
print(math.factorial(int(num)))
Running the above code gives us the following result −
#Run1:
Enter a number: 5
The factorial of 5 is :
120
#Run 2:
Enter a number: 3.6
Traceback (most recent call last):
The factorial of 3.6 is :
File "C:/Users....py", line 5, in
print(math.factorial(int(num)))
ValueError: invalid literal for int() with base 10: '3.6' | [
{
"code": null,
"e": 1372,
"s": 1062,
"text": "Finding the factorial of a number is a frequent requirement in data analysis and other mathematical analysis involving python. The factorial is always found for a positive integer by multiplying all the integers starting from 1 till the given number. There can be three approaches to find this as shown below."
},
{
"code": null,
"e": 1670,
"s": 1372,
"text": "We can use a for loop to iterate through number 1 till the designated number and keep multiplying at each step. In the below program we ask the user to enter the number and convert the input to an integer before using it in the loop. This way we ensure we get positive integers in the calculation."
},
{
"code": null,
"e": 1681,
"s": 1670,
"text": " Live Demo"
},
{
"code": null,
"e": 1845,
"s": 1681,
"text": "n = input(\"Enter a number: \")\nfactorial = 1\nif int(n) >= 1:\nfor i in range (1,int(n)+1):\n factorial = factorial * i\nprint(\"Factorail of \",n , \" is : \",factorial)"
},
{
"code": null,
"e": 1900,
"s": 1845,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 1942,
"s": 1900,
"text": "Enter a number: 5\nFactorail of 5 is : 120"
},
{
"code": null,
"e": 1953,
"s": 1942,
"text": " Live Demo"
},
{
"code": null,
"e": 2134,
"s": 1953,
"text": "num = input(\"Enter a number: \")\ndef recur_factorial(n):\nif n == 1:\n return n\nelif n < 1:\n return (\"NA\")\nelse:\n return n*recur_factorial(n-1)\nprint (recur_factorial(int(num)))"
},
{
"code": null,
"e": 2189,
"s": 2134,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2247,
"s": 2189,
"text": "#Run1:\nEnter a number: 5\n120\n#Run2:\nEnter a number: -2\nNA"
},
{
"code": null,
"e": 2505,
"s": 2247,
"text": "In this case we can directly use factorial function which is available in math module. We need not write the code for factorial functionality rather directly use the math.factorial(). That also takes care of negative numbers and fractional numbers scenario."
},
{
"code": null,
"e": 2516,
"s": 2505,
"text": " Live Demo"
},
{
"code": null,
"e": 2634,
"s": 2516,
"text": "import math\nnum = input(\"Enter a number: \")\nprint(\"The factorial of \", num, \" is : \")\nprint(math.factorial(int(num)))"
},
{
"code": null,
"e": 2689,
"s": 2634,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2955,
"s": 2689,
"text": "#Run1:\nEnter a number: 5\nThe factorial of 5 is :\n120\n#Run 2:\nEnter a number: 3.6\nTraceback (most recent call last):\nThe factorial of 3.6 is :\nFile \"C:/Users....py\", line 5, in\nprint(math.factorial(int(num)))\nValueError: invalid literal for int() with base 10: '3.6'"
}
] |
How to return an array from a function in C++? | C++ does not return entire array but it can return pointer to an array. Outside the function, address of local variable cannot be returned. By making local variable static, it can return the address of local variable.
The following is the syntax to return a pointer.
int * function_name()
{ body }
Here,
function_name − The name of function given by user.
The following is an example to return an array from a function.
Live Demo
#include <iostream>
using namespace std;
int * ret() {
static int x[3];
for(int i=0 ; i<5 ; i++) {
cout << " " <<&x[i];
}
return x;
}
int main() {
ret();
return 0;
}
0x601180 0x601184 0x601188 0x60118c 0x601190
In the above program, a function ret() is created and it is returning an array. A static int type array is declared and addresses of allocated memory blocks are printed.
int * ret() {
static int x[3];
for(int i=0 ; i<5 ; i++) {
cout << " " <<&x[i];
}
return x;
}
In the main() function, the function ret() is called −
ret(); | [
{
"code": null,
"e": 1280,
"s": 1062,
"text": "C++ does not return entire array but it can return pointer to an array. Outside the function, address of local variable cannot be returned. By making local variable static, it can return the address of local variable."
},
{
"code": null,
"e": 1329,
"s": 1280,
"text": "The following is the syntax to return a pointer."
},
{
"code": null,
"e": 1360,
"s": 1329,
"text": "int * function_name()\n{ body }"
},
{
"code": null,
"e": 1366,
"s": 1360,
"text": "Here,"
},
{
"code": null,
"e": 1418,
"s": 1366,
"text": "function_name − The name of function given by user."
},
{
"code": null,
"e": 1482,
"s": 1418,
"text": "The following is an example to return an array from a function."
},
{
"code": null,
"e": 1493,
"s": 1482,
"text": " Live Demo"
},
{
"code": null,
"e": 1683,
"s": 1493,
"text": "#include <iostream>\nusing namespace std;\nint * ret() {\n static int x[3];\n for(int i=0 ; i<5 ; i++) {\n cout << \" \" <<&x[i];\n }\n return x;\n}\nint main() {\n ret();\n return 0;\n}"
},
{
"code": null,
"e": 1728,
"s": 1683,
"text": "0x601180 0x601184 0x601188 0x60118c 0x601190"
},
{
"code": null,
"e": 1898,
"s": 1728,
"text": "In the above program, a function ret() is created and it is returning an array. A static int type array is declared and addresses of allocated memory blocks are printed."
},
{
"code": null,
"e": 2009,
"s": 1898,
"text": "int * ret() {\n static int x[3];\n for(int i=0 ; i<5 ; i++) {\n cout << \" \" <<&x[i];\n }\n return x;\n}"
},
{
"code": null,
"e": 2064,
"s": 2009,
"text": "In the main() function, the function ret() is called −"
},
{
"code": null,
"e": 2071,
"s": 2064,
"text": "ret();"
}
] |
HTML canvas fill() Method | The fill() method in HTML canvas is used to fill the current drawing path. The default is black. The <canvas> element allows you to draw graphics on a web page using JavaScript. Every canvas has two elements that describes the height and width of the canvas i.e. height and width respectively.
Following is the syntax−
ctx.fill();
Let us now see an example to implement the fill() method of canvas −
Live Demo
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="450" height="250" style="border:2px solid blue;">
Your browser does not support the HTML5 canvas tag.</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.rect(50, 60, 300, 200);
ctx.fillStyle = "green";
ctx.fill();
</script>
</body>
</html> | [
{
"code": null,
"e": 1356,
"s": 1062,
"text": "The fill() method in HTML canvas is used to fill the current drawing path. The default is black. The <canvas> element allows you to draw graphics on a web page using JavaScript. Every canvas has two elements that describes the height and width of the canvas i.e. height and width respectively."
},
{
"code": null,
"e": 1381,
"s": 1356,
"text": "Following is the syntax−"
},
{
"code": null,
"e": 1393,
"s": 1381,
"text": "ctx.fill();"
},
{
"code": null,
"e": 1462,
"s": 1393,
"text": "Let us now see an example to implement the fill() method of canvas −"
},
{
"code": null,
"e": 1473,
"s": 1462,
"text": " Live Demo"
},
{
"code": null,
"e": 1853,
"s": 1473,
"text": "<!DOCTYPE html>\n<html>\n<body>\n<canvas id=\"myCanvas\" width=\"450\" height=\"250\" style=\"border:2px solid blue;\">\nYour browser does not support the HTML5 canvas tag.</canvas>\n<script>\n var c = document.getElementById(\"myCanvas\");\n var ctx = c.getContext(\"2d\");\n ctx.beginPath();\n ctx.rect(50, 60, 300, 200);\n ctx.fillStyle = \"green\";\n ctx.fill();\n</script>\n</body>\n</html>"
}
] |
Lodash _.renameKeys() Method - GeeksforGeeks | 30 Sep, 2020
The Lodash _.renameKeys() method takes an object and a mapping object and returns a new object where the keys of the given object have been renamed as the corresponding value in the keyMap.
Syntax:
_.renameKeys(obj, mapObj);
Parameters: This method accept two parameters as mentioned above and described below:
obj: Given object to create a new object.
mapObj: Given map object to create a new object.
Return Value: This method returns a generated object.
Note: This will not work in normal JavaScript because it requires the lodash.js contrib library to be installed. Lodash.js contrib library can be installed using the following command:
npm install lodash-contrib
Example 1:
// Defining underscore lodash variable var _ = require('lodash-contrib'); // Declare and object and rename its keyvar obj = _.renameKeys( { 1 : "Geeks", 2 : "Computer_Science_Portal" }, { 1 : "g", 2 : "c" }); console.log("Generated Object: ", obj);
Output:
Generated Object: Object {c: "Computer_Science_Portal", g: "Geeks"}
Example 2:
// Defining underscore lodash variable var _ = require('lodash-contrib'); // Declare and object and rename its keyvar obj = _.renameKeys( { 1 : "Geeks", 2 : "Computer_Science_Portal", 3 : "Geeks" }, { 1 : "g", 2 : "c", 3 : "g" }); console.log("Generated Object: ", obj);
Output:
Generated Object: Object {c: "Computer_Science_Portal", g: "Geeks"}
Example 3:
// Defining underscore lodash variable var _ = require('lodash-contrib'); // Declare and object and rename its keyvar obj = _.renameKeys( [ "Computer_Science_Portal", "Geeks" ], { 0 : "a", 1 : "b", 3 : "g" }); console.log("Generated Object: ", obj);
Output:
Generated Object: Object {c: "Computer_Science_Portal", g: "Geeks"}
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
How to filter object array based on attributes?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 25300,
"s": 25272,
"text": "\n30 Sep, 2020"
},
{
"code": null,
"e": 25490,
"s": 25300,
"text": "The Lodash _.renameKeys() method takes an object and a mapping object and returns a new object where the keys of the given object have been renamed as the corresponding value in the keyMap."
},
{
"code": null,
"e": 25498,
"s": 25490,
"text": "Syntax:"
},
{
"code": null,
"e": 25525,
"s": 25498,
"text": "_.renameKeys(obj, mapObj);"
},
{
"code": null,
"e": 25611,
"s": 25525,
"text": "Parameters: This method accept two parameters as mentioned above and described below:"
},
{
"code": null,
"e": 25653,
"s": 25611,
"text": "obj: Given object to create a new object."
},
{
"code": null,
"e": 25702,
"s": 25653,
"text": "mapObj: Given map object to create a new object."
},
{
"code": null,
"e": 25756,
"s": 25702,
"text": "Return Value: This method returns a generated object."
},
{
"code": null,
"e": 25941,
"s": 25756,
"text": "Note: This will not work in normal JavaScript because it requires the lodash.js contrib library to be installed. Lodash.js contrib library can be installed using the following command:"
},
{
"code": null,
"e": 25968,
"s": 25941,
"text": "npm install lodash-contrib"
},
{
"code": null,
"e": 25979,
"s": 25968,
"text": "Example 1:"
},
{
"code": "// Defining underscore lodash variable var _ = require('lodash-contrib'); // Declare and object and rename its keyvar obj = _.renameKeys( { 1 : \"Geeks\", 2 : \"Computer_Science_Portal\" }, { 1 : \"g\", 2 : \"c\" }); console.log(\"Generated Object: \", obj);",
"e": 26259,
"s": 25979,
"text": null
},
{
"code": null,
"e": 26267,
"s": 26259,
"text": "Output:"
},
{
"code": null,
"e": 26335,
"s": 26267,
"text": "Generated Object: Object {c: \"Computer_Science_Portal\", g: \"Geeks\"}"
},
{
"code": null,
"e": 26346,
"s": 26335,
"text": "Example 2:"
},
{
"code": "// Defining underscore lodash variable var _ = require('lodash-contrib'); // Declare and object and rename its keyvar obj = _.renameKeys( { 1 : \"Geeks\", 2 : \"Computer_Science_Portal\", 3 : \"Geeks\" }, { 1 : \"g\", 2 : \"c\", 3 : \"g\" }); console.log(\"Generated Object: \", obj);",
"e": 26630,
"s": 26346,
"text": null
},
{
"code": null,
"e": 26638,
"s": 26630,
"text": "Output:"
},
{
"code": null,
"e": 26706,
"s": 26638,
"text": "Generated Object: Object {c: \"Computer_Science_Portal\", g: \"Geeks\"}"
},
{
"code": null,
"e": 26717,
"s": 26706,
"text": "Example 3:"
},
{
"code": "// Defining underscore lodash variable var _ = require('lodash-contrib'); // Declare and object and rename its keyvar obj = _.renameKeys( [ \"Computer_Science_Portal\", \"Geeks\" ], { 0 : \"a\", 1 : \"b\", 3 : \"g\" }); console.log(\"Generated Object: \", obj);",
"e": 26995,
"s": 26717,
"text": null
},
{
"code": null,
"e": 27003,
"s": 26995,
"text": "Output:"
},
{
"code": null,
"e": 27071,
"s": 27003,
"text": "Generated Object: Object {c: \"Computer_Science_Portal\", g: \"Geeks\"}"
},
{
"code": null,
"e": 27089,
"s": 27071,
"text": "JavaScript-Lodash"
},
{
"code": null,
"e": 27100,
"s": 27089,
"text": "JavaScript"
},
{
"code": null,
"e": 27117,
"s": 27100,
"text": "Web Technologies"
},
{
"code": null,
"e": 27215,
"s": 27117,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27224,
"s": 27215,
"text": "Comments"
},
{
"code": null,
"e": 27237,
"s": 27224,
"text": "Old Comments"
},
{
"code": null,
"e": 27298,
"s": 27237,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27339,
"s": 27298,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 27393,
"s": 27339,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 27433,
"s": 27393,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27481,
"s": 27433,
"text": "How to filter object array based on attributes?"
},
{
"code": null,
"e": 27523,
"s": 27481,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 27556,
"s": 27523,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27599,
"s": 27556,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 27661,
"s": 27599,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
\color - Tex Command | \color - Used to specify color for mathematics.
{ \color #1 #2 }
\color command is used to specify color for mathematics.
\color{red}{ \frac{1+\sqrt{5}}{2} }
1+52
\color{#0000FF}AB
AB
\color{red}{ \frac{1+\sqrt{5}}{2} }
1+52
\color{red}{ \frac{1+\sqrt{5}}{2} }
\color{#0000FF}AB
AB
\color{#0000FF}AB
14 Lectures
52 mins
Ashraf Said
11 Lectures
1 hours
Ashraf Said
9 Lectures
1 hours
Emenwa Global, Ejike IfeanyiChukwu
29 Lectures
2.5 hours
Mohammad Nauman
14 Lectures
1 hours
Daniel Stern
15 Lectures
47 mins
Nishant Kumar
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 8034,
"s": 7986,
"text": "\\color - Used to specify color for mathematics."
},
{
"code": null,
"e": 8051,
"s": 8034,
"text": "{ \\color #1 #2 }"
},
{
"code": null,
"e": 8108,
"s": 8051,
"text": "\\color command is used to specify color for mathematics."
},
{
"code": null,
"e": 8178,
"s": 8108,
"text": "\n\\color{red}{ \\frac{1+\\sqrt{5}}{2} }\n\n1+52\n\n\n\\color{#0000FF}AB\n\nAB\n\n\n"
},
{
"code": null,
"e": 8222,
"s": 8178,
"text": "\\color{red}{ \\frac{1+\\sqrt{5}}{2} }\n\n1+52\n\n"
},
{
"code": null,
"e": 8258,
"s": 8222,
"text": "\\color{red}{ \\frac{1+\\sqrt{5}}{2} }"
},
{
"code": null,
"e": 8282,
"s": 8258,
"text": "\\color{#0000FF}AB\n\nAB\n\n"
},
{
"code": null,
"e": 8300,
"s": 8282,
"text": "\\color{#0000FF}AB"
},
{
"code": null,
"e": 8332,
"s": 8300,
"text": "\n 14 Lectures \n 52 mins\n"
},
{
"code": null,
"e": 8345,
"s": 8332,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8378,
"s": 8345,
"text": "\n 11 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8391,
"s": 8378,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8423,
"s": 8391,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8459,
"s": 8423,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 8494,
"s": 8459,
"text": "\n 29 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8511,
"s": 8494,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 8544,
"s": 8511,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8558,
"s": 8544,
"text": " Daniel Stern"
},
{
"code": null,
"e": 8590,
"s": 8558,
"text": "\n 15 Lectures \n 47 mins\n"
},
{
"code": null,
"e": 8605,
"s": 8590,
"text": " Nishant Kumar"
},
{
"code": null,
"e": 8612,
"s": 8605,
"text": " Print"
},
{
"code": null,
"e": 8623,
"s": 8612,
"text": " Add Notes"
}
] |
SQLite - Logical Operators | Consider COMPANY table with the following records −
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
Following are simple examples showing the usage of SQLite Logical Operators. Following SELECT statement lists down all the records where AGE is greater than or equal to 25 and salary is greater than or equal to 65000.00.
sqlite> SELECT * FROM COMPANY WHERE AGE >= 25 AND SALARY >= 65000;
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
Following SELECT statement lists down all the records where AGE is greater than or equal to 25 OR salary is greater than or equal to 65000.00.
sqlite> SELECT * FROM COMPANY WHERE AGE >= 25 OR SALARY >= 65000;
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
Following SELECT statement lists down all the records where AGE is not NULL which means all the records because none of the record has AGE equal to NULL.
sqlite> SELECT * FROM COMPANY WHERE AGE IS NOT NULL;
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
Following SELECT statement lists down all the records where NAME starts with 'Ki', does not matter what comes after 'Ki'.
sqlite> SELECT * FROM COMPANY WHERE NAME LIKE 'Ki%';
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
6 Kim 22 South-Hall 45000.0
Following SELECT statement lists down all the records where NAME starts with 'Ki', does not matter what comes after 'Ki'.
sqlite> SELECT * FROM COMPANY WHERE NAME GLOB 'Ki*';
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
6 Kim 22 South-Hall 45000.0
Following SELECT statement lists down all the records where AGE value is either 25 or 27.
sqlite> SELECT * FROM COMPANY WHERE AGE IN ( 25, 27 );
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
2 Allen 25 Texas 15000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
Following SELECT statement lists down all the records where AGE value is neither 25 nor 27.
sqlite> SELECT * FROM COMPANY WHERE AGE NOT IN ( 25, 27 );
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
3 Teddy 23 Norway 20000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
Following SELECT statement lists down all the records where AGE value is in BETWEEN 25 AND 27.
sqlite> SELECT * FROM COMPANY WHERE AGE BETWEEN 25 AND 27;
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
2 Allen 25 Texas 15000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
Following SELECT statement makes use of SQL sub-query where sub-query finds all the records with AGE field having SALARY > 65000 and later WHERE clause is being used along with EXISTS operator to list down all the records where AGE from the outside query exists in the result returned by the sub-query.
sqlite> SELECT AGE FROM COMPANY
WHERE EXISTS (SELECT AGE FROM COMPANY WHERE SALARY > 65000);
AGE
----------
32
25
23
25
27
22
24
Following SELECT statement makes use of SQL sub-query where subquery finds all the records with AGE field having SALARY > 65000 and later WHERE clause is being used along with > operator to list down all the records where AGE from the outside query is greater than the age in the result returned by the sub-query.
sqlite> SELECT * FROM COMPANY
WHERE AGE > (SELECT AGE FROM COMPANY WHERE SALARY > 65000);
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
25 Lectures
4.5 hours
Sandip Bhattacharya
17 Lectures
1 hours
Laurence Svekis
5 Lectures
51 mins
Vinay Kumar
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2690,
"s": 2638,
"text": "Consider COMPANY table with the following records −"
},
{
"code": null,
"e": 3196,
"s": 2690,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0"
},
{
"code": null,
"e": 3417,
"s": 3196,
"text": "Following are simple examples showing the usage of SQLite Logical Operators. Following SELECT statement lists down all the records where AGE is greater than or equal to 25 and salary is greater than or equal to 65000.00."
},
{
"code": null,
"e": 3711,
"s": 3417,
"text": "sqlite> SELECT * FROM COMPANY WHERE AGE >= 25 AND SALARY >= 65000;\n\nID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0"
},
{
"code": null,
"e": 3855,
"s": 3711,
"text": "Following SELECT statement lists down all the records where AGE is greater than or equal to 25 OR salary is greater than or equal to 65000.00."
},
{
"code": null,
"e": 4260,
"s": 3855,
"text": "sqlite> SELECT * FROM COMPANY WHERE AGE >= 25 OR SALARY >= 65000;\n\nID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0"
},
{
"code": null,
"e": 4414,
"s": 4260,
"text": "Following SELECT statement lists down all the records where AGE is not NULL which means all the records because none of the record has AGE equal to NULL."
},
{
"code": null,
"e": 4975,
"s": 4414,
"text": "sqlite> SELECT * FROM COMPANY WHERE AGE IS NOT NULL;\n\nID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0"
},
{
"code": null,
"e": 5097,
"s": 4975,
"text": "Following SELECT statement lists down all the records where NAME starts with 'Ki', does not matter what comes after 'Ki'."
},
{
"code": null,
"e": 5321,
"s": 5097,
"text": "sqlite> SELECT * FROM COMPANY WHERE NAME LIKE 'Ki%';\n\nID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n6 Kim 22 South-Hall 45000.0"
},
{
"code": null,
"e": 5443,
"s": 5321,
"text": "Following SELECT statement lists down all the records where NAME starts with 'Ki', does not matter what comes after 'Ki'."
},
{
"code": null,
"e": 5667,
"s": 5443,
"text": "sqlite> SELECT * FROM COMPANY WHERE NAME GLOB 'Ki*';\n\nID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n6 Kim 22 South-Hall 45000.0"
},
{
"code": null,
"e": 5757,
"s": 5667,
"text": "Following SELECT statement lists down all the records where AGE value is either 25 or 27."
},
{
"code": null,
"e": 6095,
"s": 5757,
"text": "sqlite> SELECT * FROM COMPANY WHERE AGE IN ( 25, 27 );\n\nID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n2 Allen 25 Texas 15000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0"
},
{
"code": null,
"e": 6187,
"s": 6095,
"text": "Following SELECT statement lists down all the records where AGE value is neither 25 nor 27."
},
{
"code": null,
"e": 6585,
"s": 6187,
"text": "sqlite> SELECT * FROM COMPANY WHERE AGE NOT IN ( 25, 27 );\n\nID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n3 Teddy 23 Norway 20000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0"
},
{
"code": null,
"e": 6680,
"s": 6585,
"text": "Following SELECT statement lists down all the records where AGE value is in BETWEEN 25 AND 27."
},
{
"code": null,
"e": 7022,
"s": 6680,
"text": "sqlite> SELECT * FROM COMPANY WHERE AGE BETWEEN 25 AND 27;\n\nID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n2 Allen 25 Texas 15000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0"
},
{
"code": null,
"e": 7325,
"s": 7022,
"text": "Following SELECT statement makes use of SQL sub-query where sub-query finds all the records with AGE field having SALARY > 65000 and later WHERE clause is being used along with EXISTS operator to list down all the records where AGE from the outside query exists in the result returned by the sub-query."
},
{
"code": null,
"e": 7459,
"s": 7325,
"text": "sqlite> SELECT AGE FROM COMPANY \n WHERE EXISTS (SELECT AGE FROM COMPANY WHERE SALARY > 65000);\n\nAGE\n----------\n32\n25\n23\n25\n27\n22\n24"
},
{
"code": null,
"e": 7773,
"s": 7459,
"text": "Following SELECT statement makes use of SQL sub-query where subquery finds all the records with AGE field having SALARY > 65000 and later WHERE clause is being used along with > operator to list down all the records where AGE from the outside query is greater than the age in the result returned by the sub-query."
},
{
"code": null,
"e": 8038,
"s": 7773,
"text": "sqlite> SELECT * FROM COMPANY \n WHERE AGE > (SELECT AGE FROM COMPANY WHERE SALARY > 65000);\n\nID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0"
},
{
"code": null,
"e": 8073,
"s": 8038,
"text": "\n 25 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 8094,
"s": 8073,
"text": " Sandip Bhattacharya"
},
{
"code": null,
"e": 8127,
"s": 8094,
"text": "\n 17 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8144,
"s": 8127,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 8175,
"s": 8144,
"text": "\n 5 Lectures \n 51 mins\n"
},
{
"code": null,
"e": 8188,
"s": 8175,
"text": " Vinay Kumar"
},
{
"code": null,
"e": 8195,
"s": 8188,
"text": " Print"
},
{
"code": null,
"e": 8206,
"s": 8195,
"text": " Add Notes"
}
] |
How to sort grouped Pandas dataframe by group size ? - GeeksforGeeks | 28 Apr, 2021
In this article, we will discuss how to sort grouped data based on group size in Pandas.
Here we will pass the inputs through the list as a dictionary data structure.
groupby(): groupby() is used to group the data based on the column values.
size(): This is used to get the size of the data frame.
sort_values(): This function sorts a data frame in Ascending or Descending order of passed Column.
The task is straightforward, for a given dataframe first we need to group by any column as per requirement and then arrange the grouped values of the column according to their size. By size here we mean how many times a value has appeared in a column or its frequency.
Example 1:
Python3
# importing pandas module for dataframeimport pandas as pd # creating a dataframe with student# name and subject dataframe1 = pd.DataFrame({'student_name': ['bobby', 'ojaswi', 'gnanesh', 'rohith', 'karthik', 'sudheer', 'vani'], 'subjects': ['dbms', 'python', 'dbms', 'oops', 'oops', 'oops', 'dbms']}) # display dataframeprint(dataframe1) # group the data on subjects column based on# size and sort in descending ordera = dataframe1.groupby('subjects').size().sort_values(ascending=False) # group the data on subjects column based on # size and sort in ascending orderb = dataframe1.groupby('subjects').size().sort_values(ascending=True) print(a, b)
Output:
Example 2:
Python3
# importing pandas module for dataframeimport pandas as pd # creating a dataframe with student name# , subject and addressdataframe1 = pd.DataFrame({'student_name': ['bobby', 'ojaswi', 'gnanesh', 'rohith', 'karthik', 'sudheer', 'vani'], 'subjects': ['dbms', 'python', 'dbms', 'oops', 'oops', 'oops', 'dbms'], 'address': ['ponnur', 'ponnur', 'hyd', 'tenali', 'tenali', 'hyd', 'patna']}) # display dataframeprint(dataframe1) # group the data on address column based # on size and sort in descending ordera = dataframe1.groupby('address').size().sort_values(ascending=False) # group the data on address column based # on size and sort in ascending orderb = dataframe1.groupby('address').size().sort_values(ascending=True) print(a, b)
Output:
We can also group the multiple columns. The syntax remains the same, but we need to pass the multiple columns in a list and pass the list in groupby()
Syntax:
dataframe.groupby([column1,column2,.column n]).size().sort_values(ascending=True)
Example 3:
Python3
# importing pandas module for dataframeimport pandas as pd # creating a dataframe with student# name , subject and addressdataframe1 = pd.DataFrame({'student_name': ['bobby', 'ojaswi', 'gnanesh', 'rohith', 'karthik', 'sudheer', 'vani'], 'subjects': ['dbms', 'python', 'dbms', 'oops', 'oops', 'oops', 'dbms'], 'address': ['ponnur', 'ponnur', 'hyd', 'tenali', 'tenali', 'hyd', 'patna']}) # display dataframeprint(dataframe1) # group the data on address and subjects# column based on size and sort in descending# ordera = dataframe1.groupby(['address', 'subjects'] ).size().sort_values(ascending=False) # group the data on address and subjects# column based on size and sort in ascending# orderb = dataframe1.groupby(['address', 'subjects'] ).size().sort_values(ascending=True) print(a, b)
Output:
Picked
Python pandas-dataFrame
Python pandas-groupby
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 ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
Defaultdict in Python
Selecting rows in pandas DataFrame based on conditions
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n28 Apr, 2021"
},
{
"code": null,
"e": 24381,
"s": 24292,
"text": "In this article, we will discuss how to sort grouped data based on group size in Pandas."
},
{
"code": null,
"e": 24459,
"s": 24381,
"text": "Here we will pass the inputs through the list as a dictionary data structure."
},
{
"code": null,
"e": 24534,
"s": 24459,
"text": "groupby(): groupby() is used to group the data based on the column values."
},
{
"code": null,
"e": 24590,
"s": 24534,
"text": "size(): This is used to get the size of the data frame."
},
{
"code": null,
"e": 24689,
"s": 24590,
"text": "sort_values(): This function sorts a data frame in Ascending or Descending order of passed Column."
},
{
"code": null,
"e": 24958,
"s": 24689,
"text": "The task is straightforward, for a given dataframe first we need to group by any column as per requirement and then arrange the grouped values of the column according to their size. By size here we mean how many times a value has appeared in a column or its frequency."
},
{
"code": null,
"e": 24969,
"s": 24958,
"text": "Example 1:"
},
{
"code": null,
"e": 24977,
"s": 24969,
"text": "Python3"
},
{
"code": "# importing pandas module for dataframeimport pandas as pd # creating a dataframe with student# name and subject dataframe1 = pd.DataFrame({'student_name': ['bobby', 'ojaswi', 'gnanesh', 'rohith', 'karthik', 'sudheer', 'vani'], 'subjects': ['dbms', 'python', 'dbms', 'oops', 'oops', 'oops', 'dbms']}) # display dataframeprint(dataframe1) # group the data on subjects column based on# size and sort in descending ordera = dataframe1.groupby('subjects').size().sort_values(ascending=False) # group the data on subjects column based on # size and sort in ascending orderb = dataframe1.groupby('subjects').size().sort_values(ascending=True) print(a, b)",
"e": 25814,
"s": 24977,
"text": null
},
{
"code": null,
"e": 25822,
"s": 25814,
"text": "Output:"
},
{
"code": null,
"e": 25833,
"s": 25822,
"text": "Example 2:"
},
{
"code": null,
"e": 25841,
"s": 25833,
"text": "Python3"
},
{
"code": "# importing pandas module for dataframeimport pandas as pd # creating a dataframe with student name# , subject and addressdataframe1 = pd.DataFrame({'student_name': ['bobby', 'ojaswi', 'gnanesh', 'rohith', 'karthik', 'sudheer', 'vani'], 'subjects': ['dbms', 'python', 'dbms', 'oops', 'oops', 'oops', 'dbms'], 'address': ['ponnur', 'ponnur', 'hyd', 'tenali', 'tenali', 'hyd', 'patna']}) # display dataframeprint(dataframe1) # group the data on address column based # on size and sort in descending ordera = dataframe1.groupby('address').size().sort_values(ascending=False) # group the data on address column based # on size and sort in ascending orderb = dataframe1.groupby('address').size().sort_values(ascending=True) print(a, b)",
"e": 26825,
"s": 25841,
"text": null
},
{
"code": null,
"e": 26833,
"s": 26825,
"text": "Output:"
},
{
"code": null,
"e": 26984,
"s": 26833,
"text": "We can also group the multiple columns. The syntax remains the same, but we need to pass the multiple columns in a list and pass the list in groupby()"
},
{
"code": null,
"e": 26992,
"s": 26984,
"text": "Syntax:"
},
{
"code": null,
"e": 27074,
"s": 26992,
"text": "dataframe.groupby([column1,column2,.column n]).size().sort_values(ascending=True)"
},
{
"code": null,
"e": 27085,
"s": 27074,
"text": "Example 3:"
},
{
"code": null,
"e": 27093,
"s": 27085,
"text": "Python3"
},
{
"code": "# importing pandas module for dataframeimport pandas as pd # creating a dataframe with student# name , subject and addressdataframe1 = pd.DataFrame({'student_name': ['bobby', 'ojaswi', 'gnanesh', 'rohith', 'karthik', 'sudheer', 'vani'], 'subjects': ['dbms', 'python', 'dbms', 'oops', 'oops', 'oops', 'dbms'], 'address': ['ponnur', 'ponnur', 'hyd', 'tenali', 'tenali', 'hyd', 'patna']}) # display dataframeprint(dataframe1) # group the data on address and subjects# column based on size and sort in descending# ordera = dataframe1.groupby(['address', 'subjects'] ).size().sort_values(ascending=False) # group the data on address and subjects# column based on size and sort in ascending# orderb = dataframe1.groupby(['address', 'subjects'] ).size().sort_values(ascending=True) print(a, b)",
"e": 28204,
"s": 27093,
"text": null
},
{
"code": null,
"e": 28212,
"s": 28204,
"text": "Output:"
},
{
"code": null,
"e": 28219,
"s": 28212,
"text": "Picked"
},
{
"code": null,
"e": 28243,
"s": 28219,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 28265,
"s": 28243,
"text": "Python pandas-groupby"
},
{
"code": null,
"e": 28279,
"s": 28265,
"text": "Python-pandas"
},
{
"code": null,
"e": 28286,
"s": 28279,
"text": "Python"
},
{
"code": null,
"e": 28384,
"s": 28286,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28416,
"s": 28384,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28458,
"s": 28416,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28514,
"s": 28458,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28556,
"s": 28514,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28587,
"s": 28556,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28609,
"s": 28587,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28664,
"s": 28609,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 28703,
"s": 28664,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28732,
"s": 28703,
"text": "Create a directory in Python"
}
] |
Introduction to Quantum Programming | by Quentin Truong | Towards Data Science | Quantum computers exist! And so does quantum programming! In this article, I’ll walk you through everything you need to know to get started with quantum programming. I’ll start off with some context about how quantum computers differ from computers like your laptop, then explain the fundamentals of quantum programming, and finish with how you can run programs on a real quantum computer for free today.
Before we begin, please note that this article is intended for people who want to learn the full technical details of quantum programming. This article builds up from the mathematical foundation of qubits, quantum gates, and quantum circuit diagrams. This article will not explain quantum algorithms or their advantages, as those topics deserve their own articles.
Since we will be walking through the underlying math of quantum programming, readers will need to know what a vector, matrix, linear combination, and complex number is. I recommend 3Blue1Brown for learning linear algebra, and BetterExplained for learning what a complex number is.
Let’s start off by understanding what quantum computers really are and how they are different from other computers.
A quantum computer is a machine that uses quantum mechanics to perform calculations.
So how is this different from other computers? Well, a computer, in its most basic form, is simply a machine that performs calculations. There’s many different types of computers. In the early days of computers, we actually had mechanical computers — Charles Babbage designed such a machine to perform general-purpose calculations in 1837. Nowadays, our computers are based on digital electronics and operate using bits and logic gates. A quantum computer, conversely, uses quantum mechanics to perform computation. Rather than bits and logic gates, quantum computers use qubits and quantum gates.
So what is a qubit and a quantum gate? Physically, they can be any one of many different things — Google, IBM, Microsoft, and Rigetti all have their own implementations of qubits and quantum gates. For now, we won’t worry about the physical nature of qubits and quantum gates because it is not necessary when first learning about quantum programming.
Before we begin, I highly recommend that you approach quantum programming on a clean mental slate. Don’t go looking for how to declare and set variables, loop over code, create functions, etc. Any preconceptions you have about programming will probably not be useful. Quantum programming is not simply some way to make our existing programs run faster — quantum programming is fundamentally different from contemporary programming.
Let’s start with what a qubit is.
A qubit is a vector of two complex numbers with unit length.
Let’s walk through why qubits are this way and what it really means. Qubits are quite different from bits. For starters, a bit is either 0 or 1. There are no probabilities here, it’s either known to be a 0 or it’s known to be a 1. A qubit, conversely, is inherently probabilistic, meaning that two identical qubits may have different values once measured! Take a moment to really consider the gravity of this. This means that quantum computing is inherently probabilistic.
Now, here’s a second key difference. With bits, we can read the bit as many times as we want without affecting the state of the bit. But with qubits, once measured, it decoheres (loses its quantum properties) and collapses to one of two measurable states (hence the ‘bit’ in ‘qubit’). Hence, we cannot ‘unmeasure’ a qubit; once measured, the quantum nature is destroyed and cannot be recovered. We quantify the probabilistic nature of measuring a qubit using two numbers: |α|2, the probability that the qubit will be measured as 0, and |β|2, the probability that the qubit will be measured as 1.
Although |α|2 and |β|2 reflect the probabilities of what the qubit will be measured as, we think of the internal state of a qubit as two ‘probability amplitudes’, α and β. These are complex numbers which define a superposition between 0 and 1 (a superposition is a linear combination) and cannot be measured.
In other words, we think of a qubit as a vector of two complex numbers with unit length (length of the vector is equal to 1). We can concisely express this as math as shown in the following picture (the vector containing the alpha and beta is the qubit; the bar above alpha and beta denotes the complex conjugate):
To recap, qubits are a vector of two complex numbers, α and β, where the vector has unit length. The probability that the qubit will be measured as 0 is equal to the magnitude squared of α, |α|2. The probability that the qubit will be measured as 1 is equal to the magnitude squared of β, |β|2. A qubit’s state, α and β, cannot be measured. Only the value that a qubit collapses into can be measured.
We often denote qubits using Dirac notation, also known as Bra-ket notation. This notation is just a convenient way to write vectors. The bra represents row vectors and is denoted ⟨ ∣; the ket represents column vectors and is denoted ∣ ⟩. For example, we can write the ‘0’ and ‘1’ states of a qubit in Bra-ket notation as follows (be careful not to confuse what’s inside the bra/ket with what’s inside the vector!):
Qubits can either be in pure states or mixed states. If the state of a qubit can be fully described using a linear combination of ∣0⟩ and ∣1⟩, then we say its in a pure state. We often denote pure state qubits using the following notation:
Here are some examples of pure state qubits and common shorthand for denoting them.
Other qubits require mixtures of pure states to fully describe them, so we call them mixed state qubits. In other words, a mixed state qubit is described by a probability distribution over pure states. We’ll see an example of mixed state qubits later in this article (I’ll point it out).
Up until now, we have only defined the state of a single qubit. What does the combined state of multiple qubits look like?
The combined state of multiple qubits is the tensor product of all the qubits.
Don’t worry if you don’t know what a tensor product is; we’ll walk through an example (⊗ is the symbol for the tensor product operation).
In general, we can tensor product any two matrices by following two steps:
Scalar multiply each element in the first matrix by the entire second matrixCombine the resulting matrices according to the original position of their elements
Scalar multiply each element in the first matrix by the entire second matrix
Combine the resulting matrices according to the original position of their elements
Here’s a second example of how it works for 2-dimensional matrices:
We can also denote multiple qubits in Bra-ket notation as ∣0⟩⊗∣1⟩, for example. As a shorthand, we can omit the ⊗ and simply write ∣0⟩∣1⟩. As an even shorter shorthand, we can write just a single ket, ∣01⟩.
Now let’s consider what a quantum gate is.
A quantum gate is a unitary matrix.
Let’s get some context for why quantum gates are unitary matrices. First of all, quantum gates will be implemented by physical devices, and so they must abide by the laws of quantum physics. One relevant law of physics is that no information is ever lost when transitioning between points in the past and the future1. This is known as unitarity. Since our quantum gates define how we transition between states, they too must abide by unitarity.
Secondly, note that our quantum gates will be applied to qubits. We learned earlier that qubits are really just vectors, and so that means quantum gates must somehow operate on vectors. Fortunately, we recall that a matrix is actually just a linear transformation for vectors!
Combining these two ideas, we think of quantum gates as unitary matrices. A unitary matrix is any square matrix of complex numbers such that the conjugate transpose is equal to its inverse. As a quick refresher, the conjugate transpose of a matrix is found by taking the conjugate of each element in the matrix (a + bi → a — bi), and then taking the transpose of the matrix (element ij → element ji). We typically denote the conjugate transpose by the dagger, †.
A key observation about unitary matrices is that they preserve the norm (length of a vector). Suppose we allowed gates that changed the norm, then our qubit’s probabilities may sum to something other than one! That doesn’t make sense since the sum of all probabilities must always be equal to one.
Also notice that, by definition, unitary matrices have an inverse. One implication of this is that we cannot ‘assign’ qubits to arbitrary states. To understand why not, let’s pretend that we did have a quantum gate that could ‘assign’ values, hence, convert any vector of two complex numbers into a specific vector of two complex numbers. This quantum gate would have some underlying representation as a unitary matrix, and that matrix would have an inverse capable of converting a specific vector back into whatever state the qubit was before the operation! But the qubit could have been in any state before the operation and there’s no way to know which! Hence, we cannot ‘assign’ qubits to an arbitrary state. At a higher level, the fact that all quantum gates are invertible is why we often think of quantum computing as a form of reversible computing.
Lastly, notice that because our quantum gates are unitary matrices, they are square by definition, and so our quantum gates must have an equal number of input and output qubits (because square matrices map n standard basis vectors to n columns)! This is quite different from most logic gates; for example, the AND gate takes two inputs and produces one output.
Now that we know a little bit about what we are working with, let’s consider an example, the Hadamard gate, H.
We can check that H is unitary by checking that the conjugate transpose is equal to its inverse, or in other words, that H multiplied by its conjugate transpose is equal to the Identity matrix:
Another important quantum gate is the Controlled NOT gate, also known as CNOT. CNOT acts on two qubits, a control qubit and a target qubit. We can think of CNOT as an ‘if statement’ — if the control qubit is equal to 1, then CNOT applies NOT (the inverse gate) to the target qubit (hence the name, Controlled NOT).
Here is the matrix representing CNOT. This matrix treats the control qubit as the rightmost value inside the ket and the target qubit as the leftmost value.
Let’s see its effect on ∣00⟩.
In this example, we see that CNOT doesn’t modify the value of ∣00⟩. And this is the expected behavior, as CNOT only inverts the target if the control is 1.
Let’s see its effect on ∣01⟩.
Here, we can see that the control is equal to 1, so CNOT inverts the target. Hence, the result is ∣11⟩.
Try working out the other two cases, ∣10⟩ and ∣11⟩. You should find that CNOT has the following behavior:
∣00⟩ -> ∣00⟩
∣01⟩ -> ∣11⟩
∣10⟩ -> ∣10⟩
∣11⟩ -> ∣01⟩
And notice that this is precisely the behavior of applying NOT to the target bit when the control bit is 1.
To recap, we can think of quantum gates as unitary matrices. This unitarity enforces the constraint that a qubit’s probabilities sum to one and causes quantum computing to be reversible. Since unitary matrices are square, we find that quantum gates must have an equal number of input and output qubits. We learned about Hadamard and CNOT, which are two important quantum gates. There exist many more quantum gates.
Now that we know the basics of qubits and quantum gates, let’s see our first quantum circuit diagram.
Quantum circuit diagrams are how we think about quantum ‘programs’. We define the qubits as rows, and we apply quantum gates sequentially from left to right.
Let’s walk through every part of this diagram. First, we have two qubits. Each row corresponds to a qubit. The top row corresponds to the qubit named x0 and the bottom corresponds to the qubit named x1. We consider x0 to be the 0th qubit because we start counting from 0 (the same as in the rest of programming). We write x0 : ∣0⟩ and x1 : ∣0⟩ to mean that x0 and x1 start off in the state ∣0⟩.
The H is the Hadamard gate and is being applied to qubit x0. The ●-⊕ is the CNOT gate, the ● is the control qubit, and the ⊕ is the target qubit. The - is just to help us see which two qubits are affected. In other words, we are applying CNOT where the control is qubit x0 and the target is x1. Note, the order that we apply these gates is important. In this diagram, we applied H first and CNOT second.
The quantum circuit diagram is just one representation of our program. It helps us think about our quantum computation, but other representations can also be useful. We can translate our diagram into a string of symbols, which helps us when preparing to write it as computer code. Having it in string form also makes it easy to translate into the underlying math. This math will tell us the expected output of our program.
Let’s start off by converting our diagram into a string of symbols. Rather than writing our qubits as rows, we’ll use Bra-ket notation. The 0th qubit will be the rightmost qubit in ∣00⟩, just like when writing out binary numbers2. This means that qubit x1 is the leftmost qubit in ∣00⟩. (Note, the quantum physics people tend to reverse this ordering3. Always check the qubit ordering as it’s an incredibly common source of errors.)
We also need to translate the gates. Since we are applying H to qubit x0 and not applying anything to qubit x1 (which is equivalent to applying the Identity gate, I), we’ll write this as (I⊗H). Lastly, we translate the CNOT, specifying which qubit is the control and which is the target. The result is CNOT[control=0, target=1] (I⊗H) ∣00⟩ (note, this string is read from right-to-left). Great! This will be useful when writing the code that’ll be run on the quantum computer.
Having the string representation of the quantum circuit diagram makes it easy to translate our program into the underlying math. There are three pieces, the CNOT[control=0, target=1], (I⊗H), and ∣00⟩. Each piece can be translated into a matrix, as shown in the first row of the following image:
We can even multiply out our matrices to find the resulting state vector, as shown above. This state vector is the expected state of our two qubits after the quantum computation has completed. Alternatively, we can think of it as the output of our program. It tells us the probability amplitudes for each measurable state.
Also, remember our mixed state qubits? Notice that we can’t actually write qubit x0 and qubit x1 in pure states anymore because there isn’t any way to break up the vector with a tensor product. So our qubits are in a mixed state!
What if we measured our qubits now? What would we receive? We can find out by decomposing the state vector into each of the measurable states. We’ll measure our qubits in the standard basis, also known as ∣0⟩ and ∣1⟩ (there are other bases we could measure in, but don't worry about that for now). Hence, our two qubit system’s measurable states are ∣00⟩, ∣01⟩, ∣10⟩, and ∣11⟩.
We can determine the probabilities of the measured values in the same way we used|α|2 to determine the probability of ∣0⟩ for a single qubit. Since ∣01⟩ and ∣10⟩ have a 0 probability amplitude, we know that we will never measure that state. And we will measure both ∣00⟩ and ∣11⟩ with probability (1/sqrt(2))2 = 1/2.
Now, suppose we were to separate these two qubits by a large distance, and then we measured either one. The instant that we measured it, we would know the value of the other qubit too! This is because we know that the qubits can only be ∣00⟩ or ∣11⟩.
This is what Einstein referred to as ‘spooky action at a distance’, also known as quantum entanglement. We think of the information as being correlated rather than traveling. If it were traveling, then it could potentially travel faster than light, which breaks the laws of physics.
Now that we understand what’s happening under the hood with qubits, quantum gates, and quantum circuit diagrams, let’s see how to run on a real quantum computer. I’ll be using Rigetti’s quantum computer since they are currently giving out free credit to beta users. Alternatively, we can also use IBM’s quantum computer.
Here’s a basic overview of the Rigetti quantum programming process:
Write a Python program that specifies your quantum circuit and any additional code necessaryTest that Python program using a quantum simulatorReserve time on Rigetti’s quantum computerSend your program over to Rigetti’s serversExecute your program on Rigetti’s server (they’ll send your quantum program to their quantum computer for you)
Write a Python program that specifies your quantum circuit and any additional code necessary
Test that Python program using a quantum simulator
Reserve time on Rigetti’s quantum computer
Send your program over to Rigetti’s servers
Execute your program on Rigetti’s server (they’ll send your quantum program to their quantum computer for you)
Here’s the Python version of our quantum circuit diagram from above.
The results will look similar to this:
[(0, 0), (1, 1), (1, 1), (0, 0), (0, 0), (0, 0), (1, 1), (0, 0), (0, 0), (1, 1)][(0, 0), (0, 1), (1, 1), (1, 1), (1, 1), (0, 0), (0, 0), (1, 1), (1, 0), (0, 0)]
The first row corresponds to the simulator, and the results seem reasonable — we get [0, 0] roughly half the time and [1, 1] the remaining times. However, with the real quantum computer, aside from the expected [0, 0] and [1, 1], we also receive [0, 1] and [1, 0]. According to the math, we should only ever receive [0, 0] and [1, 1], so what’s going on?
The issue is that real quantum computers today (July 2019) are still quite error-prone.4 For example, we might see an error rate of 2–3% when trying to initialize qubits to 0. And we might have another 1–2% error rate per single-qubit gate operation, and around 3–4% for two-qubit gate operations. We even have error rates when measuring the qubit! In practice, these errors accumulate and result in incorrect values.
In this article, we learned that quantum computers actually do exist and work today, albeit with rather high error rates. And while the physical implementation of these machines varies substantially across companies, many of the concepts for programming them remain the same.
We think of qubits as a vector of two complex numbers with unit length, and we think of quantum gates as unitary matrices. We remember that quantum computing is probabilistic since two identical qubits could have different values once measured. And since quantum gates are unitary, we know that quantum computing is inherently reversible. At a high level, we can think of quantum programming as applied linear algebra on complex numbers.
We used quantum circuit diagrams to denote our quantum program and then converted it into Python to be run on a real quantum computer.
I hope you learned something, and I would be happy to hear any comments or suggestions you might have!
Q) I googled the matrix form of CNOT and it looks different from yours, why?
A) If you are looking at [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]], its because they reversed the target and control qubit ordering. If you see something other than what I wrote above or in this article, then it’s just wrong.
Q) So we have bits and trits for regular computers, does there exist something similar for qubits?
A) Yes, qutrits. Qubits are part of a two-level quantum system. Qutrits are parts of a three-level quantum system. There’s also qudits, which generalize the number of levels.
[1] L. Susskind, Lecture 1 Quantum Entanglements, Part 1 (2008)
[2] Basis vector ordering in Qiskit (2019), Qiskit
[3] R. Smith, Someone Shouts “01000”! Who is excited? (2017), arxiv
[4] Qubit Quality (2019), Quantum Computing Report | [
{
"code": null,
"e": 576,
"s": 171,
"text": "Quantum computers exist! And so does quantum programming! In this article, I’ll walk you through everything you need to know to get started with quantum programming. I’ll start off with some context about how quantum computers differ from computers like your laptop, then explain the fundamentals of quantum programming, and finish with how you can run programs on a real quantum computer for free today."
},
{
"code": null,
"e": 941,
"s": 576,
"text": "Before we begin, please note that this article is intended for people who want to learn the full technical details of quantum programming. This article builds up from the mathematical foundation of qubits, quantum gates, and quantum circuit diagrams. This article will not explain quantum algorithms or their advantages, as those topics deserve their own articles."
},
{
"code": null,
"e": 1222,
"s": 941,
"text": "Since we will be walking through the underlying math of quantum programming, readers will need to know what a vector, matrix, linear combination, and complex number is. I recommend 3Blue1Brown for learning linear algebra, and BetterExplained for learning what a complex number is."
},
{
"code": null,
"e": 1338,
"s": 1222,
"text": "Let’s start off by understanding what quantum computers really are and how they are different from other computers."
},
{
"code": null,
"e": 1423,
"s": 1338,
"text": "A quantum computer is a machine that uses quantum mechanics to perform calculations."
},
{
"code": null,
"e": 2021,
"s": 1423,
"text": "So how is this different from other computers? Well, a computer, in its most basic form, is simply a machine that performs calculations. There’s many different types of computers. In the early days of computers, we actually had mechanical computers — Charles Babbage designed such a machine to perform general-purpose calculations in 1837. Nowadays, our computers are based on digital electronics and operate using bits and logic gates. A quantum computer, conversely, uses quantum mechanics to perform computation. Rather than bits and logic gates, quantum computers use qubits and quantum gates."
},
{
"code": null,
"e": 2372,
"s": 2021,
"text": "So what is a qubit and a quantum gate? Physically, they can be any one of many different things — Google, IBM, Microsoft, and Rigetti all have their own implementations of qubits and quantum gates. For now, we won’t worry about the physical nature of qubits and quantum gates because it is not necessary when first learning about quantum programming."
},
{
"code": null,
"e": 2804,
"s": 2372,
"text": "Before we begin, I highly recommend that you approach quantum programming on a clean mental slate. Don’t go looking for how to declare and set variables, loop over code, create functions, etc. Any preconceptions you have about programming will probably not be useful. Quantum programming is not simply some way to make our existing programs run faster — quantum programming is fundamentally different from contemporary programming."
},
{
"code": null,
"e": 2838,
"s": 2804,
"text": "Let’s start with what a qubit is."
},
{
"code": null,
"e": 2899,
"s": 2838,
"text": "A qubit is a vector of two complex numbers with unit length."
},
{
"code": null,
"e": 3372,
"s": 2899,
"text": "Let’s walk through why qubits are this way and what it really means. Qubits are quite different from bits. For starters, a bit is either 0 or 1. There are no probabilities here, it’s either known to be a 0 or it’s known to be a 1. A qubit, conversely, is inherently probabilistic, meaning that two identical qubits may have different values once measured! Take a moment to really consider the gravity of this. This means that quantum computing is inherently probabilistic."
},
{
"code": null,
"e": 3968,
"s": 3372,
"text": "Now, here’s a second key difference. With bits, we can read the bit as many times as we want without affecting the state of the bit. But with qubits, once measured, it decoheres (loses its quantum properties) and collapses to one of two measurable states (hence the ‘bit’ in ‘qubit’). Hence, we cannot ‘unmeasure’ a qubit; once measured, the quantum nature is destroyed and cannot be recovered. We quantify the probabilistic nature of measuring a qubit using two numbers: |α|2, the probability that the qubit will be measured as 0, and |β|2, the probability that the qubit will be measured as 1."
},
{
"code": null,
"e": 4277,
"s": 3968,
"text": "Although |α|2 and |β|2 reflect the probabilities of what the qubit will be measured as, we think of the internal state of a qubit as two ‘probability amplitudes’, α and β. These are complex numbers which define a superposition between 0 and 1 (a superposition is a linear combination) and cannot be measured."
},
{
"code": null,
"e": 4592,
"s": 4277,
"text": "In other words, we think of a qubit as a vector of two complex numbers with unit length (length of the vector is equal to 1). We can concisely express this as math as shown in the following picture (the vector containing the alpha and beta is the qubit; the bar above alpha and beta denotes the complex conjugate):"
},
{
"code": null,
"e": 4993,
"s": 4592,
"text": "To recap, qubits are a vector of two complex numbers, α and β, where the vector has unit length. The probability that the qubit will be measured as 0 is equal to the magnitude squared of α, |α|2. The probability that the qubit will be measured as 1 is equal to the magnitude squared of β, |β|2. A qubit’s state, α and β, cannot be measured. Only the value that a qubit collapses into can be measured."
},
{
"code": null,
"e": 5409,
"s": 4993,
"text": "We often denote qubits using Dirac notation, also known as Bra-ket notation. This notation is just a convenient way to write vectors. The bra represents row vectors and is denoted ⟨ ∣; the ket represents column vectors and is denoted ∣ ⟩. For example, we can write the ‘0’ and ‘1’ states of a qubit in Bra-ket notation as follows (be careful not to confuse what’s inside the bra/ket with what’s inside the vector!):"
},
{
"code": null,
"e": 5649,
"s": 5409,
"text": "Qubits can either be in pure states or mixed states. If the state of a qubit can be fully described using a linear combination of ∣0⟩ and ∣1⟩, then we say its in a pure state. We often denote pure state qubits using the following notation:"
},
{
"code": null,
"e": 5733,
"s": 5649,
"text": "Here are some examples of pure state qubits and common shorthand for denoting them."
},
{
"code": null,
"e": 6021,
"s": 5733,
"text": "Other qubits require mixtures of pure states to fully describe them, so we call them mixed state qubits. In other words, a mixed state qubit is described by a probability distribution over pure states. We’ll see an example of mixed state qubits later in this article (I’ll point it out)."
},
{
"code": null,
"e": 6144,
"s": 6021,
"text": "Up until now, we have only defined the state of a single qubit. What does the combined state of multiple qubits look like?"
},
{
"code": null,
"e": 6223,
"s": 6144,
"text": "The combined state of multiple qubits is the tensor product of all the qubits."
},
{
"code": null,
"e": 6361,
"s": 6223,
"text": "Don’t worry if you don’t know what a tensor product is; we’ll walk through an example (⊗ is the symbol for the tensor product operation)."
},
{
"code": null,
"e": 6436,
"s": 6361,
"text": "In general, we can tensor product any two matrices by following two steps:"
},
{
"code": null,
"e": 6596,
"s": 6436,
"text": "Scalar multiply each element in the first matrix by the entire second matrixCombine the resulting matrices according to the original position of their elements"
},
{
"code": null,
"e": 6673,
"s": 6596,
"text": "Scalar multiply each element in the first matrix by the entire second matrix"
},
{
"code": null,
"e": 6757,
"s": 6673,
"text": "Combine the resulting matrices according to the original position of their elements"
},
{
"code": null,
"e": 6825,
"s": 6757,
"text": "Here’s a second example of how it works for 2-dimensional matrices:"
},
{
"code": null,
"e": 7032,
"s": 6825,
"text": "We can also denote multiple qubits in Bra-ket notation as ∣0⟩⊗∣1⟩, for example. As a shorthand, we can omit the ⊗ and simply write ∣0⟩∣1⟩. As an even shorter shorthand, we can write just a single ket, ∣01⟩."
},
{
"code": null,
"e": 7075,
"s": 7032,
"text": "Now let’s consider what a quantum gate is."
},
{
"code": null,
"e": 7111,
"s": 7075,
"text": "A quantum gate is a unitary matrix."
},
{
"code": null,
"e": 7556,
"s": 7111,
"text": "Let’s get some context for why quantum gates are unitary matrices. First of all, quantum gates will be implemented by physical devices, and so they must abide by the laws of quantum physics. One relevant law of physics is that no information is ever lost when transitioning between points in the past and the future1. This is known as unitarity. Since our quantum gates define how we transition between states, they too must abide by unitarity."
},
{
"code": null,
"e": 7833,
"s": 7556,
"text": "Secondly, note that our quantum gates will be applied to qubits. We learned earlier that qubits are really just vectors, and so that means quantum gates must somehow operate on vectors. Fortunately, we recall that a matrix is actually just a linear transformation for vectors!"
},
{
"code": null,
"e": 8296,
"s": 7833,
"text": "Combining these two ideas, we think of quantum gates as unitary matrices. A unitary matrix is any square matrix of complex numbers such that the conjugate transpose is equal to its inverse. As a quick refresher, the conjugate transpose of a matrix is found by taking the conjugate of each element in the matrix (a + bi → a — bi), and then taking the transpose of the matrix (element ij → element ji). We typically denote the conjugate transpose by the dagger, †."
},
{
"code": null,
"e": 8594,
"s": 8296,
"text": "A key observation about unitary matrices is that they preserve the norm (length of a vector). Suppose we allowed gates that changed the norm, then our qubit’s probabilities may sum to something other than one! That doesn’t make sense since the sum of all probabilities must always be equal to one."
},
{
"code": null,
"e": 9451,
"s": 8594,
"text": "Also notice that, by definition, unitary matrices have an inverse. One implication of this is that we cannot ‘assign’ qubits to arbitrary states. To understand why not, let’s pretend that we did have a quantum gate that could ‘assign’ values, hence, convert any vector of two complex numbers into a specific vector of two complex numbers. This quantum gate would have some underlying representation as a unitary matrix, and that matrix would have an inverse capable of converting a specific vector back into whatever state the qubit was before the operation! But the qubit could have been in any state before the operation and there’s no way to know which! Hence, we cannot ‘assign’ qubits to an arbitrary state. At a higher level, the fact that all quantum gates are invertible is why we often think of quantum computing as a form of reversible computing."
},
{
"code": null,
"e": 9812,
"s": 9451,
"text": "Lastly, notice that because our quantum gates are unitary matrices, they are square by definition, and so our quantum gates must have an equal number of input and output qubits (because square matrices map n standard basis vectors to n columns)! This is quite different from most logic gates; for example, the AND gate takes two inputs and produces one output."
},
{
"code": null,
"e": 9923,
"s": 9812,
"text": "Now that we know a little bit about what we are working with, let’s consider an example, the Hadamard gate, H."
},
{
"code": null,
"e": 10117,
"s": 9923,
"text": "We can check that H is unitary by checking that the conjugate transpose is equal to its inverse, or in other words, that H multiplied by its conjugate transpose is equal to the Identity matrix:"
},
{
"code": null,
"e": 10432,
"s": 10117,
"text": "Another important quantum gate is the Controlled NOT gate, also known as CNOT. CNOT acts on two qubits, a control qubit and a target qubit. We can think of CNOT as an ‘if statement’ — if the control qubit is equal to 1, then CNOT applies NOT (the inverse gate) to the target qubit (hence the name, Controlled NOT)."
},
{
"code": null,
"e": 10589,
"s": 10432,
"text": "Here is the matrix representing CNOT. This matrix treats the control qubit as the rightmost value inside the ket and the target qubit as the leftmost value."
},
{
"code": null,
"e": 10619,
"s": 10589,
"text": "Let’s see its effect on ∣00⟩."
},
{
"code": null,
"e": 10775,
"s": 10619,
"text": "In this example, we see that CNOT doesn’t modify the value of ∣00⟩. And this is the expected behavior, as CNOT only inverts the target if the control is 1."
},
{
"code": null,
"e": 10805,
"s": 10775,
"text": "Let’s see its effect on ∣01⟩."
},
{
"code": null,
"e": 10909,
"s": 10805,
"text": "Here, we can see that the control is equal to 1, so CNOT inverts the target. Hence, the result is ∣11⟩."
},
{
"code": null,
"e": 11015,
"s": 10909,
"text": "Try working out the other two cases, ∣10⟩ and ∣11⟩. You should find that CNOT has the following behavior:"
},
{
"code": null,
"e": 11028,
"s": 11015,
"text": "∣00⟩ -> ∣00⟩"
},
{
"code": null,
"e": 11041,
"s": 11028,
"text": "∣01⟩ -> ∣11⟩"
},
{
"code": null,
"e": 11054,
"s": 11041,
"text": "∣10⟩ -> ∣10⟩"
},
{
"code": null,
"e": 11067,
"s": 11054,
"text": "∣11⟩ -> ∣01⟩"
},
{
"code": null,
"e": 11175,
"s": 11067,
"text": "And notice that this is precisely the behavior of applying NOT to the target bit when the control bit is 1."
},
{
"code": null,
"e": 11590,
"s": 11175,
"text": "To recap, we can think of quantum gates as unitary matrices. This unitarity enforces the constraint that a qubit’s probabilities sum to one and causes quantum computing to be reversible. Since unitary matrices are square, we find that quantum gates must have an equal number of input and output qubits. We learned about Hadamard and CNOT, which are two important quantum gates. There exist many more quantum gates."
},
{
"code": null,
"e": 11692,
"s": 11590,
"text": "Now that we know the basics of qubits and quantum gates, let’s see our first quantum circuit diagram."
},
{
"code": null,
"e": 11850,
"s": 11692,
"text": "Quantum circuit diagrams are how we think about quantum ‘programs’. We define the qubits as rows, and we apply quantum gates sequentially from left to right."
},
{
"code": null,
"e": 12245,
"s": 11850,
"text": "Let’s walk through every part of this diagram. First, we have two qubits. Each row corresponds to a qubit. The top row corresponds to the qubit named x0 and the bottom corresponds to the qubit named x1. We consider x0 to be the 0th qubit because we start counting from 0 (the same as in the rest of programming). We write x0 : ∣0⟩ and x1 : ∣0⟩ to mean that x0 and x1 start off in the state ∣0⟩."
},
{
"code": null,
"e": 12649,
"s": 12245,
"text": "The H is the Hadamard gate and is being applied to qubit x0. The ●-⊕ is the CNOT gate, the ● is the control qubit, and the ⊕ is the target qubit. The - is just to help us see which two qubits are affected. In other words, we are applying CNOT where the control is qubit x0 and the target is x1. Note, the order that we apply these gates is important. In this diagram, we applied H first and CNOT second."
},
{
"code": null,
"e": 13072,
"s": 12649,
"text": "The quantum circuit diagram is just one representation of our program. It helps us think about our quantum computation, but other representations can also be useful. We can translate our diagram into a string of symbols, which helps us when preparing to write it as computer code. Having it in string form also makes it easy to translate into the underlying math. This math will tell us the expected output of our program."
},
{
"code": null,
"e": 13505,
"s": 13072,
"text": "Let’s start off by converting our diagram into a string of symbols. Rather than writing our qubits as rows, we’ll use Bra-ket notation. The 0th qubit will be the rightmost qubit in ∣00⟩, just like when writing out binary numbers2. This means that qubit x1 is the leftmost qubit in ∣00⟩. (Note, the quantum physics people tend to reverse this ordering3. Always check the qubit ordering as it’s an incredibly common source of errors.)"
},
{
"code": null,
"e": 13981,
"s": 13505,
"text": "We also need to translate the gates. Since we are applying H to qubit x0 and not applying anything to qubit x1 (which is equivalent to applying the Identity gate, I), we’ll write this as (I⊗H). Lastly, we translate the CNOT, specifying which qubit is the control and which is the target. The result is CNOT[control=0, target=1] (I⊗H) ∣00⟩ (note, this string is read from right-to-left). Great! This will be useful when writing the code that’ll be run on the quantum computer."
},
{
"code": null,
"e": 14276,
"s": 13981,
"text": "Having the string representation of the quantum circuit diagram makes it easy to translate our program into the underlying math. There are three pieces, the CNOT[control=0, target=1], (I⊗H), and ∣00⟩. Each piece can be translated into a matrix, as shown in the first row of the following image:"
},
{
"code": null,
"e": 14599,
"s": 14276,
"text": "We can even multiply out our matrices to find the resulting state vector, as shown above. This state vector is the expected state of our two qubits after the quantum computation has completed. Alternatively, we can think of it as the output of our program. It tells us the probability amplitudes for each measurable state."
},
{
"code": null,
"e": 14829,
"s": 14599,
"text": "Also, remember our mixed state qubits? Notice that we can’t actually write qubit x0 and qubit x1 in pure states anymore because there isn’t any way to break up the vector with a tensor product. So our qubits are in a mixed state!"
},
{
"code": null,
"e": 15207,
"s": 14829,
"text": "What if we measured our qubits now? What would we receive? We can find out by decomposing the state vector into each of the measurable states. We’ll measure our qubits in the standard basis, also known as ∣0⟩ and ∣1⟩ (there are other bases we could measure in, but don't worry about that for now). Hence, our two qubit system’s measurable states are ∣00⟩, ∣01⟩, ∣10⟩, and ∣11⟩."
},
{
"code": null,
"e": 15524,
"s": 15207,
"text": "We can determine the probabilities of the measured values in the same way we used|α|2 to determine the probability of ∣0⟩ for a single qubit. Since ∣01⟩ and ∣10⟩ have a 0 probability amplitude, we know that we will never measure that state. And we will measure both ∣00⟩ and ∣11⟩ with probability (1/sqrt(2))2 = 1/2."
},
{
"code": null,
"e": 15775,
"s": 15524,
"text": "Now, suppose we were to separate these two qubits by a large distance, and then we measured either one. The instant that we measured it, we would know the value of the other qubit too! This is because we know that the qubits can only be ∣00⟩ or ∣11⟩."
},
{
"code": null,
"e": 16058,
"s": 15775,
"text": "This is what Einstein referred to as ‘spooky action at a distance’, also known as quantum entanglement. We think of the information as being correlated rather than traveling. If it were traveling, then it could potentially travel faster than light, which breaks the laws of physics."
},
{
"code": null,
"e": 16379,
"s": 16058,
"text": "Now that we understand what’s happening under the hood with qubits, quantum gates, and quantum circuit diagrams, let’s see how to run on a real quantum computer. I’ll be using Rigetti’s quantum computer since they are currently giving out free credit to beta users. Alternatively, we can also use IBM’s quantum computer."
},
{
"code": null,
"e": 16447,
"s": 16379,
"text": "Here’s a basic overview of the Rigetti quantum programming process:"
},
{
"code": null,
"e": 16785,
"s": 16447,
"text": "Write a Python program that specifies your quantum circuit and any additional code necessaryTest that Python program using a quantum simulatorReserve time on Rigetti’s quantum computerSend your program over to Rigetti’s serversExecute your program on Rigetti’s server (they’ll send your quantum program to their quantum computer for you)"
},
{
"code": null,
"e": 16878,
"s": 16785,
"text": "Write a Python program that specifies your quantum circuit and any additional code necessary"
},
{
"code": null,
"e": 16929,
"s": 16878,
"text": "Test that Python program using a quantum simulator"
},
{
"code": null,
"e": 16972,
"s": 16929,
"text": "Reserve time on Rigetti’s quantum computer"
},
{
"code": null,
"e": 17016,
"s": 16972,
"text": "Send your program over to Rigetti’s servers"
},
{
"code": null,
"e": 17127,
"s": 17016,
"text": "Execute your program on Rigetti’s server (they’ll send your quantum program to their quantum computer for you)"
},
{
"code": null,
"e": 17196,
"s": 17127,
"text": "Here’s the Python version of our quantum circuit diagram from above."
},
{
"code": null,
"e": 17235,
"s": 17196,
"text": "The results will look similar to this:"
},
{
"code": null,
"e": 17396,
"s": 17235,
"text": "[(0, 0), (1, 1), (1, 1), (0, 0), (0, 0), (0, 0), (1, 1), (0, 0), (0, 0), (1, 1)][(0, 0), (0, 1), (1, 1), (1, 1), (1, 1), (0, 0), (0, 0), (1, 1), (1, 0), (0, 0)]"
},
{
"code": null,
"e": 17751,
"s": 17396,
"text": "The first row corresponds to the simulator, and the results seem reasonable — we get [0, 0] roughly half the time and [1, 1] the remaining times. However, with the real quantum computer, aside from the expected [0, 0] and [1, 1], we also receive [0, 1] and [1, 0]. According to the math, we should only ever receive [0, 0] and [1, 1], so what’s going on?"
},
{
"code": null,
"e": 18169,
"s": 17751,
"text": "The issue is that real quantum computers today (July 2019) are still quite error-prone.4 For example, we might see an error rate of 2–3% when trying to initialize qubits to 0. And we might have another 1–2% error rate per single-qubit gate operation, and around 3–4% for two-qubit gate operations. We even have error rates when measuring the qubit! In practice, these errors accumulate and result in incorrect values."
},
{
"code": null,
"e": 18445,
"s": 18169,
"text": "In this article, we learned that quantum computers actually do exist and work today, albeit with rather high error rates. And while the physical implementation of these machines varies substantially across companies, many of the concepts for programming them remain the same."
},
{
"code": null,
"e": 18883,
"s": 18445,
"text": "We think of qubits as a vector of two complex numbers with unit length, and we think of quantum gates as unitary matrices. We remember that quantum computing is probabilistic since two identical qubits could have different values once measured. And since quantum gates are unitary, we know that quantum computing is inherently reversible. At a high level, we can think of quantum programming as applied linear algebra on complex numbers."
},
{
"code": null,
"e": 19018,
"s": 18883,
"text": "We used quantum circuit diagrams to denote our quantum program and then converted it into Python to be run on a real quantum computer."
},
{
"code": null,
"e": 19121,
"s": 19018,
"text": "I hope you learned something, and I would be happy to hear any comments or suggestions you might have!"
},
{
"code": null,
"e": 19198,
"s": 19121,
"text": "Q) I googled the matrix form of CNOT and it looks different from yours, why?"
},
{
"code": null,
"e": 19439,
"s": 19198,
"text": "A) If you are looking at [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]], its because they reversed the target and control qubit ordering. If you see something other than what I wrote above or in this article, then it’s just wrong."
},
{
"code": null,
"e": 19538,
"s": 19439,
"text": "Q) So we have bits and trits for regular computers, does there exist something similar for qubits?"
},
{
"code": null,
"e": 19713,
"s": 19538,
"text": "A) Yes, qutrits. Qubits are part of a two-level quantum system. Qutrits are parts of a three-level quantum system. There’s also qudits, which generalize the number of levels."
},
{
"code": null,
"e": 19777,
"s": 19713,
"text": "[1] L. Susskind, Lecture 1 Quantum Entanglements, Part 1 (2008)"
},
{
"code": null,
"e": 19828,
"s": 19777,
"text": "[2] Basis vector ordering in Qiskit (2019), Qiskit"
},
{
"code": null,
"e": 19896,
"s": 19828,
"text": "[3] R. Smith, Someone Shouts “01000”! Who is excited? (2017), arxiv"
}
] |
Decision Coverage Testing | Decision coverage or Branch coverage is a testing method, which aims to ensure that each one of the possible branch from each decision point is executed at least once and thereby ensuring that all reachable code is executed.
That is, every decision is taken each way, true and false. It helps in validating all the branches in the code making sure that no branch leads to abnormal behavior of the application.
Read A
Read B
IF A+B > 10 THEN
Print "A+B is Large"
ENDIF
If A > 5 THEN
Print "A Large"
ENDIF
The above logic can be represented by a flowchart as:
To calculate Branch Coverage, one has to find out the minimum number of paths which will ensure that all the edges are covered. In this case there is no single path which will ensure coverage of all the edges at once. The aim is to cover all possible true/false decisions.
(1) 1A-2C-3D-E-4G-5H
(2) 1A-2B-E-4F
Hence Decision or Branch Coverage is 2.
80 Lectures
7.5 hours
Arnab Chakraborty
10 Lectures
1 hours
Zach Miller
17 Lectures
1.5 hours
Zach Miller
60 Lectures
5 hours
John Shea
99 Lectures
10 hours
Daniel IT
62 Lectures
5 hours
GlobalETraining
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 5970,
"s": 5745,
"text": "Decision coverage or Branch coverage is a testing method, which aims to ensure that each one of the possible branch from each decision point is executed at least once and thereby ensuring that all reachable code is executed."
},
{
"code": null,
"e": 6156,
"s": 5970,
"text": "That is, every decision is taken each way, true and false. It helps in validating all the branches in the code making sure that no branch leads to abnormal behavior of the application. "
},
{
"code": null,
"e": 6259,
"s": 6156,
"text": "Read A\nRead B \nIF A+B > 10 THEN \n Print \"A+B is Large\" \nENDIF \nIf A > 5 THEN \n Print \"A Large\"\nENDIF"
},
{
"code": null,
"e": 6313,
"s": 6259,
"text": "The above logic can be represented by a flowchart as:"
},
{
"code": null,
"e": 6664,
"s": 6313,
"text": "To calculate Branch Coverage, one has to find out the minimum number of paths which will ensure that all the edges are covered. In this case there is no single path which will ensure coverage of all the edges at once. The aim is to cover all possible true/false decisions.\n(1) 1A-2C-3D-E-4G-5H\n(2) 1A-2B-E-4F\nHence Decision or Branch Coverage is 2."
},
{
"code": null,
"e": 6699,
"s": 6664,
"text": "\n 80 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 6718,
"s": 6699,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6751,
"s": 6718,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6764,
"s": 6751,
"text": " Zach Miller"
},
{
"code": null,
"e": 6799,
"s": 6764,
"text": "\n 17 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6812,
"s": 6799,
"text": " Zach Miller"
},
{
"code": null,
"e": 6845,
"s": 6812,
"text": "\n 60 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 6856,
"s": 6845,
"text": " John Shea"
},
{
"code": null,
"e": 6890,
"s": 6856,
"text": "\n 99 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 6901,
"s": 6890,
"text": " Daniel IT"
},
{
"code": null,
"e": 6934,
"s": 6901,
"text": "\n 62 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 6951,
"s": 6934,
"text": " GlobalETraining"
},
{
"code": null,
"e": 6958,
"s": 6951,
"text": " Print"
},
{
"code": null,
"e": 6969,
"s": 6958,
"text": " Add Notes"
}
] |
How to Create a Responsive Like Button in ReactJS? - GeeksforGeeks | 09 Oct, 2020
React is a JavaScript library used to develop interactive user interfaces. We will be making a Like feature using React JS. Modules required:
npm
React
Font Awesome
npm install --save @fortawesome/react-fontawesome
Basic setup: Start a project by the following command:
NPX: It is a package runner tool that comes with npm 5.2+, npx is easy to use CLI tools. The npx is used for executing Node packages. It greatly simplifies a number of things one of which is checked/run a node package quickly without installing it locally or globally.
npx create-react-app like-app
Now go to the folder
cd like-app
Start the server- Start the server by typing the following command in terminal:
npm start
Now create a directory inside src with a file name – Like.js
mkdir components && cd components && touch Like.js
The directory structure will look similar to this:
Edit Like.js as following.
Like.js: The following are the imports for the required like feature app. The 2nd import denotes the famous icon library – “Font-Awesome” Library.JavascriptJavascriptimport React, { Component } from "react";import { faHeart } from "@fortawesome/free-solid-svg-icons";import { faHeartBroken } from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
Like.js: The following are the imports for the required like feature app. The 2nd import denotes the famous icon library – “Font-Awesome” Library.
Javascript
import React, { Component } from "react";import { faHeart } from "@fortawesome/free-solid-svg-icons";import { faHeartBroken } from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
Like.js: Now let’s define the state of our component. It contains one variable called liked. If it’s false then we will render a blank heart, however, if it’s true we will render a solid heart.JavascriptJavascriptstate = { liked: false };
Like.js: Now let’s define the state of our component. It contains one variable called liked. If it’s false then we will render a blank heart, however, if it’s true we will render a solid heart.
Javascript
state = { liked: false };
Like.js: The toggle(): This function is the core of the component which does the state change when the heart is clicked. It toggles the state of the heart between empty and solid.JavascriptJavascripttoggle = () => { let localLiked = this.state.liked; localLiked = !localLiked; this.setState({ liked: localLiked }); };
Like.js: The toggle(): This function is the core of the component which does the state change when the heart is clicked. It toggles the state of the heart between empty and solid.
Javascript
toggle = () => { let localLiked = this.state.liked; localLiked = !localLiked; this.setState({ liked: localLiked }); };
Like.js: This is the main render function that returns the HTML of the component. Carefully observe how we have used conditional rendering to render different hearts based on the state of the liked variable.JavascriptJavascriptrender() { return ( <div className="container"> <center> <p>Click on the Like Button</p> <div className="container" style={{ border: "1px solid black", width: "15%" }} onClick={() => this.toggle()} > {this.state.liked === false ? ( <FontAwesomeIcon icon={faHeart} /> ) : ( <FontAwesomeIcon icon={faHeartBroken} /> )} </div> </center> </div> ); }
Like.js: This is the main render function that returns the HTML of the component. Carefully observe how we have used conditional rendering to render different hearts based on the state of the liked variable.
Javascript
render() { return ( <div className="container"> <center> <p>Click on the Like Button</p> <div className="container" style={{ border: "1px solid black", width: "15%" }} onClick={() => this.toggle()} > {this.state.liked === false ? ( <FontAwesomeIcon icon={faHeart} /> ) : ( <FontAwesomeIcon icon={faHeartBroken} /> )} </div> </center> </div> ); }
Like.js: Final Code of the component which can be exported and used inside any other component.
Javascript
import React, { Component } from "react";import { faHeart } from "@fortawesome/free-solid-svg-icons";import { faHeartBroken } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";class Like extends Component { state = { liked: false }; toggle = () => { let localLiked = this.state.liked; // Toggle the state variable liked localLiked = !localLiked; this.setState({ liked: localLiked }); }; render() { return ( <div className="container"> <center> <p>Click on the Like Button</p> <div className="container" style={{ border: "1px solid black", width: "15%" }} onClick={() => this.toggle()} > {this.state.liked === false ? ( <FontAwesomeIcon icon={faHeart} /> ) : ( <FontAwesomeIcon icon={faHeartBroken} /> )} </div> </center> </div> ); }} export default Like;
Output: Final Output will look something like this. Open http://localhost:3000/ in browser:
react-js
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
How to filter object array based on attributes?
How to get selected value in dropdown list using JavaScript ?
How to remove duplicate elements from JavaScript Array ?
Angular File Upload
How to change selected value of a drop-down list using jQuery?
How to detect browser or tab closing in JavaScript ? | [
{
"code": null,
"e": 25322,
"s": 25294,
"text": "\n09 Oct, 2020"
},
{
"code": null,
"e": 25464,
"s": 25322,
"text": "React is a JavaScript library used to develop interactive user interfaces. We will be making a Like feature using React JS. Modules required:"
},
{
"code": null,
"e": 25468,
"s": 25464,
"text": "npm"
},
{
"code": null,
"e": 25474,
"s": 25468,
"text": "React"
},
{
"code": null,
"e": 25487,
"s": 25474,
"text": "Font Awesome"
},
{
"code": null,
"e": 25538,
"s": 25487,
"text": "npm install --save @fortawesome/react-fontawesome\n"
},
{
"code": null,
"e": 25593,
"s": 25538,
"text": "Basic setup: Start a project by the following command:"
},
{
"code": null,
"e": 25862,
"s": 25593,
"text": "NPX: It is a package runner tool that comes with npm 5.2+, npx is easy to use CLI tools. The npx is used for executing Node packages. It greatly simplifies a number of things one of which is checked/run a node package quickly without installing it locally or globally."
},
{
"code": null,
"e": 25893,
"s": 25862,
"text": "npx create-react-app like-app\n"
},
{
"code": null,
"e": 25914,
"s": 25893,
"text": "Now go to the folder"
},
{
"code": null,
"e": 25927,
"s": 25914,
"text": "cd like-app\n"
},
{
"code": null,
"e": 26007,
"s": 25927,
"text": "Start the server- Start the server by typing the following command in terminal:"
},
{
"code": null,
"e": 26018,
"s": 26007,
"text": "npm start\n"
},
{
"code": null,
"e": 26079,
"s": 26018,
"text": "Now create a directory inside src with a file name – Like.js"
},
{
"code": null,
"e": 26131,
"s": 26079,
"text": "mkdir components && cd components && touch Like.js\n"
},
{
"code": null,
"e": 26182,
"s": 26131,
"text": "The directory structure will look similar to this:"
},
{
"code": null,
"e": 26210,
"s": 26182,
"text": "Edit Like.js as following. "
},
{
"code": null,
"e": 26609,
"s": 26210,
"text": "Like.js: The following are the imports for the required like feature app. The 2nd import denotes the famous icon library – “Font-Awesome” Library.JavascriptJavascriptimport React, { Component } from \"react\";import { faHeart } from \"@fortawesome/free-solid-svg-icons\";import { faHeartBroken } from \"@fortawesome/free-solid-svg-icons\";import { FontAwesomeIcon } from \"@fortawesome/react-fontawesome\";"
},
{
"code": null,
"e": 26756,
"s": 26609,
"text": "Like.js: The following are the imports for the required like feature app. The 2nd import denotes the famous icon library – “Font-Awesome” Library."
},
{
"code": null,
"e": 26767,
"s": 26756,
"text": "Javascript"
},
{
"code": "import React, { Component } from \"react\";import { faHeart } from \"@fortawesome/free-solid-svg-icons\";import { faHeartBroken } from \"@fortawesome/free-solid-svg-icons\";import { FontAwesomeIcon } from \"@fortawesome/react-fontawesome\";",
"e": 27000,
"s": 26767,
"text": null
},
{
"code": null,
"e": 27239,
"s": 27000,
"text": "Like.js: Now let’s define the state of our component. It contains one variable called liked. If it’s false then we will render a blank heart, however, if it’s true we will render a solid heart.JavascriptJavascriptstate = { liked: false };"
},
{
"code": null,
"e": 27433,
"s": 27239,
"text": "Like.js: Now let’s define the state of our component. It contains one variable called liked. If it’s false then we will render a blank heart, however, if it’s true we will render a solid heart."
},
{
"code": null,
"e": 27444,
"s": 27433,
"text": "Javascript"
},
{
"code": "state = { liked: false };",
"e": 27470,
"s": 27444,
"text": null
},
{
"code": null,
"e": 27798,
"s": 27470,
"text": "Like.js: The toggle(): This function is the core of the component which does the state change when the heart is clicked. It toggles the state of the heart between empty and solid.JavascriptJavascripttoggle = () => { let localLiked = this.state.liked; localLiked = !localLiked; this.setState({ liked: localLiked }); };"
},
{
"code": null,
"e": 27978,
"s": 27798,
"text": "Like.js: The toggle(): This function is the core of the component which does the state change when the heart is clicked. It toggles the state of the heart between empty and solid."
},
{
"code": null,
"e": 27989,
"s": 27978,
"text": "Javascript"
},
{
"code": "toggle = () => { let localLiked = this.state.liked; localLiked = !localLiked; this.setState({ liked: localLiked }); };",
"e": 28118,
"s": 27989,
"text": null
},
{
"code": null,
"e": 28854,
"s": 28118,
"text": "Like.js: This is the main render function that returns the HTML of the component. Carefully observe how we have used conditional rendering to render different hearts based on the state of the liked variable.JavascriptJavascriptrender() { return ( <div className=\"container\"> <center> <p>Click on the Like Button</p> <div className=\"container\" style={{ border: \"1px solid black\", width: \"15%\" }} onClick={() => this.toggle()} > {this.state.liked === false ? ( <FontAwesomeIcon icon={faHeart} /> ) : ( <FontAwesomeIcon icon={faHeartBroken} /> )} </div> </center> </div> ); }"
},
{
"code": null,
"e": 29062,
"s": 28854,
"text": "Like.js: This is the main render function that returns the HTML of the component. Carefully observe how we have used conditional rendering to render different hearts based on the state of the liked variable."
},
{
"code": null,
"e": 29073,
"s": 29062,
"text": "Javascript"
},
{
"code": "render() { return ( <div className=\"container\"> <center> <p>Click on the Like Button</p> <div className=\"container\" style={{ border: \"1px solid black\", width: \"15%\" }} onClick={() => this.toggle()} > {this.state.liked === false ? ( <FontAwesomeIcon icon={faHeart} /> ) : ( <FontAwesomeIcon icon={faHeartBroken} /> )} </div> </center> </div> ); }",
"e": 29582,
"s": 29073,
"text": null
},
{
"code": null,
"e": 29678,
"s": 29582,
"text": "Like.js: Final Code of the component which can be exported and used inside any other component."
},
{
"code": null,
"e": 29689,
"s": 29678,
"text": "Javascript"
},
{
"code": "import React, { Component } from \"react\";import { faHeart } from \"@fortawesome/free-solid-svg-icons\";import { faHeartBroken } from \"@fortawesome/free-solid-svg-icons\"; import { FontAwesomeIcon } from \"@fortawesome/react-fontawesome\";class Like extends Component { state = { liked: false }; toggle = () => { let localLiked = this.state.liked; // Toggle the state variable liked localLiked = !localLiked; this.setState({ liked: localLiked }); }; render() { return ( <div className=\"container\"> <center> <p>Click on the Like Button</p> <div className=\"container\" style={{ border: \"1px solid black\", width: \"15%\" }} onClick={() => this.toggle()} > {this.state.liked === false ? ( <FontAwesomeIcon icon={faHeart} /> ) : ( <FontAwesomeIcon icon={faHeartBroken} /> )} </div> </center> </div> ); }} export default Like;",
"e": 30680,
"s": 29689,
"text": null
},
{
"code": null,
"e": 30772,
"s": 30680,
"text": "Output: Final Output will look something like this. Open http://localhost:3000/ in browser:"
},
{
"code": null,
"e": 30781,
"s": 30772,
"text": "react-js"
},
{
"code": null,
"e": 30792,
"s": 30781,
"text": "JavaScript"
},
{
"code": null,
"e": 30890,
"s": 30792,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30899,
"s": 30890,
"text": "Comments"
},
{
"code": null,
"e": 30912,
"s": 30899,
"text": "Old Comments"
},
{
"code": null,
"e": 30973,
"s": 30912,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 31014,
"s": 30973,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 31068,
"s": 31014,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 31108,
"s": 31068,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 31156,
"s": 31108,
"text": "How to filter object array based on attributes?"
},
{
"code": null,
"e": 31218,
"s": 31156,
"text": "How to get selected value in dropdown list using JavaScript ?"
},
{
"code": null,
"e": 31275,
"s": 31218,
"text": "How to remove duplicate elements from JavaScript Array ?"
},
{
"code": null,
"e": 31295,
"s": 31275,
"text": "Angular File Upload"
},
{
"code": null,
"e": 31358,
"s": 31295,
"text": "How to change selected value of a drop-down list using jQuery?"
}
] |
KnockoutJS - Event Binding | This binding is used to listen to specific DOM event and call associated with the handler function based on it.
Syntax
event: <{DOM-event: handler-function}>
Parameters
Parameter is inclusive of a JavaScript object, containing DOM event which will be listened to and a handler function which needs to be invoked based on that event. This function can be any JavaScript function and need not be necessarily ViewModel function.
Example
Let us take a look at the following example which demonstrates the use of event binding.
<!DOCTYPE html>
<head>
<title>KnockoutJS Event Binding</title>
<script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"
type = "text/javascript"></script>
</head>
<body>
<p>Enter Number :</p>
<input data-bind = "value: someValue , event: {keyup: showMessage},
valueUpdate: 'afterkeydown' " /><br><br>
You Entered: <span data-bind = "text: someValue"/>
<script type = "text/javascript">
function ViewModel () {
this.someValue = ko.observable();
this.showMessage = function(data,event) {
if ((event.keyCode < 47) || (event.keyCode > 58 )) { //check for number
if (event.keyCode !== 8) //ignore backspace
alert("Please enter a number.");
this.someValue('');
}
}
};
var vm = new ViewModel();
ko.applyBindings(vm);
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works −
Save the above code in event-bind.htm file.
Save the above code in event-bind.htm file.
Open this HTML file in a browser.
Open this HTML file in a browser.
Try to key in any non-numeric value and you will be prompted with an alert.
Try to key in any non-numeric value and you will be prompted with an alert.
Enter Number −
KO will pass the current item as parameter when calling the handler function. This is useful when working with a collection of items and need to work on each of them.
Example
Let us take a look at the following example in which the current item is passed in event binding.
<!DOCTYPE html>
<head>
<title>KnockoutJS Event Binding - passing current item </title>
<script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"
type = "text/javascript"></script>
</head>
<body>
<ul data-bind = "foreach: icecreams">
<li data-bind = "text: $data, event: { mouseover: $parent.logMouseOver }"> </li>
</ul>
<p>You seem to be interested in: <span data-bind = "text: flavorLiked"> </span></p>
<script type = "text/javascript">
function ViewModel () {
var self = this;
self.flavorLiked = ko.observable();
self.icecreams = ko.observableArray(['Vanilla', 'Pista', 'Chocolate',
'Mango']);
// current item is passed here as the first parameter, so we know which
// flavor was hovered over
self.logMouseOver = function (flavor) {
self.flavorLiked(flavor);
}
};
var vm = new ViewModel();
ko.applyBindings(vm);
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works −
Save the above code in event-bind-passing-curr-item.htm file.
Save the above code in event-bind-passing-curr-item.htm file.
Open this HTML file in a browser.
Open this HTML file in a browser.
Flavor, which has the mouse over it, is displayed.
Flavor, which has the mouse over it, is displayed.
Note that self as an alias is used for this. This helps to avoid any problems with this being redefined to something else in event handlers.
Note that self as an alias is used for this. This helps to avoid any problems with this being redefined to something else in event handlers.
Vanilla
Pista
Chocolate
Mango
You seem to be interested in:
There might be a situation where you need to access DOM event object associated with the event. KO passes the event as a second parameter to the handler function.
Example
Let us take a look a the following example in which the event is sent as a second parameter to function.
<!DOCTYPE html>
<head>
<title>KnockoutJS Event Binding - passing more params</title>
<script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"
type = "text/javascript"></script>
</head>
<body>
<div data-bind = "event: { mouseover: logMouseOver }">
Press shiftKey + move cursor over this line.
</div>
<script type = "text/javascript">
function ViewModel () {
self.logMouseOver = function (data, event) {
if (event.shiftKey) {
alert("shift key is pressed.");
} else {
alert("shift key is not pressed.");
}
}
};
var vm = new ViewModel();
ko.applyBindings(vm);
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works −
Save the above code in event-bind-passing-more-params.htm file.
Save the above code in event-bind-passing-more-params.htm file.
Open this HTML file in a browser.
Open this HTML file in a browser.
Press shiftKey + move cursor to the text. Observe that the message will pop up showing if you have pressed the shiftKey.
Press shiftKey + move cursor to the text. Observe that the message will pop up showing if you have pressed the shiftKey.
Knockout will avoid the event from performing any default action, by default. Meaning if you use keypress event for an input tag, then KO will just call the handler function and will not add the key value to input elements value.
If you want the event to perform a default action, then just return true from the handler function.
Example
Let us look at the following example which allows default action to take place.
<!DOCTYPE html>
<head>
<title>KnockoutJS Event Binding - allowing default action</title>
<script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"
type = "text/javascript"></script>
</head>
<body>
<p>Enter the flavor you like from available menu: (Vanilla, Pista, Chocolate,
Mango)</p>
<input data-bind = "event: { keypress: acceptInput}"></input>
<script type = "text/javascript">
function ViewModel () {
self.acceptInput = function () {
return true;
}
};
var vm = new ViewModel();
ko.applyBindings(vm);
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works −
Save the above code in event-bind-default-action.htm file.
Save the above code in event-bind-default-action.htm file.
Open this HTML file in a browser.
Open this HTML file in a browser.
Any key pressed is actually shown in the input box because the handler function returns true.
Any key pressed is actually shown in the input box because the handler function returns true.
Enter the flavor you like from available menu: (Vanilla, Pista, Chocolate, Mango)
KO will allow the event to bubble up to the higher level event handlers. Meaning if you have two mouseover events nested, then the event handler function for both of them will be called. If needed, this bubbling can be prevented by adding an extra binding called as youreventBubble and passing false value to it.
Example
Let us take a look at the following example in which bubbling is handled.
<!DOCTYPE html>
<head>
<title>KnockoutJS Event Binding - preventing bubbling </title>
<script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"
type = "text/javascript"></script>
</head>
<body>
<div data-bind = "event: { mouseover: myParentHandler }">
<button data-bind = "event: { mouseover: myChildHandler },
mouseoverBubble: false">Click me to check bubbling.</button>
</div>
<script type = "text/javascript">
function ViewModel () {
var self = this;
self.myParentHandler = function () {
alert("Parent Function");
}
self.myChildHandler = function () {
alert("Child Function");
}
};
var vm = new ViewModel();
ko.applyBindings(vm);
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works −
Save the above code in event-bind-prevent-bubble.htm file.
Save the above code in event-bind-prevent-bubble.htm file.
Open this HTML file in a browser.
Open this HTML file in a browser.
Move the mouseover button and you will see a message. Bubbling is prevented due to the use of mouseoverBubble set to false.
Move the mouseover button and you will see a message. Bubbling is prevented due to the use of mouseoverBubble set to false.
38 Lectures
2 hours
Skillbakerystudios
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1964,
"s": 1852,
"text": "This binding is used to listen to specific DOM event and call associated with the handler function based on it."
},
{
"code": null,
"e": 1971,
"s": 1964,
"text": "Syntax"
},
{
"code": null,
"e": 2011,
"s": 1971,
"text": "event: <{DOM-event: handler-function}>\n"
},
{
"code": null,
"e": 2022,
"s": 2011,
"text": "Parameters"
},
{
"code": null,
"e": 2279,
"s": 2022,
"text": "Parameter is inclusive of a JavaScript object, containing DOM event which will be listened to and a handler function which needs to be invoked based on that event. This function can be any JavaScript function and need not be necessarily ViewModel function."
},
{
"code": null,
"e": 2287,
"s": 2279,
"text": "Example"
},
{
"code": null,
"e": 2376,
"s": 2287,
"text": "Let us take a look at the following example which demonstrates the use of event binding."
},
{
"code": null,
"e": 3407,
"s": 2376,
"text": "<!DOCTYPE html>\n <head>\n <title>KnockoutJS Event Binding</title>\n <script src = \"https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js\"\n type = \"text/javascript\"></script>\n </head>\n \n <body>\n <p>Enter Number :</p>\n <input data-bind = \"value: someValue , event: {keyup: showMessage}, \n valueUpdate: 'afterkeydown' \" /><br><br>\n You Entered: <span data-bind = \"text: someValue\"/>\n\n <script type = \"text/javascript\">\n function ViewModel () {\n this.someValue = ko.observable();\n \n this.showMessage = function(data,event) {\n \n if ((event.keyCode < 47) || (event.keyCode > 58 )) { //check for number\n if (event.keyCode !== 8) //ignore backspace\n alert(\"Please enter a number.\");\n this.someValue('');\n }\n }\n };\n \n var vm = new ViewModel();\n ko.applyBindings(vm);\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 3414,
"s": 3407,
"text": "Output"
},
{
"code": null,
"e": 3484,
"s": 3414,
"text": "Let's carry out the following steps to see how the above code works −"
},
{
"code": null,
"e": 3528,
"s": 3484,
"text": "Save the above code in event-bind.htm file."
},
{
"code": null,
"e": 3572,
"s": 3528,
"text": "Save the above code in event-bind.htm file."
},
{
"code": null,
"e": 3606,
"s": 3572,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 3640,
"s": 3606,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 3716,
"s": 3640,
"text": "Try to key in any non-numeric value and you will be prompted with an alert."
},
{
"code": null,
"e": 3792,
"s": 3716,
"text": "Try to key in any non-numeric value and you will be prompted with an alert."
},
{
"code": null,
"e": 3808,
"s": 3792,
"text": "Enter Number −"
},
{
"code": null,
"e": 3975,
"s": 3808,
"text": "KO will pass the current item as parameter when calling the handler function. This is useful when working with a collection of items and need to work on each of them."
},
{
"code": null,
"e": 3983,
"s": 3975,
"text": "Example"
},
{
"code": null,
"e": 4081,
"s": 3983,
"text": "Let us take a look at the following example in which the current item is passed in event binding."
},
{
"code": null,
"e": 5197,
"s": 4081,
"text": "<!DOCTYPE html>\n <head>\n <title>KnockoutJS Event Binding - passing current item </title>\n <script src = \"https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js\"\n type = \"text/javascript\"></script>\n </head>\n \n <body>\n <ul data-bind = \"foreach: icecreams\">\n <li data-bind = \"text: $data, event: { mouseover: $parent.logMouseOver }\"> </li>\n </ul>\n <p>You seem to be interested in: <span data-bind = \"text: flavorLiked\"> </span></p>\n\n\n <script type = \"text/javascript\">\n \n function ViewModel () {\n var self = this;\n self.flavorLiked = ko.observable();\n self.icecreams = ko.observableArray(['Vanilla', 'Pista', 'Chocolate', \n 'Mango']);\n\n // current item is passed here as the first parameter, so we know which \n // flavor was hovered over\n self.logMouseOver = function (flavor) {\n self.flavorLiked(flavor);\n }\n };\n \n var vm = new ViewModel();\n ko.applyBindings(vm);\n </script>\n \n </body>\n</html>\n"
},
{
"code": null,
"e": 5204,
"s": 5197,
"text": "Output"
},
{
"code": null,
"e": 5274,
"s": 5204,
"text": "Let's carry out the following steps to see how the above code works −"
},
{
"code": null,
"e": 5336,
"s": 5274,
"text": "Save the above code in event-bind-passing-curr-item.htm file."
},
{
"code": null,
"e": 5398,
"s": 5336,
"text": "Save the above code in event-bind-passing-curr-item.htm file."
},
{
"code": null,
"e": 5432,
"s": 5398,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 5466,
"s": 5432,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 5517,
"s": 5466,
"text": "Flavor, which has the mouse over it, is displayed."
},
{
"code": null,
"e": 5568,
"s": 5517,
"text": "Flavor, which has the mouse over it, is displayed."
},
{
"code": null,
"e": 5709,
"s": 5568,
"text": "Note that self as an alias is used for this. This helps to avoid any problems with this being redefined to something else in event handlers."
},
{
"code": null,
"e": 5850,
"s": 5709,
"text": "Note that self as an alias is used for this. This helps to avoid any problems with this being redefined to something else in event handlers."
},
{
"code": null,
"e": 5858,
"s": 5850,
"text": "Vanilla"
},
{
"code": null,
"e": 5864,
"s": 5858,
"text": "Pista"
},
{
"code": null,
"e": 5874,
"s": 5864,
"text": "Chocolate"
},
{
"code": null,
"e": 5880,
"s": 5874,
"text": "Mango"
},
{
"code": null,
"e": 5911,
"s": 5880,
"text": "You seem to be interested in: "
},
{
"code": null,
"e": 6074,
"s": 5911,
"text": "There might be a situation where you need to access DOM event object associated with the event. KO passes the event as a second parameter to the handler function."
},
{
"code": null,
"e": 6082,
"s": 6074,
"text": "Example"
},
{
"code": null,
"e": 6187,
"s": 6082,
"text": "Let us take a look a the following example in which the event is sent as a second parameter to function."
},
{
"code": null,
"e": 7023,
"s": 6187,
"text": "<!DOCTYPE html>\n <head>\n <title>KnockoutJS Event Binding - passing more params</title>\n <script src = \"https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js\"\n type = \"text/javascript\"></script>\n </head>\n \n <body>\n <div data-bind = \"event: { mouseover: logMouseOver }\">\n Press shiftKey + move cursor over this line.\n </div>\n\n <script type = \"text/javascript\">\n function ViewModel () {\n \n self.logMouseOver = function (data, event) {\n if (event.shiftKey) {\n alert(\"shift key is pressed.\");\n } else {\n alert(\"shift key is not pressed.\");\n }\n }\n };\n \n var vm = new ViewModel();\n ko.applyBindings(vm);\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 7030,
"s": 7023,
"text": "Output"
},
{
"code": null,
"e": 7100,
"s": 7030,
"text": "Let's carry out the following steps to see how the above code works −"
},
{
"code": null,
"e": 7164,
"s": 7100,
"text": "Save the above code in event-bind-passing-more-params.htm file."
},
{
"code": null,
"e": 7228,
"s": 7164,
"text": "Save the above code in event-bind-passing-more-params.htm file."
},
{
"code": null,
"e": 7262,
"s": 7228,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 7296,
"s": 7262,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 7417,
"s": 7296,
"text": "Press shiftKey + move cursor to the text. Observe that the message will pop up showing if you have pressed the shiftKey."
},
{
"code": null,
"e": 7538,
"s": 7417,
"text": "Press shiftKey + move cursor to the text. Observe that the message will pop up showing if you have pressed the shiftKey."
},
{
"code": null,
"e": 7768,
"s": 7538,
"text": "Knockout will avoid the event from performing any default action, by default. Meaning if you use keypress event for an input tag, then KO will just call the handler function and will not add the key value to input elements value."
},
{
"code": null,
"e": 7868,
"s": 7768,
"text": "If you want the event to perform a default action, then just return true from the handler function."
},
{
"code": null,
"e": 7876,
"s": 7868,
"text": "Example"
},
{
"code": null,
"e": 7956,
"s": 7876,
"text": "Let us look at the following example which allows default action to take place."
},
{
"code": null,
"e": 8681,
"s": 7956,
"text": "<!DOCTYPE html>\n <head>\n <title>KnockoutJS Event Binding - allowing default action</title>\n <script src = \"https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js\"\n type = \"text/javascript\"></script>\n </head>\n \n <body>\n <p>Enter the flavor you like from available menu: (Vanilla, Pista, Chocolate, \n Mango)</p>\n <input data-bind = \"event: { keypress: acceptInput}\"></input>\n\n <script type = \"text/javascript\">\n function ViewModel () {\n \n self.acceptInput = function () {\n return true;\n }\n };\n \n var vm = new ViewModel();\n ko.applyBindings(vm);\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 8688,
"s": 8681,
"text": "Output"
},
{
"code": null,
"e": 8758,
"s": 8688,
"text": "Let's carry out the following steps to see how the above code works −"
},
{
"code": null,
"e": 8817,
"s": 8758,
"text": "Save the above code in event-bind-default-action.htm file."
},
{
"code": null,
"e": 8876,
"s": 8817,
"text": "Save the above code in event-bind-default-action.htm file."
},
{
"code": null,
"e": 8910,
"s": 8876,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 8944,
"s": 8910,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 9038,
"s": 8944,
"text": "Any key pressed is actually shown in the input box because the handler function returns true."
},
{
"code": null,
"e": 9132,
"s": 9038,
"text": "Any key pressed is actually shown in the input box because the handler function returns true."
},
{
"code": null,
"e": 9214,
"s": 9132,
"text": "Enter the flavor you like from available menu: (Vanilla, Pista, Chocolate, Mango)"
},
{
"code": null,
"e": 9527,
"s": 9214,
"text": "KO will allow the event to bubble up to the higher level event handlers. Meaning if you have two mouseover events nested, then the event handler function for both of them will be called. If needed, this bubbling can be prevented by adding an extra binding called as youreventBubble and passing false value to it."
},
{
"code": null,
"e": 9535,
"s": 9527,
"text": "Example"
},
{
"code": null,
"e": 9609,
"s": 9535,
"text": "Let us take a look at the following example in which bubbling is handled."
},
{
"code": null,
"e": 10526,
"s": 9609,
"text": "<!DOCTYPE html>\n <head>\n <title>KnockoutJS Event Binding - preventing bubbling </title>\n <script src = \"https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js\"\n type = \"text/javascript\"></script>\n </head>\n \n <body>\n <div data-bind = \"event: { mouseover: myParentHandler }\">\n <button data-bind = \"event: { mouseover: myChildHandler }, \n mouseoverBubble: false\">Click me to check bubbling.</button>\n </div>\n\n <script type = \"text/javascript\">\n function ViewModel () {\n var self = this;\n \n self.myParentHandler = function () {\n alert(\"Parent Function\");\n }\n\n self.myChildHandler = function () {\n alert(\"Child Function\");\n }\n };\n \n var vm = new ViewModel();\n ko.applyBindings(vm);\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 10533,
"s": 10526,
"text": "Output"
},
{
"code": null,
"e": 10603,
"s": 10533,
"text": "Let's carry out the following steps to see how the above code works −"
},
{
"code": null,
"e": 10662,
"s": 10603,
"text": "Save the above code in event-bind-prevent-bubble.htm file."
},
{
"code": null,
"e": 10721,
"s": 10662,
"text": "Save the above code in event-bind-prevent-bubble.htm file."
},
{
"code": null,
"e": 10755,
"s": 10721,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 10789,
"s": 10755,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 10913,
"s": 10789,
"text": "Move the mouseover button and you will see a message. Bubbling is prevented due to the use of mouseoverBubble set to false."
},
{
"code": null,
"e": 11037,
"s": 10913,
"text": "Move the mouseover button and you will see a message. Bubbling is prevented due to the use of mouseoverBubble set to false."
},
{
"code": null,
"e": 11070,
"s": 11037,
"text": "\n 38 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 11090,
"s": 11070,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 11097,
"s": 11090,
"text": " Print"
},
{
"code": null,
"e": 11108,
"s": 11097,
"text": " Add Notes"
}
] |
Array Nesting in C++ | Suppose we have a zero-indexed array A of length N that contains all integers from 0 to N-1. We have to find and return the longest length of set S, where S[i] = {A[i], A[A[i]], A[A[A[i]]], ... } subjected to the rule below. Now consider the first element in S starts with the selection of element A[i] of index = i, the next element in S should be A[A[i]], and then A[A[A[i]]]... By that analogy, we stop adding right before a duplicate element occurs in S. So if the array is like A = [5,4,0,3,1,6,2], then the output will be 4, as A[0] = 5, A[1] = 4, A[2] = 0, A[3] = 3, A[4] = 1, A[5] = 6, and finally A[6] = 2.
To solve this, we will follow these steps −
So create a function called dfs. This will take node, arr array, v array, and a set visited. Do the following in dfs array −
if node is visited, then return
insert node into v, mark node as visited
dfs(arr[node], arr, v, visited)
From the main method, do the following −
ret := 0, n := size of nums. make a set called visited
for i in range 0 to n – 1create an array vif nums[i] is not visited, then dfs(nums[i], nums, v, visited)ret := max of ret and size of v
create an array v
if nums[i] is not visited, then dfs(nums[i], nums, v, visited)
ret := max of ret and size of v
return ret
Let us see the following implementation to get better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
void dfs(int node, vector <int>& arr, vector <int>& v, set <int>& visited){
if(visited.count(node)) return;
v.push_back(node);
visited.insert(node);
dfs(arr[node], arr, v, visited);
}
int arrayNesting(vector<int>& nums) {
int ret = 0;
int n = nums.size();
set <int> visited;
for(int i = 0; i < n; i++){
vector <int> v;
if(!visited.count(nums[i]))dfs(nums[i], nums, v, visited);
ret = max(ret, (int)v.size());
}
return ret;
}
};
main(){
vector<int> v = {5,4,0,3,1,6,2};
Solution ob;
cout << (ob.arrayNesting(v));
}
[5,4,0,3,1,6,2]
4 | [
{
"code": null,
"e": 1678,
"s": 1062,
"text": "Suppose we have a zero-indexed array A of length N that contains all integers from 0 to N-1. We have to find and return the longest length of set S, where S[i] = {A[i], A[A[i]], A[A[A[i]]], ... } subjected to the rule below. Now consider the first element in S starts with the selection of element A[i] of index = i, the next element in S should be A[A[i]], and then A[A[A[i]]]... By that analogy, we stop adding right before a duplicate element occurs in S. So if the array is like A = [5,4,0,3,1,6,2], then the output will be 4, as A[0] = 5, A[1] = 4, A[2] = 0, A[3] = 3, A[4] = 1, A[5] = 6, and finally A[6] = 2."
},
{
"code": null,
"e": 1722,
"s": 1678,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1847,
"s": 1722,
"text": "So create a function called dfs. This will take node, arr array, v array, and a set visited. Do the following in dfs array −"
},
{
"code": null,
"e": 1879,
"s": 1847,
"text": "if node is visited, then return"
},
{
"code": null,
"e": 1920,
"s": 1879,
"text": "insert node into v, mark node as visited"
},
{
"code": null,
"e": 1952,
"s": 1920,
"text": "dfs(arr[node], arr, v, visited)"
},
{
"code": null,
"e": 1993,
"s": 1952,
"text": "From the main method, do the following −"
},
{
"code": null,
"e": 2048,
"s": 1993,
"text": "ret := 0, n := size of nums. make a set called visited"
},
{
"code": null,
"e": 2184,
"s": 2048,
"text": "for i in range 0 to n – 1create an array vif nums[i] is not visited, then dfs(nums[i], nums, v, visited)ret := max of ret and size of v"
},
{
"code": null,
"e": 2202,
"s": 2184,
"text": "create an array v"
},
{
"code": null,
"e": 2265,
"s": 2202,
"text": "if nums[i] is not visited, then dfs(nums[i], nums, v, visited)"
},
{
"code": null,
"e": 2297,
"s": 2265,
"text": "ret := max of ret and size of v"
},
{
"code": null,
"e": 2308,
"s": 2297,
"text": "return ret"
},
{
"code": null,
"e": 2378,
"s": 2308,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 2389,
"s": 2378,
"text": " Live Demo"
},
{
"code": null,
"e": 3085,
"s": 2389,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\n public:\n void dfs(int node, vector <int>& arr, vector <int>& v, set <int>& visited){\n if(visited.count(node)) return;\n v.push_back(node);\n visited.insert(node);\n dfs(arr[node], arr, v, visited);\n }\n int arrayNesting(vector<int>& nums) {\n int ret = 0;\n int n = nums.size();\n set <int> visited;\n for(int i = 0; i < n; i++){\n vector <int> v;\n if(!visited.count(nums[i]))dfs(nums[i], nums, v, visited);\n ret = max(ret, (int)v.size());\n }\n return ret;\n }\n};\nmain(){\n vector<int> v = {5,4,0,3,1,6,2};\n Solution ob;\n cout << (ob.arrayNesting(v));\n}"
},
{
"code": null,
"e": 3101,
"s": 3085,
"text": "[5,4,0,3,1,6,2]"
},
{
"code": null,
"e": 3103,
"s": 3101,
"text": "4"
}
] |
How to process a DataFrame with millions of rows in seconds? | by Roman Orac | Towards Data Science | Data Science is having its renaissance moment. It's hard to keep track of all new Data Science tools that have the potential to change the way Data Science gets done.
I learned about this new Data Processing Engine only recently in a conversation with a colleague, also a Data Scientist. We had a discussion about Big Data processing, which is at the forefront of innovation in the field, and this new tool popped up.
While pandas is the defacto tool for data processing in Python, it doesn’t handle big data well. With bigger datasets, you’ll get an out-of-memory exception sooner or later.
Researchers were confronted with this issue a long time ago, which prompted the development of tools like Dask and Spark, which try to overcome “the single machine” constrain by distributing processing to multiple machines.
This active area of innovation also brought us tools like Vaex, which try to solve this issue by making processing on a single machine more memory efficient.
And it doesn’t end there. There is another tool for big data processing you should know about ...
Terality is a Serverless Data Processing Engine that processes the data in the Cloud. There is no need to manage infrastructure as Terality takes care of scaling compute resources. Its target audiences are Engineers and Data Scientists.
I exchanged a few emails with the Terality’s team as I was interested in the tool they’ve developed. They answered swiftly. These were my questions to the team:
Terality comes with a Python client that you import into a Jupyter Notebook.Then you write the code in “a pandas way” and Terality securely uploads your data and takes care of distributed processing (and scaling) to calculate your analysis.After processing is completed, you can convert the data back to a regular pandas DataFrame and continue with analysis locally.
Terality comes with a Python client that you import into a Jupyter Notebook.
Then you write the code in “a pandas way” and Terality securely uploads your data and takes care of distributed processing (and scaling) to calculate your analysis.
After processing is completed, you can convert the data back to a regular pandas DataFrame and continue with analysis locally.
Terality team developed a proprietary data processing engine — it’s not a fork of Spark or Dask.
The goal was to avoid the imperfections of Dask, which doesn’t have the same syntax as pandas, it’s asynchronous, doesn’t have all pandas functions and it doesn’t support auto-scaling.
Terality’s Data Processing Engine solves these issues.
Terality has a free plan with which you can process up to 500 GB of data per month. It also offers a paid plan for companies and individuals with greater requirements.
In this article, we’ll focus on the free plan as it’s applicable to many Data Scientists.
How does Terality calculate data usage? (From Terality’s documentation)
Consider a dataset with a total size of 15GB in memory, as would be returned by the operation df.memory_usage(deep=True).sum().Running one (1) operation on this dataset, such as a .sum or a .sort_values, would consume 15GB of processed data in Terality.
The billable usage is only recorded when task runs enter a Success state.
When a user performs a read operation, the Terality client copies the dataset on Terality’s secured cloud storage on Amazon S3.
Terality has a strict policy around data privacy and protection. They guarantee that they’ll not use the data and process it securely.
Terality is not a storage solution. They will delete your data maximum within 3 days after Terality’s client session is closed.
Terality processing currently occurs on AWS in the Frankfurt region.
See the security section for more information.
No!
The user needs to have access to the dataset on his local machine and Terality will handle the uploading process behind the scene.
The upload operation is also parallelized so that is faster.
At the moment, in November 2021, Terality is still in beta. It’s optimized for datasets up to 100–200 GB.
I asked the team if they plan to increase this and they plan to soon start to optimize for Terabytes.
I was surprised that you can simply drop in replace pandas import statement with Terality’s package and rerun your analysis.
Note, once you import Terality’s python client, the data processing is not any longer performed on your local machine but with Terality’s Data Processing Engine in the Cloud.
Now, let’s install Terality and try it in practice...
You can install Terality by simply running:
pip install --upgrade terality
Then you create a free account on Terality and generate an API key:
The last step is to enter your API key (also replace the email with your email):
terality account configure --email [email protected]
Now, that we have Terality installed, we can run a small example to get familiar with it.
The practice shows that you get the best of both worlds while using both Terality and pandas — one to aggregate the data and the other to analyze the aggregate locally
The command below creates a terality.DataFrame by importing a pandas.DataFrame:
import pandas as pdimport terality as tedf_pd = pd.DataFrame({"col1": [1, 2, 2], "col2": [4, 5, 6]})df_te = te.DataFrame.from_pandas(df_pd)
Now, that the data is in Terality’s Cloud, we can proceed with analysis:
df_te.col1.value_counts()
Running filtering operations and other familiar pandas operations:
df_te[(df_te["col1"] >= 2)]
Once we finish with the analysis, we can convert it back to a pandas DataFrame with:
df_pd_roundtrip = df_te.to_pandas()
We can validate that the DataFrames are equal:
pd.testing.assert_frame_equal(df_pd, df_pd_roundtrip)
I would suggest you check Terality’s Quick Start Jupyter Notebook, which takes you through an analysis of 40 GB of Reddit comments dataset. They also have a tutorial with a smaller 5 GB dataset.
I clicked through Terality’s Jupyter Notebook and processed the 40 GB dataset. It read the data in 45 seconds and needed 35 seconds to sort it. The merge with another table took 1 minute and 17 seconds. It felt like I’m processing a much smaller dataset on my laptop.
Then I tried loading the same 40GB dataset with pandas on my laptop with 16 GB of main memory — it returned an out-of-memory exception.
I played with Terality quite a bit and my experience was without major issues. This surprised me as they are officially still in beta. A great sign is also that their support team is really responsive.
I see a great use case for Terality when you have a big data set that you can’t process on your local machine — may that be because of memory constraints or the speed of processing.
Using Dask (or Spark) would require spinning up a cluster which would cost much more than using Terality to complete your analysis.
Also, configuring such a cluster is a cumbersome process, while with Terality you only need to change the import statement.
Another thing that I like is that I can use it in my local JupyterLab, because I have many extensions, configurations, dark mode, etc.
I’m looking forward to the progress that the team makes with Terality in the coming months. | [
{
"code": null,
"e": 339,
"s": 172,
"text": "Data Science is having its renaissance moment. It's hard to keep track of all new Data Science tools that have the potential to change the way Data Science gets done."
},
{
"code": null,
"e": 590,
"s": 339,
"text": "I learned about this new Data Processing Engine only recently in a conversation with a colleague, also a Data Scientist. We had a discussion about Big Data processing, which is at the forefront of innovation in the field, and this new tool popped up."
},
{
"code": null,
"e": 764,
"s": 590,
"text": "While pandas is the defacto tool for data processing in Python, it doesn’t handle big data well. With bigger datasets, you’ll get an out-of-memory exception sooner or later."
},
{
"code": null,
"e": 988,
"s": 764,
"text": "Researchers were confronted with this issue a long time ago, which prompted the development of tools like Dask and Spark, which try to overcome “the single machine” constrain by distributing processing to multiple machines."
},
{
"code": null,
"e": 1146,
"s": 988,
"text": "This active area of innovation also brought us tools like Vaex, which try to solve this issue by making processing on a single machine more memory efficient."
},
{
"code": null,
"e": 1244,
"s": 1146,
"text": "And it doesn’t end there. There is another tool for big data processing you should know about ..."
},
{
"code": null,
"e": 1481,
"s": 1244,
"text": "Terality is a Serverless Data Processing Engine that processes the data in the Cloud. There is no need to manage infrastructure as Terality takes care of scaling compute resources. Its target audiences are Engineers and Data Scientists."
},
{
"code": null,
"e": 1642,
"s": 1481,
"text": "I exchanged a few emails with the Terality’s team as I was interested in the tool they’ve developed. They answered swiftly. These were my questions to the team:"
},
{
"code": null,
"e": 2009,
"s": 1642,
"text": "Terality comes with a Python client that you import into a Jupyter Notebook.Then you write the code in “a pandas way” and Terality securely uploads your data and takes care of distributed processing (and scaling) to calculate your analysis.After processing is completed, you can convert the data back to a regular pandas DataFrame and continue with analysis locally."
},
{
"code": null,
"e": 2086,
"s": 2009,
"text": "Terality comes with a Python client that you import into a Jupyter Notebook."
},
{
"code": null,
"e": 2251,
"s": 2086,
"text": "Then you write the code in “a pandas way” and Terality securely uploads your data and takes care of distributed processing (and scaling) to calculate your analysis."
},
{
"code": null,
"e": 2378,
"s": 2251,
"text": "After processing is completed, you can convert the data back to a regular pandas DataFrame and continue with analysis locally."
},
{
"code": null,
"e": 2475,
"s": 2378,
"text": "Terality team developed a proprietary data processing engine — it’s not a fork of Spark or Dask."
},
{
"code": null,
"e": 2660,
"s": 2475,
"text": "The goal was to avoid the imperfections of Dask, which doesn’t have the same syntax as pandas, it’s asynchronous, doesn’t have all pandas functions and it doesn’t support auto-scaling."
},
{
"code": null,
"e": 2715,
"s": 2660,
"text": "Terality’s Data Processing Engine solves these issues."
},
{
"code": null,
"e": 2883,
"s": 2715,
"text": "Terality has a free plan with which you can process up to 500 GB of data per month. It also offers a paid plan for companies and individuals with greater requirements."
},
{
"code": null,
"e": 2973,
"s": 2883,
"text": "In this article, we’ll focus on the free plan as it’s applicable to many Data Scientists."
},
{
"code": null,
"e": 3045,
"s": 2973,
"text": "How does Terality calculate data usage? (From Terality’s documentation)"
},
{
"code": null,
"e": 3299,
"s": 3045,
"text": "Consider a dataset with a total size of 15GB in memory, as would be returned by the operation df.memory_usage(deep=True).sum().Running one (1) operation on this dataset, such as a .sum or a .sort_values, would consume 15GB of processed data in Terality."
},
{
"code": null,
"e": 3373,
"s": 3299,
"text": "The billable usage is only recorded when task runs enter a Success state."
},
{
"code": null,
"e": 3501,
"s": 3373,
"text": "When a user performs a read operation, the Terality client copies the dataset on Terality’s secured cloud storage on Amazon S3."
},
{
"code": null,
"e": 3636,
"s": 3501,
"text": "Terality has a strict policy around data privacy and protection. They guarantee that they’ll not use the data and process it securely."
},
{
"code": null,
"e": 3764,
"s": 3636,
"text": "Terality is not a storage solution. They will delete your data maximum within 3 days after Terality’s client session is closed."
},
{
"code": null,
"e": 3833,
"s": 3764,
"text": "Terality processing currently occurs on AWS in the Frankfurt region."
},
{
"code": null,
"e": 3880,
"s": 3833,
"text": "See the security section for more information."
},
{
"code": null,
"e": 3884,
"s": 3880,
"text": "No!"
},
{
"code": null,
"e": 4015,
"s": 3884,
"text": "The user needs to have access to the dataset on his local machine and Terality will handle the uploading process behind the scene."
},
{
"code": null,
"e": 4076,
"s": 4015,
"text": "The upload operation is also parallelized so that is faster."
},
{
"code": null,
"e": 4182,
"s": 4076,
"text": "At the moment, in November 2021, Terality is still in beta. It’s optimized for datasets up to 100–200 GB."
},
{
"code": null,
"e": 4284,
"s": 4182,
"text": "I asked the team if they plan to increase this and they plan to soon start to optimize for Terabytes."
},
{
"code": null,
"e": 4409,
"s": 4284,
"text": "I was surprised that you can simply drop in replace pandas import statement with Terality’s package and rerun your analysis."
},
{
"code": null,
"e": 4584,
"s": 4409,
"text": "Note, once you import Terality’s python client, the data processing is not any longer performed on your local machine but with Terality’s Data Processing Engine in the Cloud."
},
{
"code": null,
"e": 4638,
"s": 4584,
"text": "Now, let’s install Terality and try it in practice..."
},
{
"code": null,
"e": 4682,
"s": 4638,
"text": "You can install Terality by simply running:"
},
{
"code": null,
"e": 4713,
"s": 4682,
"text": "pip install --upgrade terality"
},
{
"code": null,
"e": 4781,
"s": 4713,
"text": "Then you create a free account on Terality and generate an API key:"
},
{
"code": null,
"e": 4862,
"s": 4781,
"text": "The last step is to enter your API key (also replace the email with your email):"
},
{
"code": null,
"e": 4912,
"s": 4862,
"text": "terality account configure --email [email protected]"
},
{
"code": null,
"e": 5002,
"s": 4912,
"text": "Now, that we have Terality installed, we can run a small example to get familiar with it."
},
{
"code": null,
"e": 5170,
"s": 5002,
"text": "The practice shows that you get the best of both worlds while using both Terality and pandas — one to aggregate the data and the other to analyze the aggregate locally"
},
{
"code": null,
"e": 5250,
"s": 5170,
"text": "The command below creates a terality.DataFrame by importing a pandas.DataFrame:"
},
{
"code": null,
"e": 5390,
"s": 5250,
"text": "import pandas as pdimport terality as tedf_pd = pd.DataFrame({\"col1\": [1, 2, 2], \"col2\": [4, 5, 6]})df_te = te.DataFrame.from_pandas(df_pd)"
},
{
"code": null,
"e": 5463,
"s": 5390,
"text": "Now, that the data is in Terality’s Cloud, we can proceed with analysis:"
},
{
"code": null,
"e": 5489,
"s": 5463,
"text": "df_te.col1.value_counts()"
},
{
"code": null,
"e": 5556,
"s": 5489,
"text": "Running filtering operations and other familiar pandas operations:"
},
{
"code": null,
"e": 5584,
"s": 5556,
"text": "df_te[(df_te[\"col1\"] >= 2)]"
},
{
"code": null,
"e": 5669,
"s": 5584,
"text": "Once we finish with the analysis, we can convert it back to a pandas DataFrame with:"
},
{
"code": null,
"e": 5705,
"s": 5669,
"text": "df_pd_roundtrip = df_te.to_pandas()"
},
{
"code": null,
"e": 5752,
"s": 5705,
"text": "We can validate that the DataFrames are equal:"
},
{
"code": null,
"e": 5806,
"s": 5752,
"text": "pd.testing.assert_frame_equal(df_pd, df_pd_roundtrip)"
},
{
"code": null,
"e": 6001,
"s": 5806,
"text": "I would suggest you check Terality’s Quick Start Jupyter Notebook, which takes you through an analysis of 40 GB of Reddit comments dataset. They also have a tutorial with a smaller 5 GB dataset."
},
{
"code": null,
"e": 6269,
"s": 6001,
"text": "I clicked through Terality’s Jupyter Notebook and processed the 40 GB dataset. It read the data in 45 seconds and needed 35 seconds to sort it. The merge with another table took 1 minute and 17 seconds. It felt like I’m processing a much smaller dataset on my laptop."
},
{
"code": null,
"e": 6405,
"s": 6269,
"text": "Then I tried loading the same 40GB dataset with pandas on my laptop with 16 GB of main memory — it returned an out-of-memory exception."
},
{
"code": null,
"e": 6607,
"s": 6405,
"text": "I played with Terality quite a bit and my experience was without major issues. This surprised me as they are officially still in beta. A great sign is also that their support team is really responsive."
},
{
"code": null,
"e": 6789,
"s": 6607,
"text": "I see a great use case for Terality when you have a big data set that you can’t process on your local machine — may that be because of memory constraints or the speed of processing."
},
{
"code": null,
"e": 6921,
"s": 6789,
"text": "Using Dask (or Spark) would require spinning up a cluster which would cost much more than using Terality to complete your analysis."
},
{
"code": null,
"e": 7045,
"s": 6921,
"text": "Also, configuring such a cluster is a cumbersome process, while with Terality you only need to change the import statement."
},
{
"code": null,
"e": 7180,
"s": 7045,
"text": "Another thing that I like is that I can use it in my local JupyterLab, because I have many extensions, configurations, dark mode, etc."
}
] |
Immutable Map in Java - GeeksforGeeks | 11 Dec, 2018
ImmutableMap, as suggested by the name, is a type of Map which is immutable. It means that the content of the map are fixed or constant after declaration, that is, they are read-only.
If any attempt made to add, delete and update elements in the Map, UnsupportedOperationException is thrown.
An ImmutableMap does not allow null element either.
If any attempt made to create an ImmutableMap with null element, NullPointerException is thrown. If any attempt is made to add null element in Map, UnsupportedOperationException is thrown.
Advantages of ImmutableMap
They are thread safe.
They are memory efficient.
Since they are immutable, hence they can be passed over to third party libraries without any problem.
Note that it is an immutable collection, not collection of immutable objects, so the objects inside it can be modified.Class Declaration:
@GwtCompatible(serializable=true,
emulated=true)
public abstract class ImmutableMap
extends Object
implements Map, Serializable
Class hierarchy:
java.lang.Object
↳ com.google.common.collect.ImmutableMap
Creating ImmutableMapImmutableMap can be created by various methods. These include:
From existing Map using copyOf() function of Guava// Below is the Java program to create ImmutableMap import com.google.common.collect.ImmutableMap;import java.util.HashMap;import java.util.Map; class MapUtil { // Function to create ImmutableMap from Map public static <K, T> void iMap(Map<K, T> map) { // Create ImmutableMap from Map using copyOf() ImmutableMap<K, T> immutableMap = ImmutableMap.copyOf(map); // Print the ImmutableMap System.out.println(immutableMap); } public static void main(String[] args) { Map<Integer, String> map = new HashMap<Integer, String>(); map.put(1, "Geeks"); map.put(2, "For"); map.put(3, "Geeks"); iMap(map); }}Output:{1=Geeks, 2=For, 3=Geeks}
New ImmutableMap using of() function from Guava// Below is the Java program to create ImmutableMapimport com.google.common.collect.ImmutableMap;import java.util.HashMap;import java.util.Map; class MapUtil { // Function to create ImmutableMap public static void createImmutableMap() { // Create ImmutableMap using of() ImmutableMap<Integer, String> immutableMap = ImmutableMap.of( 1, "Geeks", 2, "For", 3, "Geeks"); // Print the ImmutableMap System.out.println(immutableMap); } public static void main(String[] args) { createImmutableMap(); }}Output:{1=Geeks, 2=For, 3=Geeks}
Using Java 9 Factory Of() methodIn Java, use of() with Set, Map or List to create an Immutable Map.Please Note: The programs below are of Java 9. Hence you would need a Java 9 compiler to run them.// Java code illustrating of() method to// create a ImmutableSetimport java.util.*;import com.google.common.collect.ImmutableMap; class GfG { public static void main(String args[]) { // non-empty immutable set Map<Integer, String> map = Map.of( 1, "Geeks", 2, "For", 3, "Geeks"); // Let's print the set System.out.println(map); }}Output:{1=Geeks, 2=For, 3=Geeks}
Using Builder() from ImmutableMapIn Guava, ImmnutableMap class provides a function Builder(). Through this function, a new ImmutableMap can be created, oran ImmutableMap can be created from an existing Map or both.Creating a new ImmutableMap// Java code illustrating of() method to// create a ImmutableSetimport java.util.*;import com.google.common.collect.ImmutableMap; class GfG { public static void main(String args[]) { // non-empty immutable set ImmutableMap<Integer, String> imap = ImmutableMap.<Integer, String>builder() .put(1, "Geeks") .put(2, "For") .put(3, "Geeks") .build(); // Let's print the set System.out.println(imap); }}Output:{1=Geeks, 2=For, 3=Geeks}
Creating an ImmutableMap from existing Map// Java code illustrating of() method to// create a ImmutableSetimport java.util.*;import com.google.common.collect.ImmutableMap; class GfG { public static void main(String args[]) { // non-empty immutable set Map<Integer, String> map = Map.of(1, "Geeks", 2, "For", 3, "Geeks"); ImmutableMap<Integer, String> imap = ImmutableMap.<Integer, String>builder() .putAll(map) .build(); // Let's print the set System.out.println(imap); }}Output:{1=Geeks, 2=For, 3=Geeks}
Creating a new ImmutableMap including the existing Map// Java code illustrating of() method to// create a ImmutableSetimport java.util.*;import com.google.common.collect.ImmutableMap; class GfG { public static void main(String args[]) { // non-empty immutable set Map<Integer, String> map = Map.of(1, "Geeks", 2, "For", 3, "Geeks"); ImmutableMap<Integer, String> imap = ImmutableMap.<Integer, String>builder() .putAll(map) .put(4, "Computer") .put(5, "Portal") .build(); // Let's print the set System.out.println(imap); }}Output:{1=Geeks, 2=For, 3=Geeks, 4=Computer, 5=Portal}
From existing Map using copyOf() function of Guava// Below is the Java program to create ImmutableMap import com.google.common.collect.ImmutableMap;import java.util.HashMap;import java.util.Map; class MapUtil { // Function to create ImmutableMap from Map public static <K, T> void iMap(Map<K, T> map) { // Create ImmutableMap from Map using copyOf() ImmutableMap<K, T> immutableMap = ImmutableMap.copyOf(map); // Print the ImmutableMap System.out.println(immutableMap); } public static void main(String[] args) { Map<Integer, String> map = new HashMap<Integer, String>(); map.put(1, "Geeks"); map.put(2, "For"); map.put(3, "Geeks"); iMap(map); }}Output:{1=Geeks, 2=For, 3=Geeks}
// Below is the Java program to create ImmutableMap import com.google.common.collect.ImmutableMap;import java.util.HashMap;import java.util.Map; class MapUtil { // Function to create ImmutableMap from Map public static <K, T> void iMap(Map<K, T> map) { // Create ImmutableMap from Map using copyOf() ImmutableMap<K, T> immutableMap = ImmutableMap.copyOf(map); // Print the ImmutableMap System.out.println(immutableMap); } public static void main(String[] args) { Map<Integer, String> map = new HashMap<Integer, String>(); map.put(1, "Geeks"); map.put(2, "For"); map.put(3, "Geeks"); iMap(map); }}
Output:
{1=Geeks, 2=For, 3=Geeks}
New ImmutableMap using of() function from Guava// Below is the Java program to create ImmutableMapimport com.google.common.collect.ImmutableMap;import java.util.HashMap;import java.util.Map; class MapUtil { // Function to create ImmutableMap public static void createImmutableMap() { // Create ImmutableMap using of() ImmutableMap<Integer, String> immutableMap = ImmutableMap.of( 1, "Geeks", 2, "For", 3, "Geeks"); // Print the ImmutableMap System.out.println(immutableMap); } public static void main(String[] args) { createImmutableMap(); }}Output:{1=Geeks, 2=For, 3=Geeks}
// Below is the Java program to create ImmutableMapimport com.google.common.collect.ImmutableMap;import java.util.HashMap;import java.util.Map; class MapUtil { // Function to create ImmutableMap public static void createImmutableMap() { // Create ImmutableMap using of() ImmutableMap<Integer, String> immutableMap = ImmutableMap.of( 1, "Geeks", 2, "For", 3, "Geeks"); // Print the ImmutableMap System.out.println(immutableMap); } public static void main(String[] args) { createImmutableMap(); }}
Output:
{1=Geeks, 2=For, 3=Geeks}
Using Java 9 Factory Of() methodIn Java, use of() with Set, Map or List to create an Immutable Map.Please Note: The programs below are of Java 9. Hence you would need a Java 9 compiler to run them.// Java code illustrating of() method to// create a ImmutableSetimport java.util.*;import com.google.common.collect.ImmutableMap; class GfG { public static void main(String args[]) { // non-empty immutable set Map<Integer, String> map = Map.of( 1, "Geeks", 2, "For", 3, "Geeks"); // Let's print the set System.out.println(map); }}Output:{1=Geeks, 2=For, 3=Geeks}
In Java, use of() with Set, Map or List to create an Immutable Map.
Please Note: The programs below are of Java 9. Hence you would need a Java 9 compiler to run them.
// Java code illustrating of() method to// create a ImmutableSetimport java.util.*;import com.google.common.collect.ImmutableMap; class GfG { public static void main(String args[]) { // non-empty immutable set Map<Integer, String> map = Map.of( 1, "Geeks", 2, "For", 3, "Geeks"); // Let's print the set System.out.println(map); }}
Output:
{1=Geeks, 2=For, 3=Geeks}
Using Builder() from ImmutableMapIn Guava, ImmnutableMap class provides a function Builder(). Through this function, a new ImmutableMap can be created, oran ImmutableMap can be created from an existing Map or both.Creating a new ImmutableMap// Java code illustrating of() method to// create a ImmutableSetimport java.util.*;import com.google.common.collect.ImmutableMap; class GfG { public static void main(String args[]) { // non-empty immutable set ImmutableMap<Integer, String> imap = ImmutableMap.<Integer, String>builder() .put(1, "Geeks") .put(2, "For") .put(3, "Geeks") .build(); // Let's print the set System.out.println(imap); }}Output:{1=Geeks, 2=For, 3=Geeks}
Creating an ImmutableMap from existing Map// Java code illustrating of() method to// create a ImmutableSetimport java.util.*;import com.google.common.collect.ImmutableMap; class GfG { public static void main(String args[]) { // non-empty immutable set Map<Integer, String> map = Map.of(1, "Geeks", 2, "For", 3, "Geeks"); ImmutableMap<Integer, String> imap = ImmutableMap.<Integer, String>builder() .putAll(map) .build(); // Let's print the set System.out.println(imap); }}Output:{1=Geeks, 2=For, 3=Geeks}
Creating a new ImmutableMap including the existing Map// Java code illustrating of() method to// create a ImmutableSetimport java.util.*;import com.google.common.collect.ImmutableMap; class GfG { public static void main(String args[]) { // non-empty immutable set Map<Integer, String> map = Map.of(1, "Geeks", 2, "For", 3, "Geeks"); ImmutableMap<Integer, String> imap = ImmutableMap.<Integer, String>builder() .putAll(map) .put(4, "Computer") .put(5, "Portal") .build(); // Let's print the set System.out.println(imap); }}Output:{1=Geeks, 2=For, 3=Geeks, 4=Computer, 5=Portal}
In Guava, ImmnutableMap class provides a function Builder(). Through this function, a new ImmutableMap can be created, oran ImmutableMap can be created from an existing Map or both.
Creating a new ImmutableMap// Java code illustrating of() method to// create a ImmutableSetimport java.util.*;import com.google.common.collect.ImmutableMap; class GfG { public static void main(String args[]) { // non-empty immutable set ImmutableMap<Integer, String> imap = ImmutableMap.<Integer, String>builder() .put(1, "Geeks") .put(2, "For") .put(3, "Geeks") .build(); // Let's print the set System.out.println(imap); }}Output:{1=Geeks, 2=For, 3=Geeks}
// Java code illustrating of() method to// create a ImmutableSetimport java.util.*;import com.google.common.collect.ImmutableMap; class GfG { public static void main(String args[]) { // non-empty immutable set ImmutableMap<Integer, String> imap = ImmutableMap.<Integer, String>builder() .put(1, "Geeks") .put(2, "For") .put(3, "Geeks") .build(); // Let's print the set System.out.println(imap); }}
Output:
{1=Geeks, 2=For, 3=Geeks}
Creating an ImmutableMap from existing Map// Java code illustrating of() method to// create a ImmutableSetimport java.util.*;import com.google.common.collect.ImmutableMap; class GfG { public static void main(String args[]) { // non-empty immutable set Map<Integer, String> map = Map.of(1, "Geeks", 2, "For", 3, "Geeks"); ImmutableMap<Integer, String> imap = ImmutableMap.<Integer, String>builder() .putAll(map) .build(); // Let's print the set System.out.println(imap); }}Output:{1=Geeks, 2=For, 3=Geeks}
// Java code illustrating of() method to// create a ImmutableSetimport java.util.*;import com.google.common.collect.ImmutableMap; class GfG { public static void main(String args[]) { // non-empty immutable set Map<Integer, String> map = Map.of(1, "Geeks", 2, "For", 3, "Geeks"); ImmutableMap<Integer, String> imap = ImmutableMap.<Integer, String>builder() .putAll(map) .build(); // Let's print the set System.out.println(imap); }}
Output:
{1=Geeks, 2=For, 3=Geeks}
Creating a new ImmutableMap including the existing Map// Java code illustrating of() method to// create a ImmutableSetimport java.util.*;import com.google.common.collect.ImmutableMap; class GfG { public static void main(String args[]) { // non-empty immutable set Map<Integer, String> map = Map.of(1, "Geeks", 2, "For", 3, "Geeks"); ImmutableMap<Integer, String> imap = ImmutableMap.<Integer, String>builder() .putAll(map) .put(4, "Computer") .put(5, "Portal") .build(); // Let's print the set System.out.println(imap); }}Output:{1=Geeks, 2=For, 3=Geeks, 4=Computer, 5=Portal}
// Java code illustrating of() method to// create a ImmutableSetimport java.util.*;import com.google.common.collect.ImmutableMap; class GfG { public static void main(String args[]) { // non-empty immutable set Map<Integer, String> map = Map.of(1, "Geeks", 2, "For", 3, "Geeks"); ImmutableMap<Integer, String> imap = ImmutableMap.<Integer, String>builder() .putAll(map) .put(4, "Computer") .put(5, "Portal") .build(); // Let's print the set System.out.println(imap); }}
Output:
{1=Geeks, 2=For, 3=Geeks, 4=Computer, 5=Portal}
Try to change ImmutableMap
As mentioned earlier, the below program will throw UnsupportedOperationException.
// Java code to show that UnsupportedOperationException// will be thrown when ImmutableMap is modified.import java.util.*; class GfG { public static void main(String args[]) { // empty immutable map Map<Integer, String> map = Map.of(); // Lets try adding element in these set map.put(1, "Geeks"); map.put(2, "For"); map.put(3, "Geeks"); }}
Output :
Exception in thread "main" java.lang.UnsupportedOperationException
at com.google.common.collect.ImmutableCollection.add(ImmutableCollection.java:218)
at ImmutableListDemo.main(Main.java:16)
How is it different from Collections.unmodifiableMap()?
Collections.unmodifiableMap creates a wrapper around the same existing Map such that the wrapper cannot be used to modify it. However we can still change original Map.
// Java program to demonstrate that a Map created using// Collections.unmodifiableMap() can be modified indirectly.import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { Map<Integer, String> map = new HashMap<Integer, String>(); map.put(1, "Geeks"); map.put(2, "For"); map.put(3, "Geeks"); // Create ImmutableMap from Map using copyOf() Map<Integer, String> imap = Collections.unmodifiableMap(map); // We change map and the changes reflect in imap. map.put(4, "Computer"); map.put(5, "Portal"); System.out.println(imap); }}
Output:
{1=Geeks, 2=For, 3=Geeks, 4=Computer, 5=Portal}
If we create an ImmutableMap from an existing Map and change the existing Map, the ImmutableMap does not change because a copy is created.
// Below is a Java program for// Creating an immutable Map using copyOf()// and modifying original Map.import java.io.*;import java.util.*;import com.google.common.collect.ImmutableMap; class GFG { public static void main(String[] args) { Map<Integer, String> map = new HashMap<Integer, String>(); map.put(1, "Geeks"); map.put(2, "For"); map.put(3, "Geeks"); // Create ImmutableMap from Map using copyOf() ImmutableMap<Integer, String> imap = ImmutableMap.copyOf(map); // We change map and the changes wont reflect in imap. map.put(4, "Computer"); map.put(5, "Portal"); System.out.println(imap); }}
Output :
{1=Geeks, 2=For, 3=Geeks}
Java - util package
Java-Collections
java-guava
java-map
Java-Map-Programs
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Initialize an ArrayList in Java
Interfaces in Java
ArrayList in Java
Multidimensional Arrays in Java
Singleton Class in Java
Multithreading in Java
Stack Class in Java
LinkedList in Java
Collections in Java
Overriding in Java | [
{
"code": null,
"e": 24220,
"s": 24192,
"text": "\n11 Dec, 2018"
},
{
"code": null,
"e": 24404,
"s": 24220,
"text": "ImmutableMap, as suggested by the name, is a type of Map which is immutable. It means that the content of the map are fixed or constant after declaration, that is, they are read-only."
},
{
"code": null,
"e": 24512,
"s": 24404,
"text": "If any attempt made to add, delete and update elements in the Map, UnsupportedOperationException is thrown."
},
{
"code": null,
"e": 24564,
"s": 24512,
"text": "An ImmutableMap does not allow null element either."
},
{
"code": null,
"e": 24753,
"s": 24564,
"text": "If any attempt made to create an ImmutableMap with null element, NullPointerException is thrown. If any attempt is made to add null element in Map, UnsupportedOperationException is thrown."
},
{
"code": null,
"e": 24780,
"s": 24753,
"text": "Advantages of ImmutableMap"
},
{
"code": null,
"e": 24802,
"s": 24780,
"text": "They are thread safe."
},
{
"code": null,
"e": 24829,
"s": 24802,
"text": "They are memory efficient."
},
{
"code": null,
"e": 24931,
"s": 24829,
"text": "Since they are immutable, hence they can be passed over to third party libraries without any problem."
},
{
"code": null,
"e": 25069,
"s": 24931,
"text": "Note that it is an immutable collection, not collection of immutable objects, so the objects inside it can be modified.Class Declaration:"
},
{
"code": null,
"e": 25213,
"s": 25069,
"text": "@GwtCompatible(serializable=true,\n emulated=true)\npublic abstract class ImmutableMap\nextends Object\nimplements Map, Serializable\n"
},
{
"code": null,
"e": 25230,
"s": 25213,
"text": "Class hierarchy:"
},
{
"code": null,
"e": 25292,
"s": 25230,
"text": "java.lang.Object\n ↳ com.google.common.collect.ImmutableMap \n"
},
{
"code": null,
"e": 25376,
"s": 25292,
"text": "Creating ImmutableMapImmutableMap can be created by various methods. These include:"
},
{
"code": null,
"e": 30038,
"s": 25376,
"text": "From existing Map using copyOf() function of Guava// Below is the Java program to create ImmutableMap import com.google.common.collect.ImmutableMap;import java.util.HashMap;import java.util.Map; class MapUtil { // Function to create ImmutableMap from Map public static <K, T> void iMap(Map<K, T> map) { // Create ImmutableMap from Map using copyOf() ImmutableMap<K, T> immutableMap = ImmutableMap.copyOf(map); // Print the ImmutableMap System.out.println(immutableMap); } public static void main(String[] args) { Map<Integer, String> map = new HashMap<Integer, String>(); map.put(1, \"Geeks\"); map.put(2, \"For\"); map.put(3, \"Geeks\"); iMap(map); }}Output:{1=Geeks, 2=For, 3=Geeks}\nNew ImmutableMap using of() function from Guava// Below is the Java program to create ImmutableMapimport com.google.common.collect.ImmutableMap;import java.util.HashMap;import java.util.Map; class MapUtil { // Function to create ImmutableMap public static void createImmutableMap() { // Create ImmutableMap using of() ImmutableMap<Integer, String> immutableMap = ImmutableMap.of( 1, \"Geeks\", 2, \"For\", 3, \"Geeks\"); // Print the ImmutableMap System.out.println(immutableMap); } public static void main(String[] args) { createImmutableMap(); }}Output:{1=Geeks, 2=For, 3=Geeks}\nUsing Java 9 Factory Of() methodIn Java, use of() with Set, Map or List to create an Immutable Map.Please Note: The programs below are of Java 9. Hence you would need a Java 9 compiler to run them.// Java code illustrating of() method to// create a ImmutableSetimport java.util.*;import com.google.common.collect.ImmutableMap; class GfG { public static void main(String args[]) { // non-empty immutable set Map<Integer, String> map = Map.of( 1, \"Geeks\", 2, \"For\", 3, \"Geeks\"); // Let's print the set System.out.println(map); }}Output:{1=Geeks, 2=For, 3=Geeks}\nUsing Builder() from ImmutableMapIn Guava, ImmnutableMap class provides a function Builder(). Through this function, a new ImmutableMap can be created, oran ImmutableMap can be created from an existing Map or both.Creating a new ImmutableMap// Java code illustrating of() method to// create a ImmutableSetimport java.util.*;import com.google.common.collect.ImmutableMap; class GfG { public static void main(String args[]) { // non-empty immutable set ImmutableMap<Integer, String> imap = ImmutableMap.<Integer, String>builder() .put(1, \"Geeks\") .put(2, \"For\") .put(3, \"Geeks\") .build(); // Let's print the set System.out.println(imap); }}Output:{1=Geeks, 2=For, 3=Geeks}\nCreating an ImmutableMap from existing Map// Java code illustrating of() method to// create a ImmutableSetimport java.util.*;import com.google.common.collect.ImmutableMap; class GfG { public static void main(String args[]) { // non-empty immutable set Map<Integer, String> map = Map.of(1, \"Geeks\", 2, \"For\", 3, \"Geeks\"); ImmutableMap<Integer, String> imap = ImmutableMap.<Integer, String>builder() .putAll(map) .build(); // Let's print the set System.out.println(imap); }}Output:{1=Geeks, 2=For, 3=Geeks}\nCreating a new ImmutableMap including the existing Map// Java code illustrating of() method to// create a ImmutableSetimport java.util.*;import com.google.common.collect.ImmutableMap; class GfG { public static void main(String args[]) { // non-empty immutable set Map<Integer, String> map = Map.of(1, \"Geeks\", 2, \"For\", 3, \"Geeks\"); ImmutableMap<Integer, String> imap = ImmutableMap.<Integer, String>builder() .putAll(map) .put(4, \"Computer\") .put(5, \"Portal\") .build(); // Let's print the set System.out.println(imap); }}Output:{1=Geeks, 2=For, 3=Geeks, 4=Computer, 5=Portal}\n"
},
{
"code": null,
"e": 30810,
"s": 30038,
"text": "From existing Map using copyOf() function of Guava// Below is the Java program to create ImmutableMap import com.google.common.collect.ImmutableMap;import java.util.HashMap;import java.util.Map; class MapUtil { // Function to create ImmutableMap from Map public static <K, T> void iMap(Map<K, T> map) { // Create ImmutableMap from Map using copyOf() ImmutableMap<K, T> immutableMap = ImmutableMap.copyOf(map); // Print the ImmutableMap System.out.println(immutableMap); } public static void main(String[] args) { Map<Integer, String> map = new HashMap<Integer, String>(); map.put(1, \"Geeks\"); map.put(2, \"For\"); map.put(3, \"Geeks\"); iMap(map); }}Output:{1=Geeks, 2=For, 3=Geeks}\n"
},
{
"code": "// Below is the Java program to create ImmutableMap import com.google.common.collect.ImmutableMap;import java.util.HashMap;import java.util.Map; class MapUtil { // Function to create ImmutableMap from Map public static <K, T> void iMap(Map<K, T> map) { // Create ImmutableMap from Map using copyOf() ImmutableMap<K, T> immutableMap = ImmutableMap.copyOf(map); // Print the ImmutableMap System.out.println(immutableMap); } public static void main(String[] args) { Map<Integer, String> map = new HashMap<Integer, String>(); map.put(1, \"Geeks\"); map.put(2, \"For\"); map.put(3, \"Geeks\"); iMap(map); }}",
"e": 31499,
"s": 30810,
"text": null
},
{
"code": null,
"e": 31507,
"s": 31499,
"text": "Output:"
},
{
"code": null,
"e": 31534,
"s": 31507,
"text": "{1=Geeks, 2=For, 3=Geeks}\n"
},
{
"code": null,
"e": 32206,
"s": 31534,
"text": "New ImmutableMap using of() function from Guava// Below is the Java program to create ImmutableMapimport com.google.common.collect.ImmutableMap;import java.util.HashMap;import java.util.Map; class MapUtil { // Function to create ImmutableMap public static void createImmutableMap() { // Create ImmutableMap using of() ImmutableMap<Integer, String> immutableMap = ImmutableMap.of( 1, \"Geeks\", 2, \"For\", 3, \"Geeks\"); // Print the ImmutableMap System.out.println(immutableMap); } public static void main(String[] args) { createImmutableMap(); }}Output:{1=Geeks, 2=For, 3=Geeks}\n"
},
{
"code": "// Below is the Java program to create ImmutableMapimport com.google.common.collect.ImmutableMap;import java.util.HashMap;import java.util.Map; class MapUtil { // Function to create ImmutableMap public static void createImmutableMap() { // Create ImmutableMap using of() ImmutableMap<Integer, String> immutableMap = ImmutableMap.of( 1, \"Geeks\", 2, \"For\", 3, \"Geeks\"); // Print the ImmutableMap System.out.println(immutableMap); } public static void main(String[] args) { createImmutableMap(); }}",
"e": 32798,
"s": 32206,
"text": null
},
{
"code": null,
"e": 32806,
"s": 32798,
"text": "Output:"
},
{
"code": null,
"e": 32833,
"s": 32806,
"text": "{1=Geeks, 2=For, 3=Geeks}\n"
},
{
"code": null,
"e": 33467,
"s": 32833,
"text": "Using Java 9 Factory Of() methodIn Java, use of() with Set, Map or List to create an Immutable Map.Please Note: The programs below are of Java 9. Hence you would need a Java 9 compiler to run them.// Java code illustrating of() method to// create a ImmutableSetimport java.util.*;import com.google.common.collect.ImmutableMap; class GfG { public static void main(String args[]) { // non-empty immutable set Map<Integer, String> map = Map.of( 1, \"Geeks\", 2, \"For\", 3, \"Geeks\"); // Let's print the set System.out.println(map); }}Output:{1=Geeks, 2=For, 3=Geeks}\n"
},
{
"code": null,
"e": 33535,
"s": 33467,
"text": "In Java, use of() with Set, Map or List to create an Immutable Map."
},
{
"code": null,
"e": 33634,
"s": 33535,
"text": "Please Note: The programs below are of Java 9. Hence you would need a Java 9 compiler to run them."
},
{
"code": "// Java code illustrating of() method to// create a ImmutableSetimport java.util.*;import com.google.common.collect.ImmutableMap; class GfG { public static void main(String args[]) { // non-empty immutable set Map<Integer, String> map = Map.of( 1, \"Geeks\", 2, \"For\", 3, \"Geeks\"); // Let's print the set System.out.println(map); }}",
"e": 34038,
"s": 33634,
"text": null
},
{
"code": null,
"e": 34046,
"s": 34038,
"text": "Output:"
},
{
"code": null,
"e": 34073,
"s": 34046,
"text": "{1=Geeks, 2=For, 3=Geeks}\n"
},
{
"code": null,
"e": 36660,
"s": 34073,
"text": "Using Builder() from ImmutableMapIn Guava, ImmnutableMap class provides a function Builder(). Through this function, a new ImmutableMap can be created, oran ImmutableMap can be created from an existing Map or both.Creating a new ImmutableMap// Java code illustrating of() method to// create a ImmutableSetimport java.util.*;import com.google.common.collect.ImmutableMap; class GfG { public static void main(String args[]) { // non-empty immutable set ImmutableMap<Integer, String> imap = ImmutableMap.<Integer, String>builder() .put(1, \"Geeks\") .put(2, \"For\") .put(3, \"Geeks\") .build(); // Let's print the set System.out.println(imap); }}Output:{1=Geeks, 2=For, 3=Geeks}\nCreating an ImmutableMap from existing Map// Java code illustrating of() method to// create a ImmutableSetimport java.util.*;import com.google.common.collect.ImmutableMap; class GfG { public static void main(String args[]) { // non-empty immutable set Map<Integer, String> map = Map.of(1, \"Geeks\", 2, \"For\", 3, \"Geeks\"); ImmutableMap<Integer, String> imap = ImmutableMap.<Integer, String>builder() .putAll(map) .build(); // Let's print the set System.out.println(imap); }}Output:{1=Geeks, 2=For, 3=Geeks}\nCreating a new ImmutableMap including the existing Map// Java code illustrating of() method to// create a ImmutableSetimport java.util.*;import com.google.common.collect.ImmutableMap; class GfG { public static void main(String args[]) { // non-empty immutable set Map<Integer, String> map = Map.of(1, \"Geeks\", 2, \"For\", 3, \"Geeks\"); ImmutableMap<Integer, String> imap = ImmutableMap.<Integer, String>builder() .putAll(map) .put(4, \"Computer\") .put(5, \"Portal\") .build(); // Let's print the set System.out.println(imap); }}Output:{1=Geeks, 2=For, 3=Geeks, 4=Computer, 5=Portal}\n"
},
{
"code": null,
"e": 36842,
"s": 36660,
"text": "In Guava, ImmnutableMap class provides a function Builder(). Through this function, a new ImmutableMap can be created, oran ImmutableMap can be created from an existing Map or both."
},
{
"code": null,
"e": 37557,
"s": 36842,
"text": "Creating a new ImmutableMap// Java code illustrating of() method to// create a ImmutableSetimport java.util.*;import com.google.common.collect.ImmutableMap; class GfG { public static void main(String args[]) { // non-empty immutable set ImmutableMap<Integer, String> imap = ImmutableMap.<Integer, String>builder() .put(1, \"Geeks\") .put(2, \"For\") .put(3, \"Geeks\") .build(); // Let's print the set System.out.println(imap); }}Output:{1=Geeks, 2=For, 3=Geeks}\n"
},
{
"code": "// Java code illustrating of() method to// create a ImmutableSetimport java.util.*;import com.google.common.collect.ImmutableMap; class GfG { public static void main(String args[]) { // non-empty immutable set ImmutableMap<Integer, String> imap = ImmutableMap.<Integer, String>builder() .put(1, \"Geeks\") .put(2, \"For\") .put(3, \"Geeks\") .build(); // Let's print the set System.out.println(imap); }}",
"e": 38212,
"s": 37557,
"text": null
},
{
"code": null,
"e": 38220,
"s": 38212,
"text": "Output:"
},
{
"code": null,
"e": 38247,
"s": 38220,
"text": "{1=Geeks, 2=For, 3=Geeks}\n"
},
{
"code": null,
"e": 39001,
"s": 38247,
"text": "Creating an ImmutableMap from existing Map// Java code illustrating of() method to// create a ImmutableSetimport java.util.*;import com.google.common.collect.ImmutableMap; class GfG { public static void main(String args[]) { // non-empty immutable set Map<Integer, String> map = Map.of(1, \"Geeks\", 2, \"For\", 3, \"Geeks\"); ImmutableMap<Integer, String> imap = ImmutableMap.<Integer, String>builder() .putAll(map) .build(); // Let's print the set System.out.println(imap); }}Output:{1=Geeks, 2=For, 3=Geeks}\n"
},
{
"code": "// Java code illustrating of() method to// create a ImmutableSetimport java.util.*;import com.google.common.collect.ImmutableMap; class GfG { public static void main(String args[]) { // non-empty immutable set Map<Integer, String> map = Map.of(1, \"Geeks\", 2, \"For\", 3, \"Geeks\"); ImmutableMap<Integer, String> imap = ImmutableMap.<Integer, String>builder() .putAll(map) .build(); // Let's print the set System.out.println(imap); }}",
"e": 39680,
"s": 39001,
"text": null
},
{
"code": null,
"e": 39688,
"s": 39680,
"text": "Output:"
},
{
"code": null,
"e": 39715,
"s": 39688,
"text": "{1=Geeks, 2=For, 3=Geeks}\n"
},
{
"code": null,
"e": 40621,
"s": 39715,
"text": "Creating a new ImmutableMap including the existing Map// Java code illustrating of() method to// create a ImmutableSetimport java.util.*;import com.google.common.collect.ImmutableMap; class GfG { public static void main(String args[]) { // non-empty immutable set Map<Integer, String> map = Map.of(1, \"Geeks\", 2, \"For\", 3, \"Geeks\"); ImmutableMap<Integer, String> imap = ImmutableMap.<Integer, String>builder() .putAll(map) .put(4, \"Computer\") .put(5, \"Portal\") .build(); // Let's print the set System.out.println(imap); }}Output:{1=Geeks, 2=For, 3=Geeks, 4=Computer, 5=Portal}\n"
},
{
"code": "// Java code illustrating of() method to// create a ImmutableSetimport java.util.*;import com.google.common.collect.ImmutableMap; class GfG { public static void main(String args[]) { // non-empty immutable set Map<Integer, String> map = Map.of(1, \"Geeks\", 2, \"For\", 3, \"Geeks\"); ImmutableMap<Integer, String> imap = ImmutableMap.<Integer, String>builder() .putAll(map) .put(4, \"Computer\") .put(5, \"Portal\") .build(); // Let's print the set System.out.println(imap); }}",
"e": 41418,
"s": 40621,
"text": null
},
{
"code": null,
"e": 41426,
"s": 41418,
"text": "Output:"
},
{
"code": null,
"e": 41475,
"s": 41426,
"text": "{1=Geeks, 2=For, 3=Geeks, 4=Computer, 5=Portal}\n"
},
{
"code": null,
"e": 41502,
"s": 41475,
"text": "Try to change ImmutableMap"
},
{
"code": null,
"e": 41584,
"s": 41502,
"text": "As mentioned earlier, the below program will throw UnsupportedOperationException."
},
{
"code": "// Java code to show that UnsupportedOperationException// will be thrown when ImmutableMap is modified.import java.util.*; class GfG { public static void main(String args[]) { // empty immutable map Map<Integer, String> map = Map.of(); // Lets try adding element in these set map.put(1, \"Geeks\"); map.put(2, \"For\"); map.put(3, \"Geeks\"); }}",
"e": 41978,
"s": 41584,
"text": null
},
{
"code": null,
"e": 41987,
"s": 41978,
"text": "Output :"
},
{
"code": null,
"e": 42186,
"s": 41987,
"text": "Exception in thread \"main\" java.lang.UnsupportedOperationException\n at com.google.common.collect.ImmutableCollection.add(ImmutableCollection.java:218)\n at ImmutableListDemo.main(Main.java:16)\n"
},
{
"code": null,
"e": 42242,
"s": 42186,
"text": "How is it different from Collections.unmodifiableMap()?"
},
{
"code": null,
"e": 42410,
"s": 42242,
"text": "Collections.unmodifiableMap creates a wrapper around the same existing Map such that the wrapper cannot be used to modify it. However we can still change original Map."
},
{
"code": "// Java program to demonstrate that a Map created using// Collections.unmodifiableMap() can be modified indirectly.import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { Map<Integer, String> map = new HashMap<Integer, String>(); map.put(1, \"Geeks\"); map.put(2, \"For\"); map.put(3, \"Geeks\"); // Create ImmutableMap from Map using copyOf() Map<Integer, String> imap = Collections.unmodifiableMap(map); // We change map and the changes reflect in imap. map.put(4, \"Computer\"); map.put(5, \"Portal\"); System.out.println(imap); }}",
"e": 43055,
"s": 42410,
"text": null
},
{
"code": null,
"e": 43063,
"s": 43055,
"text": "Output:"
},
{
"code": null,
"e": 43112,
"s": 43063,
"text": "{1=Geeks, 2=For, 3=Geeks, 4=Computer, 5=Portal}\n"
},
{
"code": null,
"e": 43251,
"s": 43112,
"text": "If we create an ImmutableMap from an existing Map and change the existing Map, the ImmutableMap does not change because a copy is created."
},
{
"code": "// Below is a Java program for// Creating an immutable Map using copyOf()// and modifying original Map.import java.io.*;import java.util.*;import com.google.common.collect.ImmutableMap; class GFG { public static void main(String[] args) { Map<Integer, String> map = new HashMap<Integer, String>(); map.put(1, \"Geeks\"); map.put(2, \"For\"); map.put(3, \"Geeks\"); // Create ImmutableMap from Map using copyOf() ImmutableMap<Integer, String> imap = ImmutableMap.copyOf(map); // We change map and the changes wont reflect in imap. map.put(4, \"Computer\"); map.put(5, \"Portal\"); System.out.println(imap); }}",
"e": 43936,
"s": 43251,
"text": null
},
{
"code": null,
"e": 43945,
"s": 43936,
"text": "Output :"
},
{
"code": null,
"e": 43972,
"s": 43945,
"text": "{1=Geeks, 2=For, 3=Geeks}\n"
},
{
"code": null,
"e": 43992,
"s": 43972,
"text": "Java - util package"
},
{
"code": null,
"e": 44009,
"s": 43992,
"text": "Java-Collections"
},
{
"code": null,
"e": 44020,
"s": 44009,
"text": "java-guava"
},
{
"code": null,
"e": 44029,
"s": 44020,
"text": "java-map"
},
{
"code": null,
"e": 44047,
"s": 44029,
"text": "Java-Map-Programs"
},
{
"code": null,
"e": 44052,
"s": 44047,
"text": "Java"
},
{
"code": null,
"e": 44057,
"s": 44052,
"text": "Java"
},
{
"code": null,
"e": 44074,
"s": 44057,
"text": "Java-Collections"
},
{
"code": null,
"e": 44172,
"s": 44074,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 44181,
"s": 44172,
"text": "Comments"
},
{
"code": null,
"e": 44194,
"s": 44181,
"text": "Old Comments"
},
{
"code": null,
"e": 44226,
"s": 44194,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 44245,
"s": 44226,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 44263,
"s": 44245,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 44295,
"s": 44263,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 44319,
"s": 44295,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 44342,
"s": 44319,
"text": "Multithreading in Java"
},
{
"code": null,
"e": 44362,
"s": 44342,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 44381,
"s": 44362,
"text": "LinkedList in Java"
},
{
"code": null,
"e": 44401,
"s": 44381,
"text": "Collections in Java"
}
] |
JSTL - XML <x:forEach> Tag | The <x:forEach> tag is used to loop over nodes in an XML document.
The <x:forEach> tag has the following attributes −
The following example shows the use of the <x:forEach> tag −
<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix = "x" uri = "http://java.sun.com/jsp/jstl/xml" %>
<html>
<head>
<title>JSTL x:if Tags</title>
</head>
<body>
<h3>Books Info:</h3>
<c:set var = "xmltext">
<books>
<book>
<name>Padam History</name>
<author>ZARA</author>
<price>100</price>
</book>
<book>
<name>Great Mistry</name>
<author>NUHA</author>
<price>2000</price>
</book>
</books>
</c:set>
<x:parse xml = "${xmltext}" var = "output"/>
<ul class = "list">
<x:forEach select = "$output/books/book/name" var = "item">
<li>Book Name: <x:out select = "$item" /></li>
</x:forEach>
</ul>
</body>
</html>
You will receive the following result −
Books Info:
Book Name: Padam History
Book Name: Great Mistry
Book Name: Padam History
Book Name: Padam History
Book Name: Great Mistry
Book Name: Great Mistry
108 Lectures
11 hours
Chaand Sheikh
517 Lectures
57 hours
Chaand Sheikh
41 Lectures
4.5 hours
Karthikeya T
42 Lectures
5.5 hours
TELCOMA Global
15 Lectures
3 hours
TELCOMA Global
44 Lectures
15 hours
Uplatz
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2306,
"s": 2239,
"text": "The <x:forEach> tag is used to loop over nodes in an XML document."
},
{
"code": null,
"e": 2357,
"s": 2306,
"text": "The <x:forEach> tag has the following attributes −"
},
{
"code": null,
"e": 2418,
"s": 2357,
"text": "The following example shows the use of the <x:forEach> tag −"
},
{
"code": null,
"e": 3323,
"s": 2418,
"text": "<%@ taglib prefix = \"c\" uri = \"http://java.sun.com/jsp/jstl/core\" %>\n<%@ taglib prefix = \"x\" uri = \"http://java.sun.com/jsp/jstl/xml\" %>\n\n<html>\n <head>\n <title>JSTL x:if Tags</title>\n </head>\n\n <body>\n <h3>Books Info:</h3>\n\n <c:set var = \"xmltext\">\n <books>\n <book>\n <name>Padam History</name>\n <author>ZARA</author>\n <price>100</price>\n </book>\n \n <book>\n <name>Great Mistry</name>\n <author>NUHA</author>\n <price>2000</price>\n </book>\n </books>\n </c:set>\n\n <x:parse xml = \"${xmltext}\" var = \"output\"/>\n \n <ul class = \"list\">\n <x:forEach select = \"$output/books/book/name\" var = \"item\">\n <li>Book Name: <x:out select = \"$item\" /></li>\n </x:forEach>\n </ul>\n\n </body>\n</html>"
},
{
"code": null,
"e": 3363,
"s": 3323,
"text": "You will receive the following result −"
},
{
"code": null,
"e": 3427,
"s": 3363,
"text": "Books Info:\n\nBook Name: Padam History\nBook Name: Great Mistry\n\n"
},
{
"code": null,
"e": 3452,
"s": 3427,
"text": "Book Name: Padam History"
},
{
"code": null,
"e": 3477,
"s": 3452,
"text": "Book Name: Padam History"
},
{
"code": null,
"e": 3501,
"s": 3477,
"text": "Book Name: Great Mistry"
},
{
"code": null,
"e": 3525,
"s": 3501,
"text": "Book Name: Great Mistry"
},
{
"code": null,
"e": 3560,
"s": 3525,
"text": "\n 108 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3575,
"s": 3560,
"text": " Chaand Sheikh"
},
{
"code": null,
"e": 3610,
"s": 3575,
"text": "\n 517 Lectures \n 57 hours \n"
},
{
"code": null,
"e": 3625,
"s": 3610,
"text": " Chaand Sheikh"
},
{
"code": null,
"e": 3660,
"s": 3625,
"text": "\n 41 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3674,
"s": 3660,
"text": " Karthikeya T"
},
{
"code": null,
"e": 3709,
"s": 3674,
"text": "\n 42 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3725,
"s": 3709,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 3758,
"s": 3725,
"text": "\n 15 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 3774,
"s": 3758,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 3808,
"s": 3774,
"text": "\n 44 Lectures \n 15 hours \n"
},
{
"code": null,
"e": 3816,
"s": 3808,
"text": " Uplatz"
},
{
"code": null,
"e": 3823,
"s": 3816,
"text": " Print"
},
{
"code": null,
"e": 3834,
"s": 3823,
"text": " Add Notes"
}
] |
Scraping websites with Newspaper3k in Python - GeeksforGeeks | 23 Jan, 2022
Web Scraping is a powerful tool to gather information from a website. To scrape multiple URLs, we can use a Python library called Newspaper3k. The Newspaper3k package is a Python library used for Web Scraping articles, It is built on top of requests and for parsing lxml. This module is a modified and better version of the Newspaper module which is also used for the same purpose.
To install this module type the below command in the terminal.
pip install newspaper3k
First we will define a list containing the URLs or assign a single URL.We will create an Article object passing in the parameters such as the name of the URL and optional parameters like language=’en’, for EnglishWe will then download and parse the file.Finally, display the data extracted.
First we will define a list containing the URLs or assign a single URL.
We will create an Article object passing in the parameters such as the name of the URL and optional parameters like language=’en’, for English
We will then download and parse the file.
Finally, display the data extracted.
Below are some examples based on the above approach:
Example 1
Below is a program to scrap data from a given URL.
Python3
# Import required moduleimport newspaper # Assign urlurl = 'https://www.geeksforgeeks.org/top-5-open-source-online-machine-learning-environments/' # Extract web dataurl_i = newspaper.Article(url="%s" % (url), language='en')url_i.download()url_i.parse() # Display scrapped dataprint(url_i.text)
Output:
Example 2
Here, we scrap data from multiple URLs and then display it.
Python3
# Import required modulesimport newspaper # Define list of urlslist_of_urls = ['https://www.geeksforgeeks.org/how-to-get-the-magnitude-of-a-vector-in-numpy/', 'https://www.geeksforgeeks.org/3d-wireframe-plotting-in-python-using-matplotlib/', 'https://www.geeksforgeeks.org/difference-between-small-data-and-big-data/'] # Parse through each url and display its contentfor url in list_of_urls: url_i = newspaper.Article(url="%s" % (url), language='en') url_i.download() url_i.parse() print(url_i.text)
Output:
abhishek0719kadiyan
sumitgumber28
Python web-scraping-exercises
python-modules
Web-scraping
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Pandas dataframe.groupby()
Create a directory in Python
Defaultdict in Python
Python | Get unique values from a list | [
{
"code": null,
"e": 25671,
"s": 25643,
"text": "\n23 Jan, 2022"
},
{
"code": null,
"e": 26053,
"s": 25671,
"text": "Web Scraping is a powerful tool to gather information from a website. To scrape multiple URLs, we can use a Python library called Newspaper3k. The Newspaper3k package is a Python library used for Web Scraping articles, It is built on top of requests and for parsing lxml. This module is a modified and better version of the Newspaper module which is also used for the same purpose."
},
{
"code": null,
"e": 26116,
"s": 26053,
"text": "To install this module type the below command in the terminal."
},
{
"code": null,
"e": 26140,
"s": 26116,
"text": "pip install newspaper3k"
},
{
"code": null,
"e": 26435,
"s": 26140,
"text": "First we will define a list containing the URLs or assign a single URL.We will create an Article object passing in the parameters such as the name of the URL and optional parameters like language=’en’, for EnglishWe will then download and parse the file.Finally, display the data extracted."
},
{
"code": null,
"e": 26507,
"s": 26435,
"text": "First we will define a list containing the URLs or assign a single URL."
},
{
"code": null,
"e": 26654,
"s": 26507,
"text": "We will create an Article object passing in the parameters such as the name of the URL and optional parameters like language=’en’, for English"
},
{
"code": null,
"e": 26696,
"s": 26654,
"text": "We will then download and parse the file."
},
{
"code": null,
"e": 26733,
"s": 26696,
"text": "Finally, display the data extracted."
},
{
"code": null,
"e": 26786,
"s": 26733,
"text": "Below are some examples based on the above approach:"
},
{
"code": null,
"e": 26796,
"s": 26786,
"text": "Example 1"
},
{
"code": null,
"e": 26847,
"s": 26796,
"text": "Below is a program to scrap data from a given URL."
},
{
"code": null,
"e": 26855,
"s": 26847,
"text": "Python3"
},
{
"code": "# Import required moduleimport newspaper # Assign urlurl = 'https://www.geeksforgeeks.org/top-5-open-source-online-machine-learning-environments/' # Extract web dataurl_i = newspaper.Article(url=\"%s\" % (url), language='en')url_i.download()url_i.parse() # Display scrapped dataprint(url_i.text)",
"e": 27149,
"s": 26855,
"text": null
},
{
"code": null,
"e": 27157,
"s": 27149,
"text": "Output:"
},
{
"code": null,
"e": 27167,
"s": 27157,
"text": "Example 2"
},
{
"code": null,
"e": 27227,
"s": 27167,
"text": "Here, we scrap data from multiple URLs and then display it."
},
{
"code": null,
"e": 27235,
"s": 27227,
"text": "Python3"
},
{
"code": "# Import required modulesimport newspaper # Define list of urlslist_of_urls = ['https://www.geeksforgeeks.org/how-to-get-the-magnitude-of-a-vector-in-numpy/', 'https://www.geeksforgeeks.org/3d-wireframe-plotting-in-python-using-matplotlib/', 'https://www.geeksforgeeks.org/difference-between-small-data-and-big-data/'] # Parse through each url and display its contentfor url in list_of_urls: url_i = newspaper.Article(url=\"%s\" % (url), language='en') url_i.download() url_i.parse() print(url_i.text)",
"e": 27777,
"s": 27235,
"text": null
},
{
"code": null,
"e": 27785,
"s": 27777,
"text": "Output:"
},
{
"code": null,
"e": 27805,
"s": 27785,
"text": "abhishek0719kadiyan"
},
{
"code": null,
"e": 27819,
"s": 27805,
"text": "sumitgumber28"
},
{
"code": null,
"e": 27849,
"s": 27819,
"text": "Python web-scraping-exercises"
},
{
"code": null,
"e": 27864,
"s": 27849,
"text": "python-modules"
},
{
"code": null,
"e": 27877,
"s": 27864,
"text": "Web-scraping"
},
{
"code": null,
"e": 27884,
"s": 27877,
"text": "Python"
},
{
"code": null,
"e": 27982,
"s": 27884,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28014,
"s": 27982,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28056,
"s": 28014,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28098,
"s": 28056,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28154,
"s": 28098,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28181,
"s": 28154,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28212,
"s": 28181,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28248,
"s": 28212,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 28277,
"s": 28248,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 28299,
"s": 28277,
"text": "Defaultdict in Python"
}
] |
Inheritance of Interface in Java with Examples - GeeksforGeeks | 10 Jun, 2020
Inheritance is an important pillar of OOPs(Object Oriented Programming). It is the mechanism in java by which one class is allowed to inherit the features(fields and methods) of another class. Like a class, an interface can have methods and variables, but the methods declared in an interface are by default abstract (only method signature, no body).
In this article, we will understand how the concept of inheritance is used in the interface.
An interface is a set of specifications or statements that define what a class can do without specifying how the class will do it. The interface is always abstract. A concrete class must implement all the abstract methods specified in the interface. Java does not support the concept of multiple inheritances to avoid the diamond problem encountered in C++ without using a virtual base class. However, Java supports multiple interface inheritance where an interface extends more than one super interfaces. The following is the syntax used to extend multiple interfaces in Java:
access_specifier interface subinterfaceName extends superinterface1, superinterface2, ...... {
// Body}
The following is an example which implements the multiple inheritances in interfaces:
Java
// Java program to demonstrate// the multiple inheritance// in interface // Interface to implement the// addition and subtraction methodsinterface Add_Sub { public void add(double x, double y); public void subtract(double x, double y);} // Interface to implement the// multiplication and divisioninterface Mul_Div { public void multiply(double x, double y); public void divide(double x, double y);} // Calculator interface which extends// both the above defined interfacesinterface Calculator extends Add_Sub, Mul_Div { public void printResult(double result);} // Calculator class which// implements the above// interfacepublic class MyCalculator implements Calculator { // Implementing the addition // method public void add(double x, double y) { double result = x + y; printResult(result); } // Implementing the subtraction // method public void subtract(double x, double y) { double result = x - y; printResult(result); } // Implementing the multiplication // method public void multiply(double x, double y) { double result = x * y; printResult(result); } // Implementing the division // method public void divide(double x, double y) { double result = x / y; printResult(result); } // Implementing a method // to print the result public void printResult(double result) { System.out.println( "The result is : " + result); } // Driver code public static void main(String args[]) { // Creating the object of // the calculator MyCalculator c = new MyCalculator(); c.add(5, 10); c.subtract(35, 15); c.multiply(6, 9); c.divide(45, 6); }}
The result is : 15.0
The result is : 20.0
The result is : 54.0
The result is : 7.5
Superinterface-Subinterface relationship: A subinterface type reference variable can be assigned to super interface type reference variable. Let us consider an example where we have an interface named animal which is extended by an interface mammal. We have a class named horse which implements the animal interface and the class named human which implements mammal. When we assign the mammal to an animal, it compiles without any error because a mammal is also an animal. That is:
// Animal Interfacepublic interface Animal { // body} // Mammal interface which extends// the Animal interfacepublic interface Mammal extends Animal { // body} // Horse which implements the// Animalclass Horse implements Animal { // body} // Human which implements the// mammalclass Human implements Mammal { // body} public class GFG { public static void main(String args[]) { Animal a = new Horse(); Mammal m = new Human(); // This compiles without any error // because mammal is also an animal, // subtype reference variable m // is assigned to the super type // reference variable a a = m; }}
How does multiple inheritance affect the variables:
There are two possible cases while inheriting the variables defined in one interface into others. They are:
Case 1: A subinterface inherits all the constant variables of the super interface. If a subinterface declares a constant variable with the same name as the inherited constants, then the new constant variable hides the inherited one irrespective of the type. For example:JavaJava// Java program to demonstrate the// inheritance of the variables // Defining an interface X// with some variablesinterface X { int VALUE = 100; int h = 10;} // Defining the interface Y// with the same variables// as the interface Xinterface Y extends X { int VALUE = 200; String h = "Hello World"; int sub = VALUE - X.VALUE;} // A class which implements the// above interfacepublic class GFG implements Y { // Printing the values of the // variables public static void main(String args[]) { System.out.println("X.VALUE = " + X.VALUE); System.out.println("Y.VALUE = " + Y.VALUE); System.out.println("sub = " + sub); System.out.println("X.h = " + X.h); System.out.println("h = " + h); }}Output:X.VALUE = 100
Y.VALUE = 200
sub = 100
X.h = 10
h = Hello World
Java
// Java program to demonstrate the// inheritance of the variables // Defining an interface X// with some variablesinterface X { int VALUE = 100; int h = 10;} // Defining the interface Y// with the same variables// as the interface Xinterface Y extends X { int VALUE = 200; String h = "Hello World"; int sub = VALUE - X.VALUE;} // A class which implements the// above interfacepublic class GFG implements Y { // Printing the values of the // variables public static void main(String args[]) { System.out.println("X.VALUE = " + X.VALUE); System.out.println("Y.VALUE = " + Y.VALUE); System.out.println("sub = " + sub); System.out.println("X.h = " + X.h); System.out.println("h = " + h); }}
X.VALUE = 100
Y.VALUE = 200
sub = 100
X.h = 10
h = Hello World
Case 2: When a subinterface extends the interfaces having the constant variables with the same name, Java gives a compilation error because the compiler cannot decide which constant variable to inherit. For example:JavaJava// Java program to demonstrate the// case when the constant variable// with the same name is defined // Implementing an interface// X with a variable Ainterface X { int A = 10;} // Implementing an interface// Y with the same variableinterface Y { String A = "hi";} // Implementing an interface which// extends both the above interfacesinterface Z extends X, Y { // body} // Creating a class which implements// the above interfacepublic class GFG implements Z { public static void main(String args[]) { // Shows compile time error if // the backslash is removed // System.out.println(Z.A); System.out.println(X.A); System.out.println(Y.A); }}Output:10
hi
Java
// Java program to demonstrate the// case when the constant variable// with the same name is defined // Implementing an interface// X with a variable Ainterface X { int A = 10;} // Implementing an interface// Y with the same variableinterface Y { String A = "hi";} // Implementing an interface which// extends both the above interfacesinterface Z extends X, Y { // body} // Creating a class which implements// the above interfacepublic class GFG implements Z { public static void main(String args[]) { // Shows compile time error if // the backslash is removed // System.out.println(Z.A); System.out.println(X.A); System.out.println(Y.A); }}
10
hi
How do multiple inheritances affect the methods and ways to handle the conflicts:
All the abstract and default methods of a super interface are inherited by the subinterface. When a subinterface extends more than one interface, then either a default-default conflict or an abstract-default conflict arises. These conflicts are handled by either of the following rules:
Override the conflicting method with an abstract method.Override the conflicting method with a default method and provide a new implementation.Override the conflicting method with a default method and call the default method of the immediate super interface.
Override the conflicting method with an abstract method.
Override the conflicting method with a default method and provide a new implementation.
Override the conflicting method with a default method and call the default method of the immediate super interface.
Default-default Conflict: The default-default conflict arises when two interfaces implement the same default methods with different operations and the compiler doesn’t know which task needs to be performed when both these interfaces are extended by a third interface. For example:
// Interface oneinterface one { // A default methoddefault void print() { System.out.println("one"); }} // Interface twointerface two { // Another default method// with the same namedefault void print() { System.out.println("two"); }}
We can apply the above-discussed rules to solve the above conflict. The following are the ways to handle the conflict:
Rule 1: Override the conflicting method with an abstract method. For example:interface four extends one, two { // Implementing another method void print();}Rule 2: Override the conflicting method with a default method and provide a new implementation. For example:interface four extends one, two { // Declare another method and// provide an implementationdefault void print() { System.out.println("four"); }}Rule 3: Override the conflicting method with a default method and call the default method of the immediate super interface. For example:interface four extends one, two { // Override the method with a// default method and give the// signature of what to performdefault void print() { two.super.print(); System.out.println("-four"); }}
Rule 1: Override the conflicting method with an abstract method. For example:interface four extends one, two { // Implementing another method void print();}
interface four extends one, two { // Implementing another method void print();}
Rule 2: Override the conflicting method with a default method and provide a new implementation. For example:interface four extends one, two { // Declare another method and// provide an implementationdefault void print() { System.out.println("four"); }}
interface four extends one, two { // Declare another method and// provide an implementationdefault void print() { System.out.println("four"); }}
Rule 3: Override the conflicting method with a default method and call the default method of the immediate super interface. For example:interface four extends one, two { // Override the method with a// default method and give the// signature of what to performdefault void print() { two.super.print(); System.out.println("-four"); }}
interface four extends one, two { // Override the method with a// default method and give the// signature of what to performdefault void print() { two.super.print(); System.out.println("-four"); }}
Abstract-default Conflict: The abstract-default conflict arises when one interface implements the default method and another interface defines an abstract method with the same name. While implementing both the interfaces, then we need to provide an implementation of the method but default methods don’t need an implementation. Even in this case, the compiler doesn’t know which method to execute. For example:
// Implementing the interface// one with a default methodinterface one {default void print() { System.out.println("one"); }} // Implementing another interface// with an abstract method of the// same nameinterface three { void print();}
We can apply the above-discussed rules to solve the above conflict. The following are the ways to handle the conflict:
Rule 1: Override the conflicting method with an abstract method. For example:interface five extends one, three { void print();}}Rule 2: Override the conflicting method with a default method and provide a new implementation. For example:interface five extends one, three {default void print() { System.out.println("five"); }}Rule 3: Override the conflicting method with a default method and call the default method of the immediate super interface. For example:interface five extends one, three {default void print() { one.super.print(); System.out.println("-four"); }}
Rule 1: Override the conflicting method with an abstract method. For example:interface five extends one, three { void print();}}
interface five extends one, three { void print();}}
Rule 2: Override the conflicting method with a default method and provide a new implementation. For example:interface five extends one, three {default void print() { System.out.println("five"); }}
interface five extends one, three {default void print() { System.out.println("five"); }}
Rule 3: Override the conflicting method with a default method and call the default method of the immediate super interface. For example:interface five extends one, three {default void print() { one.super.print(); System.out.println("-four"); }}
interface five extends one, three {default void print() { one.super.print(); System.out.println("-four"); }}
Overriding inherited static methods in interface inheritance:
In the interface inheritance, the static methods are not changed throughout the execution and they are not inherited. Hence, they cannot be overridden. However, if a class implements multiple interfaces without having a parent-child relationship by providing the methods with the same signature and the class does not override those methods, then a conflict occurs. For example:
// Interface A with an// abstract methodinterface A { void m();} // Interface B which doesn't// implement the above interface// and have the same abstract methodinterface B { void m() { System.out.println("In B"); }} // An Abstract class with the// normal method Mclass abstract C { public void m() { System.out.println("In C"); }}public class test extends C implements A, B { public static void main(String args[]) { // Creating an object of test test t = new test(); // Here, a conflict occurs as to // which method needs to be called t.m(); }}
To overcome this problem there are three rules:
Rule 1: Superclass has higher precedence than interfaces. This means that the superclass method is called.Rule 2: Derived interfaces have higher precedence than the super interfaces in the inheritance hierarchy. If I1 has a method m1() and I2 extends I1 and overrides m1() then I2 is the most specific version and has higher precedence.Rule 3: The class must override the method as needed. For example:public class test extends C implements A, B { // Overriding the conflicting // method public void m() { System.out.println("test"); } public static void main(String args[]) { test t = new test(); t.m(); }}
Rule 1: Superclass has higher precedence than interfaces. This means that the superclass method is called.
Rule 2: Derived interfaces have higher precedence than the super interfaces in the inheritance hierarchy. If I1 has a method m1() and I2 extends I1 and overrides m1() then I2 is the most specific version and has higher precedence.
Rule 3: The class must override the method as needed. For example:public class test extends C implements A, B { // Overriding the conflicting // method public void m() { System.out.println("test"); } public static void main(String args[]) { test t = new test(); t.m(); }}
public class test extends C implements A, B { // Overriding the conflicting // method public void m() { System.out.println("test"); } public static void main(String args[]) { test t = new test(); t.m(); }}
To conclude, though interfaces support multiple inheritances, there are few limitations and conflicts which needs to be handled.
Abstract Class and Interface
java-inheritance
java-interfaces
Java Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate Over the Characters of a String in Java
How to Get Elements By Index from HashSet in Java?
Java Program to Write into a File
Java Program to Read a File to String
How to Write Data into Excel Sheet using Java?
Java Servlet and JDBC Example | Insert data in MySQL
Removing last element from ArrayList in Java
How to Replace a Element in Java ArrayList?
Java Program to Find Sum of Array Elements
Tic-Tac-Toe Game in Java | [
{
"code": null,
"e": 26217,
"s": 26189,
"text": "\n10 Jun, 2020"
},
{
"code": null,
"e": 26568,
"s": 26217,
"text": "Inheritance is an important pillar of OOPs(Object Oriented Programming). It is the mechanism in java by which one class is allowed to inherit the features(fields and methods) of another class. Like a class, an interface can have methods and variables, but the methods declared in an interface are by default abstract (only method signature, no body)."
},
{
"code": null,
"e": 26661,
"s": 26568,
"text": "In this article, we will understand how the concept of inheritance is used in the interface."
},
{
"code": null,
"e": 27239,
"s": 26661,
"text": "An interface is a set of specifications or statements that define what a class can do without specifying how the class will do it. The interface is always abstract. A concrete class must implement all the abstract methods specified in the interface. Java does not support the concept of multiple inheritances to avoid the diamond problem encountered in C++ without using a virtual base class. However, Java supports multiple interface inheritance where an interface extends more than one super interfaces. The following is the syntax used to extend multiple interfaces in Java:"
},
{
"code": null,
"e": 27334,
"s": 27239,
"text": "access_specifier interface subinterfaceName extends superinterface1, superinterface2, ...... {"
},
{
"code": null,
"e": 27343,
"s": 27334,
"text": "// Body}"
},
{
"code": null,
"e": 27429,
"s": 27343,
"text": "The following is an example which implements the multiple inheritances in interfaces:"
},
{
"code": null,
"e": 27434,
"s": 27429,
"text": "Java"
},
{
"code": "// Java program to demonstrate// the multiple inheritance// in interface // Interface to implement the// addition and subtraction methodsinterface Add_Sub { public void add(double x, double y); public void subtract(double x, double y);} // Interface to implement the// multiplication and divisioninterface Mul_Div { public void multiply(double x, double y); public void divide(double x, double y);} // Calculator interface which extends// both the above defined interfacesinterface Calculator extends Add_Sub, Mul_Div { public void printResult(double result);} // Calculator class which// implements the above// interfacepublic class MyCalculator implements Calculator { // Implementing the addition // method public void add(double x, double y) { double result = x + y; printResult(result); } // Implementing the subtraction // method public void subtract(double x, double y) { double result = x - y; printResult(result); } // Implementing the multiplication // method public void multiply(double x, double y) { double result = x * y; printResult(result); } // Implementing the division // method public void divide(double x, double y) { double result = x / y; printResult(result); } // Implementing a method // to print the result public void printResult(double result) { System.out.println( \"The result is : \" + result); } // Driver code public static void main(String args[]) { // Creating the object of // the calculator MyCalculator c = new MyCalculator(); c.add(5, 10); c.subtract(35, 15); c.multiply(6, 9); c.divide(45, 6); }}",
"e": 29212,
"s": 27434,
"text": null
},
{
"code": null,
"e": 29296,
"s": 29212,
"text": "The result is : 15.0\nThe result is : 20.0\nThe result is : 54.0\nThe result is : 7.5\n"
},
{
"code": null,
"e": 29778,
"s": 29296,
"text": "Superinterface-Subinterface relationship: A subinterface type reference variable can be assigned to super interface type reference variable. Let us consider an example where we have an interface named animal which is extended by an interface mammal. We have a class named horse which implements the animal interface and the class named human which implements mammal. When we assign the mammal to an animal, it compiles without any error because a mammal is also an animal. That is:"
},
{
"code": "// Animal Interfacepublic interface Animal { // body} // Mammal interface which extends// the Animal interfacepublic interface Mammal extends Animal { // body} // Horse which implements the// Animalclass Horse implements Animal { // body} // Human which implements the// mammalclass Human implements Mammal { // body} public class GFG { public static void main(String args[]) { Animal a = new Horse(); Mammal m = new Human(); // This compiles without any error // because mammal is also an animal, // subtype reference variable m // is assigned to the super type // reference variable a a = m; }}",
"e": 30459,
"s": 29778,
"text": null
},
{
"code": null,
"e": 30511,
"s": 30459,
"text": "How does multiple inheritance affect the variables:"
},
{
"code": null,
"e": 30619,
"s": 30511,
"text": "There are two possible cases while inheriting the variables defined in one interface into others. They are:"
},
{
"code": null,
"e": 31724,
"s": 30619,
"text": "Case 1: A subinterface inherits all the constant variables of the super interface. If a subinterface declares a constant variable with the same name as the inherited constants, then the new constant variable hides the inherited one irrespective of the type. For example:JavaJava// Java program to demonstrate the// inheritance of the variables // Defining an interface X// with some variablesinterface X { int VALUE = 100; int h = 10;} // Defining the interface Y// with the same variables// as the interface Xinterface Y extends X { int VALUE = 200; String h = \"Hello World\"; int sub = VALUE - X.VALUE;} // A class which implements the// above interfacepublic class GFG implements Y { // Printing the values of the // variables public static void main(String args[]) { System.out.println(\"X.VALUE = \" + X.VALUE); System.out.println(\"Y.VALUE = \" + Y.VALUE); System.out.println(\"sub = \" + sub); System.out.println(\"X.h = \" + X.h); System.out.println(\"h = \" + h); }}Output:X.VALUE = 100\nY.VALUE = 200\nsub = 100\nX.h = 10\nh = Hello World\n"
},
{
"code": null,
"e": 31729,
"s": 31724,
"text": "Java"
},
{
"code": "// Java program to demonstrate the// inheritance of the variables // Defining an interface X// with some variablesinterface X { int VALUE = 100; int h = 10;} // Defining the interface Y// with the same variables// as the interface Xinterface Y extends X { int VALUE = 200; String h = \"Hello World\"; int sub = VALUE - X.VALUE;} // A class which implements the// above interfacepublic class GFG implements Y { // Printing the values of the // variables public static void main(String args[]) { System.out.println(\"X.VALUE = \" + X.VALUE); System.out.println(\"Y.VALUE = \" + Y.VALUE); System.out.println(\"sub = \" + sub); System.out.println(\"X.h = \" + X.h); System.out.println(\"h = \" + h); }}",
"e": 32486,
"s": 31729,
"text": null
},
{
"code": null,
"e": 32550,
"s": 32486,
"text": "X.VALUE = 100\nY.VALUE = 200\nsub = 100\nX.h = 10\nh = Hello World\n"
},
{
"code": null,
"e": 33487,
"s": 32550,
"text": "Case 2: When a subinterface extends the interfaces having the constant variables with the same name, Java gives a compilation error because the compiler cannot decide which constant variable to inherit. For example:JavaJava// Java program to demonstrate the// case when the constant variable// with the same name is defined // Implementing an interface// X with a variable Ainterface X { int A = 10;} // Implementing an interface// Y with the same variableinterface Y { String A = \"hi\";} // Implementing an interface which// extends both the above interfacesinterface Z extends X, Y { // body} // Creating a class which implements// the above interfacepublic class GFG implements Z { public static void main(String args[]) { // Shows compile time error if // the backslash is removed // System.out.println(Z.A); System.out.println(X.A); System.out.println(Y.A); }}Output:10\nhi\n"
},
{
"code": null,
"e": 33492,
"s": 33487,
"text": "Java"
},
{
"code": "// Java program to demonstrate the// case when the constant variable// with the same name is defined // Implementing an interface// X with a variable Ainterface X { int A = 10;} // Implementing an interface// Y with the same variableinterface Y { String A = \"hi\";} // Implementing an interface which// extends both the above interfacesinterface Z extends X, Y { // body} // Creating a class which implements// the above interfacepublic class GFG implements Z { public static void main(String args[]) { // Shows compile time error if // the backslash is removed // System.out.println(Z.A); System.out.println(X.A); System.out.println(Y.A); }}",
"e": 34193,
"s": 33492,
"text": null
},
{
"code": null,
"e": 34200,
"s": 34193,
"text": "10\nhi\n"
},
{
"code": null,
"e": 34282,
"s": 34200,
"text": "How do multiple inheritances affect the methods and ways to handle the conflicts:"
},
{
"code": null,
"e": 34569,
"s": 34282,
"text": "All the abstract and default methods of a super interface are inherited by the subinterface. When a subinterface extends more than one interface, then either a default-default conflict or an abstract-default conflict arises. These conflicts are handled by either of the following rules:"
},
{
"code": null,
"e": 34828,
"s": 34569,
"text": "Override the conflicting method with an abstract method.Override the conflicting method with a default method and provide a new implementation.Override the conflicting method with a default method and call the default method of the immediate super interface."
},
{
"code": null,
"e": 34885,
"s": 34828,
"text": "Override the conflicting method with an abstract method."
},
{
"code": null,
"e": 34973,
"s": 34885,
"text": "Override the conflicting method with a default method and provide a new implementation."
},
{
"code": null,
"e": 35089,
"s": 34973,
"text": "Override the conflicting method with a default method and call the default method of the immediate super interface."
},
{
"code": null,
"e": 35370,
"s": 35089,
"text": "Default-default Conflict: The default-default conflict arises when two interfaces implement the same default methods with different operations and the compiler doesn’t know which task needs to be performed when both these interfaces are extended by a third interface. For example:"
},
{
"code": "// Interface oneinterface one { // A default methoddefault void print() { System.out.println(\"one\"); }} // Interface twointerface two { // Another default method// with the same namedefault void print() { System.out.println(\"two\"); }}",
"e": 35640,
"s": 35370,
"text": null
},
{
"code": null,
"e": 35759,
"s": 35640,
"text": "We can apply the above-discussed rules to solve the above conflict. The following are the ways to handle the conflict:"
},
{
"code": null,
"e": 36550,
"s": 35759,
"text": "Rule 1: Override the conflicting method with an abstract method. For example:interface four extends one, two { // Implementing another method void print();}Rule 2: Override the conflicting method with a default method and provide a new implementation. For example:interface four extends one, two { // Declare another method and// provide an implementationdefault void print() { System.out.println(\"four\"); }}Rule 3: Override the conflicting method with a default method and call the default method of the immediate super interface. For example:interface four extends one, two { // Override the method with a// default method and give the// signature of what to performdefault void print() { two.super.print(); System.out.println(\"-four\"); }}"
},
{
"code": null,
"e": 36715,
"s": 36550,
"text": "Rule 1: Override the conflicting method with an abstract method. For example:interface four extends one, two { // Implementing another method void print();}"
},
{
"code": "interface four extends one, two { // Implementing another method void print();}",
"e": 36803,
"s": 36715,
"text": null
},
{
"code": null,
"e": 37073,
"s": 36803,
"text": "Rule 2: Override the conflicting method with a default method and provide a new implementation. For example:interface four extends one, two { // Declare another method and// provide an implementationdefault void print() { System.out.println(\"four\"); }}"
},
{
"code": "interface four extends one, two { // Declare another method and// provide an implementationdefault void print() { System.out.println(\"four\"); }}",
"e": 37235,
"s": 37073,
"text": null
},
{
"code": null,
"e": 37593,
"s": 37235,
"text": "Rule 3: Override the conflicting method with a default method and call the default method of the immediate super interface. For example:interface four extends one, two { // Override the method with a// default method and give the// signature of what to performdefault void print() { two.super.print(); System.out.println(\"-four\"); }}"
},
{
"code": "interface four extends one, two { // Override the method with a// default method and give the// signature of what to performdefault void print() { two.super.print(); System.out.println(\"-four\"); }}",
"e": 37815,
"s": 37593,
"text": null
},
{
"code": null,
"e": 38226,
"s": 37815,
"text": "Abstract-default Conflict: The abstract-default conflict arises when one interface implements the default method and another interface defines an abstract method with the same name. While implementing both the interfaces, then we need to provide an implementation of the method but default methods don’t need an implementation. Even in this case, the compiler doesn’t know which method to execute. For example:"
},
{
"code": "// Implementing the interface// one with a default methodinterface one {default void print() { System.out.println(\"one\"); }} // Implementing another interface// with an abstract method of the// same nameinterface three { void print();}",
"e": 38482,
"s": 38226,
"text": null
},
{
"code": null,
"e": 38601,
"s": 38482,
"text": "We can apply the above-discussed rules to solve the above conflict. The following are the ways to handle the conflict:"
},
{
"code": null,
"e": 39212,
"s": 38601,
"text": "Rule 1: Override the conflicting method with an abstract method. For example:interface five extends one, three { void print();}}Rule 2: Override the conflicting method with a default method and provide a new implementation. For example:interface five extends one, three {default void print() { System.out.println(\"five\"); }}Rule 3: Override the conflicting method with a default method and call the default method of the immediate super interface. For example:interface five extends one, three {default void print() { one.super.print(); System.out.println(\"-four\"); }}"
},
{
"code": null,
"e": 39344,
"s": 39212,
"text": "Rule 1: Override the conflicting method with an abstract method. For example:interface five extends one, three { void print();}}"
},
{
"code": "interface five extends one, three { void print();}}",
"e": 39399,
"s": 39344,
"text": null
},
{
"code": null,
"e": 39612,
"s": 39399,
"text": "Rule 2: Override the conflicting method with a default method and provide a new implementation. For example:interface five extends one, three {default void print() { System.out.println(\"five\"); }}"
},
{
"code": "interface five extends one, three {default void print() { System.out.println(\"five\"); }}",
"e": 39717,
"s": 39612,
"text": null
},
{
"code": null,
"e": 39985,
"s": 39717,
"text": "Rule 3: Override the conflicting method with a default method and call the default method of the immediate super interface. For example:interface five extends one, three {default void print() { one.super.print(); System.out.println(\"-four\"); }}"
},
{
"code": "interface five extends one, three {default void print() { one.super.print(); System.out.println(\"-four\"); }}",
"e": 40117,
"s": 39985,
"text": null
},
{
"code": null,
"e": 40179,
"s": 40117,
"text": "Overriding inherited static methods in interface inheritance:"
},
{
"code": null,
"e": 40558,
"s": 40179,
"text": "In the interface inheritance, the static methods are not changed throughout the execution and they are not inherited. Hence, they cannot be overridden. However, if a class implements multiple interfaces without having a parent-child relationship by providing the methods with the same signature and the class does not override those methods, then a conflict occurs. For example:"
},
{
"code": "// Interface A with an// abstract methodinterface A { void m();} // Interface B which doesn't// implement the above interface// and have the same abstract methodinterface B { void m() { System.out.println(\"In B\"); }} // An Abstract class with the// normal method Mclass abstract C { public void m() { System.out.println(\"In C\"); }}public class test extends C implements A, B { public static void main(String args[]) { // Creating an object of test test t = new test(); // Here, a conflict occurs as to // which method needs to be called t.m(); }}",
"e": 41193,
"s": 40558,
"text": null
},
{
"code": null,
"e": 41241,
"s": 41193,
"text": "To overcome this problem there are three rules:"
},
{
"code": null,
"e": 41899,
"s": 41241,
"text": "Rule 1: Superclass has higher precedence than interfaces. This means that the superclass method is called.Rule 2: Derived interfaces have higher precedence than the super interfaces in the inheritance hierarchy. If I1 has a method m1() and I2 extends I1 and overrides m1() then I2 is the most specific version and has higher precedence.Rule 3: The class must override the method as needed. For example:public class test extends C implements A, B { // Overriding the conflicting // method public void m() { System.out.println(\"test\"); } public static void main(String args[]) { test t = new test(); t.m(); }}"
},
{
"code": null,
"e": 42006,
"s": 41899,
"text": "Rule 1: Superclass has higher precedence than interfaces. This means that the superclass method is called."
},
{
"code": null,
"e": 42237,
"s": 42006,
"text": "Rule 2: Derived interfaces have higher precedence than the super interfaces in the inheritance hierarchy. If I1 has a method m1() and I2 extends I1 and overrides m1() then I2 is the most specific version and has higher precedence."
},
{
"code": null,
"e": 42559,
"s": 42237,
"text": "Rule 3: The class must override the method as needed. For example:public class test extends C implements A, B { // Overriding the conflicting // method public void m() { System.out.println(\"test\"); } public static void main(String args[]) { test t = new test(); t.m(); }}"
},
{
"code": "public class test extends C implements A, B { // Overriding the conflicting // method public void m() { System.out.println(\"test\"); } public static void main(String args[]) { test t = new test(); t.m(); }}",
"e": 42815,
"s": 42559,
"text": null
},
{
"code": null,
"e": 42944,
"s": 42815,
"text": "To conclude, though interfaces support multiple inheritances, there are few limitations and conflicts which needs to be handled."
},
{
"code": null,
"e": 42973,
"s": 42944,
"text": "Abstract Class and Interface"
},
{
"code": null,
"e": 42990,
"s": 42973,
"text": "java-inheritance"
},
{
"code": null,
"e": 43006,
"s": 42990,
"text": "java-interfaces"
},
{
"code": null,
"e": 43020,
"s": 43006,
"text": "Java Programs"
},
{
"code": null,
"e": 43118,
"s": 43020,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 43166,
"s": 43118,
"text": "Iterate Over the Characters of a String in Java"
},
{
"code": null,
"e": 43217,
"s": 43166,
"text": "How to Get Elements By Index from HashSet in Java?"
},
{
"code": null,
"e": 43251,
"s": 43217,
"text": "Java Program to Write into a File"
},
{
"code": null,
"e": 43289,
"s": 43251,
"text": "Java Program to Read a File to String"
},
{
"code": null,
"e": 43336,
"s": 43289,
"text": "How to Write Data into Excel Sheet using Java?"
},
{
"code": null,
"e": 43389,
"s": 43336,
"text": "Java Servlet and JDBC Example | Insert data in MySQL"
},
{
"code": null,
"e": 43434,
"s": 43389,
"text": "Removing last element from ArrayList in Java"
},
{
"code": null,
"e": 43478,
"s": 43434,
"text": "How to Replace a Element in Java ArrayList?"
},
{
"code": null,
"e": 43521,
"s": 43478,
"text": "Java Program to Find Sum of Array Elements"
}
] |
How to Install and Use Htop on Linux? - GeeksforGeeks | 09 Apr, 2021
For Linux systems, Htop is an interactive system control, process viewer, and process manager. It was created as a replacement for the Linux program top, and it has a lot of the same features as the top, but with a lot more flexibility in terms of how system processes can be interpreted. Unlike top, htop displays the entire list of running processes rather than just the most resource-intensive ones. Htop can view processes as a tree and provides resource-usage statistics using color.
First, update your system sources:
$ sudo apt install htop
Updating system source
Now, install htop using the below command:
$ sudo apt-get install -y htop
Installing htop
We’ll need ncurses, as well as development tools/build necessary, to compile htop from the source. The steps for downloading htop from the source are as follows.
Install development tools using the below command:
$ sudo apt-get install build-essential
Installing development tools
Installing ncurses:
$ sudo apt-get install libncurses5-dev libncursesw5-dev
Installing ncurses
Now download htop from the source using wget:
$ wget http://hisham.hm/htop/releases/2.2.0/htop-2.2.0.tar.gz
Downloading htop
Extract tar:
$ tar xvfvz htop-2.2.0.tar.gz
Extract tar
Change directory to htop:
$ cd htop-2.2.0/
Change directory to htop
Now run the configure:
$ ./configure
Running the configure file
Now make a script:
$ make
Making script
Now we can install htop:
$ make install
Installing htop
Now you can open htop by simply typing:
$ htop
htop
Picked
How To
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install FFmpeg on Windows?
How to Set Git Username and Password in GitBash?
How to Install Selenium on MacOS?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Check the OS Version in Linux?
AWK command in Unix/Linux with examples
Sed Command in Linux/Unix with examples
grep command in Unix/Linux
cut command in Linux with examples
TCP Server-Client implementation in C | [
{
"code": null,
"e": 24872,
"s": 24844,
"text": "\n09 Apr, 2021"
},
{
"code": null,
"e": 25361,
"s": 24872,
"text": "For Linux systems, Htop is an interactive system control, process viewer, and process manager. It was created as a replacement for the Linux program top, and it has a lot of the same features as the top, but with a lot more flexibility in terms of how system processes can be interpreted. Unlike top, htop displays the entire list of running processes rather than just the most resource-intensive ones. Htop can view processes as a tree and provides resource-usage statistics using color."
},
{
"code": null,
"e": 25396,
"s": 25361,
"text": "First, update your system sources:"
},
{
"code": null,
"e": 25420,
"s": 25396,
"text": "$ sudo apt install htop"
},
{
"code": null,
"e": 25443,
"s": 25420,
"text": "Updating system source"
},
{
"code": null,
"e": 25486,
"s": 25443,
"text": "Now, install htop using the below command:"
},
{
"code": null,
"e": 25517,
"s": 25486,
"text": "$ sudo apt-get install -y htop"
},
{
"code": null,
"e": 25533,
"s": 25517,
"text": "Installing htop"
},
{
"code": null,
"e": 25695,
"s": 25533,
"text": "We’ll need ncurses, as well as development tools/build necessary, to compile htop from the source. The steps for downloading htop from the source are as follows."
},
{
"code": null,
"e": 25746,
"s": 25695,
"text": "Install development tools using the below command:"
},
{
"code": null,
"e": 25785,
"s": 25746,
"text": "$ sudo apt-get install build-essential"
},
{
"code": null,
"e": 25814,
"s": 25785,
"text": "Installing development tools"
},
{
"code": null,
"e": 25834,
"s": 25814,
"text": "Installing ncurses:"
},
{
"code": null,
"e": 25890,
"s": 25834,
"text": "$ sudo apt-get install libncurses5-dev libncursesw5-dev"
},
{
"code": null,
"e": 25909,
"s": 25890,
"text": "Installing ncurses"
},
{
"code": null,
"e": 25955,
"s": 25909,
"text": "Now download htop from the source using wget:"
},
{
"code": null,
"e": 26017,
"s": 25955,
"text": "$ wget http://hisham.hm/htop/releases/2.2.0/htop-2.2.0.tar.gz"
},
{
"code": null,
"e": 26034,
"s": 26017,
"text": "Downloading htop"
},
{
"code": null,
"e": 26047,
"s": 26034,
"text": "Extract tar:"
},
{
"code": null,
"e": 26077,
"s": 26047,
"text": "$ tar xvfvz htop-2.2.0.tar.gz"
},
{
"code": null,
"e": 26089,
"s": 26077,
"text": "Extract tar"
},
{
"code": null,
"e": 26115,
"s": 26089,
"text": "Change directory to htop:"
},
{
"code": null,
"e": 26132,
"s": 26115,
"text": "$ cd htop-2.2.0/"
},
{
"code": null,
"e": 26157,
"s": 26132,
"text": "Change directory to htop"
},
{
"code": null,
"e": 26180,
"s": 26157,
"text": "Now run the configure:"
},
{
"code": null,
"e": 26194,
"s": 26180,
"text": "$ ./configure"
},
{
"code": null,
"e": 26221,
"s": 26194,
"text": "Running the configure file"
},
{
"code": null,
"e": 26240,
"s": 26221,
"text": "Now make a script:"
},
{
"code": null,
"e": 26247,
"s": 26240,
"text": "$ make"
},
{
"code": null,
"e": 26261,
"s": 26247,
"text": "Making script"
},
{
"code": null,
"e": 26286,
"s": 26261,
"text": "Now we can install htop:"
},
{
"code": null,
"e": 26301,
"s": 26286,
"text": "$ make install"
},
{
"code": null,
"e": 26317,
"s": 26301,
"text": "Installing htop"
},
{
"code": null,
"e": 26357,
"s": 26317,
"text": "Now you can open htop by simply typing:"
},
{
"code": null,
"e": 26364,
"s": 26357,
"text": "$ htop"
},
{
"code": null,
"e": 26369,
"s": 26364,
"text": "htop"
},
{
"code": null,
"e": 26376,
"s": 26369,
"text": "Picked"
},
{
"code": null,
"e": 26383,
"s": 26376,
"text": "How To"
},
{
"code": null,
"e": 26394,
"s": 26383,
"text": "Linux-Unix"
},
{
"code": null,
"e": 26492,
"s": 26394,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26501,
"s": 26492,
"text": "Comments"
},
{
"code": null,
"e": 26514,
"s": 26501,
"text": "Old Comments"
},
{
"code": null,
"e": 26548,
"s": 26514,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 26597,
"s": 26548,
"text": "How to Set Git Username and Password in GitBash?"
},
{
"code": null,
"e": 26631,
"s": 26597,
"text": "How to Install Selenium on MacOS?"
},
{
"code": null,
"e": 26689,
"s": 26631,
"text": "How to Add External JAR File to an IntelliJ IDEA Project?"
},
{
"code": null,
"e": 26727,
"s": 26689,
"text": "How to Check the OS Version in Linux?"
},
{
"code": null,
"e": 26767,
"s": 26727,
"text": "AWK command in Unix/Linux with examples"
},
{
"code": null,
"e": 26807,
"s": 26767,
"text": "Sed Command in Linux/Unix with examples"
},
{
"code": null,
"e": 26834,
"s": 26807,
"text": "grep command in Unix/Linux"
},
{
"code": null,
"e": 26869,
"s": 26834,
"text": "cut command in Linux with examples"
}
] |
Concatenated string with uncommon characters in Python? | Here two strings are given, first we have to remove all the common element from the first string and uncommon characters of the second string have to be concatenated with uncommon element of first string.
Input >> first string::AABCD
Second string:: MNAABP
Output >> CDMNP
Uncommonstring(s1,s2)
/* s1 and s2 are two string */
Step 1: Convert both string into set st1 and st2.
Step 2: use the intersection of two sets and get common characters.
Step 3: now separate out characters in each string which are not common in both string.
Step 4: join each character without space to get a final string.
# Concatination of two uncommon strings
def uncommonstring(s1, s2):
# convert both strings into set
st1 = set(s1)
st2 = set(s2)
# take intersection of two sets to get list of common characters
lst = list(st1 & st2)
finallist = [i for i in s1 if i not in lst] + \ [i for i in s2 if i not in lst]
print("CONCATENATED STRING IS :::", ''.join(finallist))
# Driver program
if __name__ == "__main__":
s1 =input("Enter the String ::")
s2=input("Enter the String ::")
uncommonstring(s1,s2)
Enter the String ::abcde
Enter the String ::bdkl
CONCATEATED STRINGIS ::: acekl | [
{
"code": null,
"e": 1267,
"s": 1062,
"text": "Here two strings are given, first we have to remove all the common element from the first string and uncommon characters of the second string have to be concatenated with uncommon element of first string."
},
{
"code": null,
"e": 1336,
"s": 1267,
"text": "Input >> first string::AABCD\nSecond string:: MNAABP\nOutput >> CDMNP\n"
},
{
"code": null,
"e": 1661,
"s": 1336,
"text": "Uncommonstring(s1,s2)\n/* s1 and s2 are two string */\nStep 1: Convert both string into set st1 and st2.\nStep 2: use the intersection of two sets and get common characters.\nStep 3: now separate out characters in each string which are not common in both string.\nStep 4: join each character without space to get a final string.\n"
},
{
"code": null,
"e": 2172,
"s": 1661,
"text": "# Concatination of two uncommon strings \ndef uncommonstring(s1, s2):\n# convert both strings into set\n st1 = set(s1)\n st2 = set(s2)\n # take intersection of two sets to get list of common characters \n lst = list(st1 & st2)\n finallist = [i for i in s1 if i not in lst] + \\ [i for i in s2 if i not in lst]\n print(\"CONCATENATED STRING IS :::\", ''.join(finallist))\n# Driver program\nif __name__ == \"__main__\":\n s1 =input(\"Enter the String ::\")\n s2=input(\"Enter the String ::\")\n uncommonstring(s1,s2)"
},
{
"code": null,
"e": 2253,
"s": 2172,
"text": "Enter the String ::abcde\nEnter the String ::bdkl\nCONCATEATED STRINGIS ::: acekl\n"
}
] |
How to generate PDF file using PHP ? - GeeksforGeeks | 02 Jul, 2021
In this article, we will learn how to generate PDF files with PHP by using FPDF. It is a free PHP class that contains many functions for creating and modifying PDFs. The FPDF class includes many features like page formats, page headers, footers, automatic page break, line break, image support, colors, links, and many more.
Approach:
You need to download the FPDF class from the FPDF website and include it in your PHP script.
require('fpdf/fpdf.php');
Instantiate and use the FPDF class according to your need as shown in the following examples.
$pdf=new FPDF();
Example 1: The following example generates a PDF file with the given text in the code. The file can be downloaded or previewed as needed.
PHP
<?php ob_end_clean();require('fpdf/fpdf.php'); // Instantiate and use the FPDF class $pdf = new FPDF(); //Add a new page$pdf->AddPage(); // Set the font for the text$pdf->SetFont('Arial', 'B', 18); // Prints a cell with given text $pdf->Cell(60,20,'Hello GeeksforGeeks!'); // return the generated output$pdf->Output(); ?>
Output:
Example 2: The following example helps in understanding the setting of the page header and footer along with printing many lines on different pages of PDF files.
PHP
<?php require('fpdf/fpdf.php'); class PDF extends FPDF { // Page header function Header() { // Add logo to page $this->Image('gfg1.png',10,8,33); // Set font family to Arial bold $this->SetFont('Arial','B',20); // Move to the right $this->Cell(80); // Header $this->Cell(50,10,'Heading',1,0,'C'); // Line break $this->Ln(20); } // Page footer function Footer() { // Position at 1.5 cm from bottom $this->SetY(-15); // Arial italic 8 $this->SetFont('Arial','I',8); // Page number $this->Cell(0,10,'Page ' . $this->PageNo() . '/{nb}',0,0,'C'); }} // Instantiation of FPDF class$pdf = new PDF(); // Define alias for number of pages$pdf->AliasNbPages();$pdf->AddPage();$pdf->SetFont('Times','',14); for($i = 1; $i <= 30; $i++) $pdf->Cell(0, 10, 'line number ' . $i, 0, 1);$pdf->Output(); ?>
Output:
PHP-function
PHP-Questions
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to fetch data from localserver database and display on HTML table using PHP ?
How to create admin login page using PHP?
PHP Database connection
How to pass a PHP array to a JavaScript function?
String comparison using == vs strcmp() in PHP
Express.js express.Router() Function
How to set input type date in dd-mm-yyyy format using HTML ?
Installation of Node.js on Linux
Differences between Functional Components and Class Components in React
How to create footer to stay at the bottom of a Web page? | [
{
"code": null,
"e": 24581,
"s": 24553,
"text": "\n02 Jul, 2021"
},
{
"code": null,
"e": 24906,
"s": 24581,
"text": "In this article, we will learn how to generate PDF files with PHP by using FPDF. It is a free PHP class that contains many functions for creating and modifying PDFs. The FPDF class includes many features like page formats, page headers, footers, automatic page break, line break, image support, colors, links, and many more."
},
{
"code": null,
"e": 24916,
"s": 24906,
"text": "Approach:"
},
{
"code": null,
"e": 25009,
"s": 24916,
"text": "You need to download the FPDF class from the FPDF website and include it in your PHP script."
},
{
"code": null,
"e": 25035,
"s": 25009,
"text": "require('fpdf/fpdf.php');"
},
{
"code": null,
"e": 25129,
"s": 25035,
"text": "Instantiate and use the FPDF class according to your need as shown in the following examples."
},
{
"code": null,
"e": 25146,
"s": 25129,
"text": "$pdf=new FPDF();"
},
{
"code": null,
"e": 25284,
"s": 25146,
"text": "Example 1: The following example generates a PDF file with the given text in the code. The file can be downloaded or previewed as needed."
},
{
"code": null,
"e": 25288,
"s": 25284,
"text": "PHP"
},
{
"code": "<?php ob_end_clean();require('fpdf/fpdf.php'); // Instantiate and use the FPDF class $pdf = new FPDF(); //Add a new page$pdf->AddPage(); // Set the font for the text$pdf->SetFont('Arial', 'B', 18); // Prints a cell with given text $pdf->Cell(60,20,'Hello GeeksforGeeks!'); // return the generated output$pdf->Output(); ?>",
"e": 25619,
"s": 25288,
"text": null
},
{
"code": null,
"e": 25629,
"s": 25621,
"text": "Output:"
},
{
"code": null,
"e": 25791,
"s": 25629,
"text": "Example 2: The following example helps in understanding the setting of the page header and footer along with printing many lines on different pages of PDF files."
},
{
"code": null,
"e": 25795,
"s": 25791,
"text": "PHP"
},
{
"code": "<?php require('fpdf/fpdf.php'); class PDF extends FPDF { // Page header function Header() { // Add logo to page $this->Image('gfg1.png',10,8,33); // Set font family to Arial bold $this->SetFont('Arial','B',20); // Move to the right $this->Cell(80); // Header $this->Cell(50,10,'Heading',1,0,'C'); // Line break $this->Ln(20); } // Page footer function Footer() { // Position at 1.5 cm from bottom $this->SetY(-15); // Arial italic 8 $this->SetFont('Arial','I',8); // Page number $this->Cell(0,10,'Page ' . $this->PageNo() . '/{nb}',0,0,'C'); }} // Instantiation of FPDF class$pdf = new PDF(); // Define alias for number of pages$pdf->AliasNbPages();$pdf->AddPage();$pdf->SetFont('Times','',14); for($i = 1; $i <= 30; $i++) $pdf->Cell(0, 10, 'line number ' . $i, 0, 1);$pdf->Output(); ?>",
"e": 26830,
"s": 25795,
"text": null
},
{
"code": null,
"e": 26838,
"s": 26830,
"text": "Output:"
},
{
"code": null,
"e": 26851,
"s": 26838,
"text": "PHP-function"
},
{
"code": null,
"e": 26865,
"s": 26851,
"text": "PHP-Questions"
},
{
"code": null,
"e": 26869,
"s": 26865,
"text": "PHP"
},
{
"code": null,
"e": 26886,
"s": 26869,
"text": "Web Technologies"
},
{
"code": null,
"e": 26890,
"s": 26886,
"text": "PHP"
},
{
"code": null,
"e": 26988,
"s": 26890,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26997,
"s": 26988,
"text": "Comments"
},
{
"code": null,
"e": 27010,
"s": 26997,
"text": "Old Comments"
},
{
"code": null,
"e": 27092,
"s": 27010,
"text": "How to fetch data from localserver database and display on HTML table using PHP ?"
},
{
"code": null,
"e": 27134,
"s": 27092,
"text": "How to create admin login page using PHP?"
},
{
"code": null,
"e": 27158,
"s": 27134,
"text": "PHP Database connection"
},
{
"code": null,
"e": 27208,
"s": 27158,
"text": "How to pass a PHP array to a JavaScript function?"
},
{
"code": null,
"e": 27254,
"s": 27208,
"text": "String comparison using == vs strcmp() in PHP"
},
{
"code": null,
"e": 27291,
"s": 27254,
"text": "Express.js express.Router() Function"
},
{
"code": null,
"e": 27352,
"s": 27291,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 27385,
"s": 27352,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27457,
"s": 27385,
"text": "Differences between Functional Components and Class Components in React"
}
] |
jQuery keypress() with Examples | The keypress method in jQuery is used to trigger the keypress event. It occurs when a keyboard key is pressed down.
The syntax is as follows −
$(selector).keypress(func)
Let us now see an example to implement the jQuery keypress() method−
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
count = 0;
$(document).ready(function(){
$("input").keypress(function(){
$("span").text(count += 1);
});
$("input").keyup(function(){
$("input").css("color", "blue");
});
});
</script>
</style>
</head>
<body>
<h2>Registeration</h2>
<p>Enter username of the student:</p>
Username: <input type="text"><br><br>
Key is pressed <span> 0 </span>times.
</body>
</html>
This will produce the following output−
Now, when the key is pressed, the count of the number of keys appeared− | [
{
"code": null,
"e": 1178,
"s": 1062,
"text": "The keypress method in jQuery is used to trigger the keypress event. It occurs when a keyboard key is pressed down."
},
{
"code": null,
"e": 1205,
"s": 1178,
"text": "The syntax is as follows −"
},
{
"code": null,
"e": 1232,
"s": 1205,
"text": "$(selector).keypress(func)"
},
{
"code": null,
"e": 1301,
"s": 1232,
"text": "Let us now see an example to implement the jQuery keypress() method−"
},
{
"code": null,
"e": 1312,
"s": 1301,
"text": " Live Demo"
},
{
"code": null,
"e": 1861,
"s": 1312,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\n<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"></script>\n<script>\n count = 0;\n $(document).ready(function(){\n $(\"input\").keypress(function(){\n $(\"span\").text(count += 1);\n });\n $(\"input\").keyup(function(){\n $(\"input\").css(\"color\", \"blue\");\n });\n });\n</script>\n</style>\n</head>\n<body>\n<h2>Registeration</h2>\n<p>Enter username of the student:</p>\nUsername: <input type=\"text\"><br><br>\nKey is pressed <span> 0 </span>times.\n</body>\n</html>"
},
{
"code": null,
"e": 1901,
"s": 1861,
"text": "This will produce the following output−"
},
{
"code": null,
"e": 1973,
"s": 1901,
"text": "Now, when the key is pressed, the count of the number of keys appeared−"
}
] |
The Problem of Vanishing Gradients | by Animesh Agarwal | Towards Data Science | Vanishing gradients occur while training deep neural networks using gradient-based optimization methods. It occurs due to the nature of the backpropagation algorithm that is used to train the neural network.
Explain the problem of vanishing gradients: We will understand why the problem of vanishing gradients exists. We will also look at why this problem is more observed while using the sigmoid activation function and how RELU reduces the problem.A comparative study using TensorFlow: We will train an MLP classifier on the Fashion MNIST dataset using the sigmoid and RELU activation functions and compare the gradients.
Explain the problem of vanishing gradients: We will understand why the problem of vanishing gradients exists. We will also look at why this problem is more observed while using the sigmoid activation function and how RELU reduces the problem.
A comparative study using TensorFlow: We will train an MLP classifier on the Fashion MNIST dataset using the sigmoid and RELU activation functions and compare the gradients.
Before we can understand why the problem of vanishing gradients exists, we should have some understanding of the equations of the backpropagation algorithm. I will not derive the backpropagation equations as it is beyond the scope of this article. However, I have attached a screenshot from this famous book.
Observations:
From equation 1&2 we can see that the error in the output layer depends on the derivative of the activation function.From equation 2 we can observe that the error in the previous/hidden layer is proportional to the weights, the error from the outer layers and the derivative of the activation function. The error from outer layers is in turn dependent on the derivative of the activation function of its layer.From equation 1,2 &4 we can conclude that the gradients for weights for any layer are dependent on the product of derivatives of the activation layers.
From equation 1&2 we can see that the error in the output layer depends on the derivative of the activation function.
From equation 2 we can observe that the error in the previous/hidden layer is proportional to the weights, the error from the outer layers and the derivative of the activation function. The error from outer layers is in turn dependent on the derivative of the activation function of its layer.
From equation 1,2 &4 we can conclude that the gradients for weights for any layer are dependent on the product of derivatives of the activation layers.
Consider the graph of sigmoid function and it’s derivative. Observe that for very large values for sigmoid function the derivative takes a very low value. If the neural network has many hidden layers, the gradients in the earlier layers will become very low as we multiply the derivatives of each layer. As a result, learning in the earlier layers becomes very slow.
On the other hand, the derivative of the RELU function is either zero or 1. Even if we multiply the derivatives for many layers, there will be no degradation unlike the case of the sigmoid function (assuming that RELU is not operating in the dead-region). However, if you carefully look at equation 2, the error signal is also dependent on the weights of the network. If the weights of the network are constantly below zero, the gradients will diminish slowly.
Now that we have understood the problem of vanishing gradients, let’s train two different MLP Classifiers, one using the sigmoid and the other using the RELU activation functions.
Let’s get started.
Import Libraries
import tensorflow as tfimport numpy as npfrom tensorflow import kerasimport matplotlib.pyplot as plt from tqdm import tqdm
Download the dataset
We will be using the Fashion MNIST dataset. It consists of 70000 grayscale images of 10 different product categories. Each product category has 7000 samples. You can read more about the dataset here.
We will use Keras to download the Fashion MNIST dataset.
fashion_mnist = keras.datasets.fashion_mnist(x_train, y_train), (x_test, y_test) = fashion_mnist.load_data()print(x_train.shape)print(y_train.shape)print(x_test.shape)print(y_test.shape)(60000,28,28)(60000,)(10000,28,28)(10000,)
As we will be using an MLP Classifier, we need to flatten the 28*28 grayscale image into a 784 long vector.
x_train = x_train.reshape(60000,-1)x_test = x_test.reshape(10000,-1)
The pixel values of the images are between 0 and 1. We will define a function to standardize the dataset by removing the mean and scaling to unit variance.
def normalize(x_train, x_test): train_mean = np.mean(x_train) train_std = np.mean(x_train) x_train = (x_train - train_mean)/train_std x_test = (x_test - train_mean)/train_std return x_train, x_test
The product categories are labeled from 0 to 9. We will define a utility to convert the values into one hot encoding.
def convert_to_one_hot(labels): no_samples = labels.shape[0] n_classes = np.max(labels) + 1 one_hot = np.zeros((no_samples, n_classes)) one_hot[np.arange(no_samples),labels.ravel()] = 1 return one_hot
Next, we preprocess our dataset by passing the raw values to the utility functions we defined above.
x_train, x_test = normalize(x_train, x_test)y_train = convert_to_one_hot(y_train)y_test = convert_to_one_hot(y_test)
We will train an MLP classifier using TensorFlow. We will create a 6 layer network including the input and output layers. We will train two different models, one using the sigmoid activation function and the other using the RELU activation function. At every iteration of the backpropagation algorithm, we will store the gradients of loss with respect to the weights at each layer. Finally, through some visualizations, we will compare
The gradients of final layers vs the earlier layersThe gradients of sigmoid activation function vs the RELU activation function
The gradients of final layers vs the earlier layers
The gradients of sigmoid activation function vs the RELU activation function
Let’s build the model.
First, we define the placeholders for inputs and the targets.
def get_placeholders(input_size, output_size): inputs = tf.placeholder(dtype=tf.float32, shape=[None, input_size], name="inputs") targets = tf.placeholder(dtype=tf.float32, shape=[None, output_size], name="targets") return inputs, targets
We will define a function to create a fully connected layer. The weights at each layer are named in the format “kernel/<layer_num>”. This will be useful later to extract the gradients. More on this later.
def dense_layer(input, hidden_units, layer_no, activation_fn= tf.nn.relu): weights_name = "kernel/{}".format(layer_no) bias_name = "biases/{}".format(layer_no) weights = tf.get_variable(weights_name, shape=[input.shape[1], hidden_units], initializer = tf.contrib.layers.xavier_initializer(seed=0)) biases = tf.get_variable(bias_name, shape=[hidden_units], initializer = tf.zeros_initializer()) output = tf.add(tf.matmul(input, weights), biases) if activation_fn: return activation_fn(output) else: return output
Next, we define a function to create the forward pass of the network. We apply the activation function to each hidden layer. The output layer is not passed through an activation function as softmax activation for the output layer will be included in the loss definition.
def build_network(features, labels, hidden_units, num_layers, activation_fn): inputs = features for layer in range(num_layers-1): inputs = dense_layer(inputs, hidden_units[layer], layer+1, activation_fn) logits = dense_layer(inputs, 10, num_layers, None) return logits
As we want to classify between 10 different product categories, we apply the softmax activation to the output layer to get the final probabilities. We will use cross-entropy loss as a measure to identify how good is our network. Tensorflow provides a handy utility to compute both of them together using tf.nn.softmax_cross_entropy_with_logits_v2.
def compute_loss(logits, labels): loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels = labels , logits= logits)) train_op = tf.train.AdamOptimizer(0.001) return loss, train_op
If you see carefully, we haven’t added the minimize operation on the optimizer. The minimize operation internally performs two operations. First, it computes the gradients of the loss w.r.t the weights and biases. Second, it updates the weights and biases using the gradients computed above.
As we want the value of the gradients at each iteration to study the problem of vanishing gradients, we will define two separate operations, one to compute the gradients and the second to apply the gradients. We will revisit this later when we train our model.
We will also define a utility to compute the accuracy of the model. tf.argmax(logits,1) will return the index for which the probability is maximum. As the labels are one-hot encoded, tf.argmax(labels,1) will return the index where the value is 1. We compare both these values to determine the correct predictions and accuracy.
def compute_accuracy(logits, labels): correct_predictions = tf.equal(tf.argmax(logits,1), tf.argmax(labels,1)) accuracy = tf.reduce_mean(tf.cast(correct_predictions, tf.float32)) return accuracy
We will define a function to return the names of all the weights in the network. Remember that we defined the name of the weights as kernel/<layer_num>? Tensorflow internally appends “:0” to the name of the variable. You can read more about it here.
def get_weights_name(num_layers): return ["kernel/{}:0".format(layer+1) for layer in range(num_layers)]
We will define a function to train the model. We will train our model with sigmoid and RELU activations.
def train_model(features, labels, hidden_units, epochs, batch_size, learning_rate, num_layers, activation_fn): tf.reset_default_graph() input_size = features.shape[1] output_size = labels.shape[1] # get the placeholders inputs, targets = get_placeholders(input_size,output_size) # create a dataset dataset = tf.data.Dataset.from_tensor_slices((inputs, targets)) # make the required batches dataset = dataset.batch(batch_size) # initialize the iterator for the dataset iterator = dataset.make_initializable_iterator() # get the next batch x_batch, y_batch = iterator.get_next() # forward network logits = build_network(x_batch, y_batch, hidden_units, num_layers, activation_fn) # compute the loss loss, train_op = compute_loss(logits, y_batch) ''' instead of directly using the minimize function on the optimizer, we break the operation into two parts 1. compute the gradients 2. apply the gradients ''' grads_and_vars_tensor = train_op.compute_gradients(loss, tf.trainable_variables()) optimizer = train_op.apply_gradients(grads_and_vars_tensor) # compute the accuracy of the model accuracy = compute_accuracy(logits, y_batch) init_op = tf.global_variables_initializer() saver = tf.train.Saver() with tf.Session() as sess: sess.run(init_op) def_graph = tf.get_default_graph() gradient_means = [] losses = [] accuracies = [] train_samples = features.shape[0] iteration = 0 # get the name of all the trainable variables trainable_variables = [var.name for var in tf.trainable_variables()] for epoch in range(epochs): epoch_loss = 0 total_accuracy = 0 # run the iterator's initializer sess.run(iterator.initializer, feed_dict={inputs:features, targets:labels}) try: while True: gradients = [] batch_loss, grads_and_vars, _ , batch_accuracy = sess.run([loss, grads_and_vars_tensor, optimizer, accuracy]) if iteration % 100 == 0: # create a dictionary of all the trianbale variables and it's gradients var_grads = dict(zip(trainable_variables, [grad for grad,var in grads_and_vars])) # get the gradients of all the weights for all the layers weights_grads = [var_grads[var] for var in get_weights_name(num_layers)] # take the mean of the gradients at each layer mean_values = [np.mean(np.abs(val)) for val in weights_grads] gradient_means.append(mean_values) epoch_loss += batch_loss total_accuracy += batch_accuracy*batch_size iteration += 1 except tf.errors.OutOfRangeError: pass print("Total Iterations {}".format(iteration)) acc = total_accuracy/train_samples accuracies.append(acc) losses.append(epoch_loss) print("Epoch: {}/{} , Loss: {} , Accuracy: {}".format(epoch, epochs, epoch_loss, acc)) return losses, accuracies, gradient_means
As the function is very big, we will break it down into smaller parts to understand.
Feeding the data to the model
First, we use Datasets and Iterators to feed the data to the network. If you want to read more in detail about Datasets and Iterators, you can refer to this blog. We then define the logits, loss, optimizer and accuracy operations using the routines we defined earlier.
inputs, targets = get_placeholders(input_size,output_size)dataset = tf.data.Dataset.from_tensor_slices((inputs, targets))dataset = dataset.batch(batch_size)iterator = dataset.make_initializable_iterator()x_batch, y_batch = iterator.get_next() logits = build_network(x_batch, y_batch, num_layers, activation_fn) loss, train_op = compute_loss(logits, y_batch)accuracy = compute_accuracy(logits, y_batch)
Optimization operation
If you recollect, we hadn’t added the minimize operation to the optimizer as we wanted the values of the gradients. We can compute the gradients in Tensorflow using tf.compute_gradients. We can update the weights and biases using the above gradients using tf.apply_gradients.
grads_and_vars_tensor = train_op.compute_gradients(loss, tf.trainable_variables())optimizer = train_op.apply_gradients(grads_and_vars_tensor)
Training the model
with tf.Session() as sess: sess.run(init_op) def_graph = tf.get_default_graph() gradient_means = [] losses = [] accuracies = [] train_samples = features.shape[0] iteration = 0 trainable_variables = [var.name for var in tf.trainable_variables()] for epoch in range(epochs): epoch_loss = 0 total_accuracy = 0 sess.run(iterator.initializer, feed_dict={inputs:features, targets:labels}) try: while True: gradients = [] batch_loss, grads_and_vars, _ , batch_accuracy = sess.run([loss, grads_and_vars_tensor, optimizer, accuracy]) var_grads = dict(zip(trainable_variables, [grad for grad,var in grads_and_vars])) weights_grads = [var_grads[var] for var in get_weights_name(num_layers)] mean_values = [np.mean(np.abs(val)) for val in weights_grads] epoch_loss += batch_loss total_accuracy += batch_accuracy*batch_size iteration += 1 gradient_means.append(mean_values) except tf.errors.OutOfRangeError: pass print("Total Iterations {}".format(iteration)) acc = total_accuracy/train_samples accuracies.append(acc) losses.append(epoch_loss) print("Epoch: {}/{} , Loss: {} , Accuracy: {}".format(epoch, epochs, epoch_loss, acc)) return losses, accuracies, gradient_means
We have computed the mean of the gradients for each layer at every iteration using the below code.
var_grads = dict(zip(trainable_variables, [grad for grad,var in grads_and_vars]))weights_grads = [var_grads[var] for var in get_weights_name(num_layers)]mean_values = [np.mean(np.abs(val)) for val in weights_grads
We first create a dictionary of all the trainable variables along with the gradients. Next, we extract the gradients only for weights and compute the mean for each layer.
We have defined all the routines we need to run the model. Let’s define the model’s hyperparameters and run the model for both the sigmoid and RELU activation functions.
features = x_trainlabels = y_trainepochs = 20batch_size = 256 learning_rate = 0.001num_layers = 5hidden_units = [30,30,30,30]input_units = x_train.shape[1]output_units = y_train.shape[1] # run the model for the activation functions sigmoid and reluactivation_fns = {"sigmoid":tf.nn.sigmoid, "relu":tf.nn.relu}loss = {}acc= {}grad={} for name, activation_fn in activation_fns.items(): model_name = "Running model with activation function as {}".format(name) print(model_name) losses, accuracies, grad_means = train_model(features = features, labels = labels, hidden_units = hidden_units, epochs = epochs, batch_size = batch_size, learning_rate = learning_rate, num_layers = num_layers, activation_fn = activation_fn) loss[name] = losses acc[name] = accuracies grad[name] = grad_means
Let’s compare the accuracy and the gradients for both the models using some visualizations.
Accuracy
def plot_accuracy(accuracies, title): for name, values in accuracies.items(): plt.plot(values, label = name) plt.legend(title=title)plot_accuracy(acc, "Accuracy")
We can see that the accuracy of the model trained with the RELU function is more than the model trained with the sigmoid. It can also be observed that it takes more time for the sigmoid model to achieve high accuracy. WHY? Learning is slow in earlier layers due to the problem of vanishing gradients.
Let’s plot the gradients of each layer.
def plot_gradients(grads): sigmoid = np.array(grads['sigmoid']) relu = np.array(grads['relu']) for layer_num in range(num_layers): plt.figure(figsize=(20,20)) plt.subplot(5,1,layer_num+1) plt.plot(sigmoid[:,layer_num], label='Sigmoid') plt.plot(relu[:,layer_num], label='Relu') plt.legend(title='Layer{}'.format(layer_num+1))plot_gradients(grad)
We can draw two major conclusions from the above graphs
The magnitude of gradients in earlier layers are very low compared to the gradients in the final layers. This explains the problem of vanishing gradients.The value of gradients of the sigmoid model is very low as compared to the RELU model.
The magnitude of gradients in earlier layers are very low compared to the gradients in the final layers. This explains the problem of vanishing gradients.
The value of gradients of the sigmoid model is very low as compared to the RELU model.
In this blog, we have discussed the problem of vanishing gradients and how it is alleviated when we use the sigmoid function. We also discussed how the RELU function helps in reducing this problem considerably.
Thanks for reading the blog. Hope you liked the article. Do leave your suggestions in the below comments.
The entire code for this article can be found in this Jupyter Notebook. | [
{
"code": null,
"e": 379,
"s": 171,
"text": "Vanishing gradients occur while training deep neural networks using gradient-based optimization methods. It occurs due to the nature of the backpropagation algorithm that is used to train the neural network."
},
{
"code": null,
"e": 795,
"s": 379,
"text": "Explain the problem of vanishing gradients: We will understand why the problem of vanishing gradients exists. We will also look at why this problem is more observed while using the sigmoid activation function and how RELU reduces the problem.A comparative study using TensorFlow: We will train an MLP classifier on the Fashion MNIST dataset using the sigmoid and RELU activation functions and compare the gradients."
},
{
"code": null,
"e": 1038,
"s": 795,
"text": "Explain the problem of vanishing gradients: We will understand why the problem of vanishing gradients exists. We will also look at why this problem is more observed while using the sigmoid activation function and how RELU reduces the problem."
},
{
"code": null,
"e": 1212,
"s": 1038,
"text": "A comparative study using TensorFlow: We will train an MLP classifier on the Fashion MNIST dataset using the sigmoid and RELU activation functions and compare the gradients."
},
{
"code": null,
"e": 1521,
"s": 1212,
"text": "Before we can understand why the problem of vanishing gradients exists, we should have some understanding of the equations of the backpropagation algorithm. I will not derive the backpropagation equations as it is beyond the scope of this article. However, I have attached a screenshot from this famous book."
},
{
"code": null,
"e": 1535,
"s": 1521,
"text": "Observations:"
},
{
"code": null,
"e": 2097,
"s": 1535,
"text": "From equation 1&2 we can see that the error in the output layer depends on the derivative of the activation function.From equation 2 we can observe that the error in the previous/hidden layer is proportional to the weights, the error from the outer layers and the derivative of the activation function. The error from outer layers is in turn dependent on the derivative of the activation function of its layer.From equation 1,2 &4 we can conclude that the gradients for weights for any layer are dependent on the product of derivatives of the activation layers."
},
{
"code": null,
"e": 2215,
"s": 2097,
"text": "From equation 1&2 we can see that the error in the output layer depends on the derivative of the activation function."
},
{
"code": null,
"e": 2509,
"s": 2215,
"text": "From equation 2 we can observe that the error in the previous/hidden layer is proportional to the weights, the error from the outer layers and the derivative of the activation function. The error from outer layers is in turn dependent on the derivative of the activation function of its layer."
},
{
"code": null,
"e": 2661,
"s": 2509,
"text": "From equation 1,2 &4 we can conclude that the gradients for weights for any layer are dependent on the product of derivatives of the activation layers."
},
{
"code": null,
"e": 3028,
"s": 2661,
"text": "Consider the graph of sigmoid function and it’s derivative. Observe that for very large values for sigmoid function the derivative takes a very low value. If the neural network has many hidden layers, the gradients in the earlier layers will become very low as we multiply the derivatives of each layer. As a result, learning in the earlier layers becomes very slow."
},
{
"code": null,
"e": 3489,
"s": 3028,
"text": "On the other hand, the derivative of the RELU function is either zero or 1. Even if we multiply the derivatives for many layers, there will be no degradation unlike the case of the sigmoid function (assuming that RELU is not operating in the dead-region). However, if you carefully look at equation 2, the error signal is also dependent on the weights of the network. If the weights of the network are constantly below zero, the gradients will diminish slowly."
},
{
"code": null,
"e": 3669,
"s": 3489,
"text": "Now that we have understood the problem of vanishing gradients, let’s train two different MLP Classifiers, one using the sigmoid and the other using the RELU activation functions."
},
{
"code": null,
"e": 3688,
"s": 3669,
"text": "Let’s get started."
},
{
"code": null,
"e": 3705,
"s": 3688,
"text": "Import Libraries"
},
{
"code": null,
"e": 3828,
"s": 3705,
"text": "import tensorflow as tfimport numpy as npfrom tensorflow import kerasimport matplotlib.pyplot as plt from tqdm import tqdm"
},
{
"code": null,
"e": 3849,
"s": 3828,
"text": "Download the dataset"
},
{
"code": null,
"e": 4049,
"s": 3849,
"text": "We will be using the Fashion MNIST dataset. It consists of 70000 grayscale images of 10 different product categories. Each product category has 7000 samples. You can read more about the dataset here."
},
{
"code": null,
"e": 4106,
"s": 4049,
"text": "We will use Keras to download the Fashion MNIST dataset."
},
{
"code": null,
"e": 4335,
"s": 4106,
"text": "fashion_mnist = keras.datasets.fashion_mnist(x_train, y_train), (x_test, y_test) = fashion_mnist.load_data()print(x_train.shape)print(y_train.shape)print(x_test.shape)print(y_test.shape)(60000,28,28)(60000,)(10000,28,28)(10000,)"
},
{
"code": null,
"e": 4443,
"s": 4335,
"text": "As we will be using an MLP Classifier, we need to flatten the 28*28 grayscale image into a 784 long vector."
},
{
"code": null,
"e": 4512,
"s": 4443,
"text": "x_train = x_train.reshape(60000,-1)x_test = x_test.reshape(10000,-1)"
},
{
"code": null,
"e": 4668,
"s": 4512,
"text": "The pixel values of the images are between 0 and 1. We will define a function to standardize the dataset by removing the mean and scaling to unit variance."
},
{
"code": null,
"e": 4873,
"s": 4668,
"text": "def normalize(x_train, x_test): train_mean = np.mean(x_train) train_std = np.mean(x_train) x_train = (x_train - train_mean)/train_std x_test = (x_test - train_mean)/train_std return x_train, x_test"
},
{
"code": null,
"e": 4991,
"s": 4873,
"text": "The product categories are labeled from 0 to 9. We will define a utility to convert the values into one hot encoding."
},
{
"code": null,
"e": 5197,
"s": 4991,
"text": "def convert_to_one_hot(labels): no_samples = labels.shape[0] n_classes = np.max(labels) + 1 one_hot = np.zeros((no_samples, n_classes)) one_hot[np.arange(no_samples),labels.ravel()] = 1 return one_hot"
},
{
"code": null,
"e": 5298,
"s": 5197,
"text": "Next, we preprocess our dataset by passing the raw values to the utility functions we defined above."
},
{
"code": null,
"e": 5415,
"s": 5298,
"text": "x_train, x_test = normalize(x_train, x_test)y_train = convert_to_one_hot(y_train)y_test = convert_to_one_hot(y_test)"
},
{
"code": null,
"e": 5851,
"s": 5415,
"text": "We will train an MLP classifier using TensorFlow. We will create a 6 layer network including the input and output layers. We will train two different models, one using the sigmoid activation function and the other using the RELU activation function. At every iteration of the backpropagation algorithm, we will store the gradients of loss with respect to the weights at each layer. Finally, through some visualizations, we will compare"
},
{
"code": null,
"e": 5979,
"s": 5851,
"text": "The gradients of final layers vs the earlier layersThe gradients of sigmoid activation function vs the RELU activation function"
},
{
"code": null,
"e": 6031,
"s": 5979,
"text": "The gradients of final layers vs the earlier layers"
},
{
"code": null,
"e": 6108,
"s": 6031,
"text": "The gradients of sigmoid activation function vs the RELU activation function"
},
{
"code": null,
"e": 6131,
"s": 6108,
"text": "Let’s build the model."
},
{
"code": null,
"e": 6193,
"s": 6131,
"text": "First, we define the placeholders for inputs and the targets."
},
{
"code": null,
"e": 6435,
"s": 6193,
"text": "def get_placeholders(input_size, output_size): inputs = tf.placeholder(dtype=tf.float32, shape=[None, input_size], name=\"inputs\") targets = tf.placeholder(dtype=tf.float32, shape=[None, output_size], name=\"targets\") return inputs, targets"
},
{
"code": null,
"e": 6640,
"s": 6435,
"text": "We will define a function to create a fully connected layer. The weights at each layer are named in the format “kernel/<layer_num>”. This will be useful later to extract the gradients. More on this later."
},
{
"code": null,
"e": 7165,
"s": 6640,
"text": "def dense_layer(input, hidden_units, layer_no, activation_fn= tf.nn.relu): weights_name = \"kernel/{}\".format(layer_no) bias_name = \"biases/{}\".format(layer_no) weights = tf.get_variable(weights_name, shape=[input.shape[1], hidden_units], initializer = tf.contrib.layers.xavier_initializer(seed=0)) biases = tf.get_variable(bias_name, shape=[hidden_units], initializer = tf.zeros_initializer()) output = tf.add(tf.matmul(input, weights), biases) if activation_fn: return activation_fn(output) else: return output"
},
{
"code": null,
"e": 7436,
"s": 7165,
"text": "Next, we define a function to create the forward pass of the network. We apply the activation function to each hidden layer. The output layer is not passed through an activation function as softmax activation for the output layer will be included in the loss definition."
},
{
"code": null,
"e": 7713,
"s": 7436,
"text": "def build_network(features, labels, hidden_units, num_layers, activation_fn): inputs = features for layer in range(num_layers-1): inputs = dense_layer(inputs, hidden_units[layer], layer+1, activation_fn) logits = dense_layer(inputs, 10, num_layers, None) return logits"
},
{
"code": null,
"e": 8061,
"s": 7713,
"text": "As we want to classify between 10 different product categories, we apply the softmax activation to the output layer to get the final probabilities. We will use cross-entropy loss as a measure to identify how good is our network. Tensorflow provides a handy utility to compute both of them together using tf.nn.softmax_cross_entropy_with_logits_v2."
},
{
"code": null,
"e": 8261,
"s": 8061,
"text": "def compute_loss(logits, labels): loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels = labels , logits= logits)) train_op = tf.train.AdamOptimizer(0.001) return loss, train_op"
},
{
"code": null,
"e": 8553,
"s": 8261,
"text": "If you see carefully, we haven’t added the minimize operation on the optimizer. The minimize operation internally performs two operations. First, it computes the gradients of the loss w.r.t the weights and biases. Second, it updates the weights and biases using the gradients computed above."
},
{
"code": null,
"e": 8814,
"s": 8553,
"text": "As we want the value of the gradients at each iteration to study the problem of vanishing gradients, we will define two separate operations, one to compute the gradients and the second to apply the gradients. We will revisit this later when we train our model."
},
{
"code": null,
"e": 9141,
"s": 8814,
"text": "We will also define a utility to compute the accuracy of the model. tf.argmax(logits,1) will return the index for which the probability is maximum. As the labels are one-hot encoded, tf.argmax(labels,1) will return the index where the value is 1. We compare both these values to determine the correct predictions and accuracy."
},
{
"code": null,
"e": 9339,
"s": 9141,
"text": "def compute_accuracy(logits, labels): correct_predictions = tf.equal(tf.argmax(logits,1), tf.argmax(labels,1)) accuracy = tf.reduce_mean(tf.cast(correct_predictions, tf.float32)) return accuracy"
},
{
"code": null,
"e": 9589,
"s": 9339,
"text": "We will define a function to return the names of all the weights in the network. Remember that we defined the name of the weights as kernel/<layer_num>? Tensorflow internally appends “:0” to the name of the variable. You can read more about it here."
},
{
"code": null,
"e": 9694,
"s": 9589,
"text": "def get_weights_name(num_layers): return [\"kernel/{}:0\".format(layer+1) for layer in range(num_layers)]"
},
{
"code": null,
"e": 9799,
"s": 9694,
"text": "We will define a function to train the model. We will train our model with sigmoid and RELU activations."
},
{
"code": null,
"e": 12791,
"s": 9799,
"text": "def train_model(features, labels, hidden_units, epochs, batch_size, learning_rate, num_layers, activation_fn): tf.reset_default_graph() input_size = features.shape[1] output_size = labels.shape[1] # get the placeholders inputs, targets = get_placeholders(input_size,output_size) # create a dataset dataset = tf.data.Dataset.from_tensor_slices((inputs, targets)) # make the required batches dataset = dataset.batch(batch_size) # initialize the iterator for the dataset iterator = dataset.make_initializable_iterator() # get the next batch x_batch, y_batch = iterator.get_next() # forward network logits = build_network(x_batch, y_batch, hidden_units, num_layers, activation_fn) # compute the loss loss, train_op = compute_loss(logits, y_batch) ''' instead of directly using the minimize function on the optimizer, we break the operation into two parts 1. compute the gradients 2. apply the gradients ''' grads_and_vars_tensor = train_op.compute_gradients(loss, tf.trainable_variables()) optimizer = train_op.apply_gradients(grads_and_vars_tensor) # compute the accuracy of the model accuracy = compute_accuracy(logits, y_batch) init_op = tf.global_variables_initializer() saver = tf.train.Saver() with tf.Session() as sess: sess.run(init_op) def_graph = tf.get_default_graph() gradient_means = [] losses = [] accuracies = [] train_samples = features.shape[0] iteration = 0 # get the name of all the trainable variables trainable_variables = [var.name for var in tf.trainable_variables()] for epoch in range(epochs): epoch_loss = 0 total_accuracy = 0 # run the iterator's initializer sess.run(iterator.initializer, feed_dict={inputs:features, targets:labels}) try: while True: gradients = [] batch_loss, grads_and_vars, _ , batch_accuracy = sess.run([loss, grads_and_vars_tensor, optimizer, accuracy]) if iteration % 100 == 0: # create a dictionary of all the trianbale variables and it's gradients var_grads = dict(zip(trainable_variables, [grad for grad,var in grads_and_vars])) # get the gradients of all the weights for all the layers weights_grads = [var_grads[var] for var in get_weights_name(num_layers)] # take the mean of the gradients at each layer mean_values = [np.mean(np.abs(val)) for val in weights_grads] gradient_means.append(mean_values) epoch_loss += batch_loss total_accuracy += batch_accuracy*batch_size iteration += 1 except tf.errors.OutOfRangeError: pass print(\"Total Iterations {}\".format(iteration)) acc = total_accuracy/train_samples accuracies.append(acc) losses.append(epoch_loss) print(\"Epoch: {}/{} , Loss: {} , Accuracy: {}\".format(epoch, epochs, epoch_loss, acc)) return losses, accuracies, gradient_means"
},
{
"code": null,
"e": 12876,
"s": 12791,
"text": "As the function is very big, we will break it down into smaller parts to understand."
},
{
"code": null,
"e": 12906,
"s": 12876,
"text": "Feeding the data to the model"
},
{
"code": null,
"e": 13175,
"s": 12906,
"text": "First, we use Datasets and Iterators to feed the data to the network. If you want to read more in detail about Datasets and Iterators, you can refer to this blog. We then define the logits, loss, optimizer and accuracy operations using the routines we defined earlier."
},
{
"code": null,
"e": 13578,
"s": 13175,
"text": "inputs, targets = get_placeholders(input_size,output_size)dataset = tf.data.Dataset.from_tensor_slices((inputs, targets))dataset = dataset.batch(batch_size)iterator = dataset.make_initializable_iterator()x_batch, y_batch = iterator.get_next() logits = build_network(x_batch, y_batch, num_layers, activation_fn) loss, train_op = compute_loss(logits, y_batch)accuracy = compute_accuracy(logits, y_batch)"
},
{
"code": null,
"e": 13601,
"s": 13578,
"text": "Optimization operation"
},
{
"code": null,
"e": 13877,
"s": 13601,
"text": "If you recollect, we hadn’t added the minimize operation to the optimizer as we wanted the values of the gradients. We can compute the gradients in Tensorflow using tf.compute_gradients. We can update the weights and biases using the above gradients using tf.apply_gradients."
},
{
"code": null,
"e": 14019,
"s": 13877,
"text": "grads_and_vars_tensor = train_op.compute_gradients(loss, tf.trainable_variables())optimizer = train_op.apply_gradients(grads_and_vars_tensor)"
},
{
"code": null,
"e": 14038,
"s": 14019,
"text": "Training the model"
},
{
"code": null,
"e": 15390,
"s": 14038,
"text": "with tf.Session() as sess: sess.run(init_op) def_graph = tf.get_default_graph() gradient_means = [] losses = [] accuracies = [] train_samples = features.shape[0] iteration = 0 trainable_variables = [var.name for var in tf.trainable_variables()] for epoch in range(epochs): epoch_loss = 0 total_accuracy = 0 sess.run(iterator.initializer, feed_dict={inputs:features, targets:labels}) try: while True: gradients = [] batch_loss, grads_and_vars, _ , batch_accuracy = sess.run([loss, grads_and_vars_tensor, optimizer, accuracy]) var_grads = dict(zip(trainable_variables, [grad for grad,var in grads_and_vars])) weights_grads = [var_grads[var] for var in get_weights_name(num_layers)] mean_values = [np.mean(np.abs(val)) for val in weights_grads] epoch_loss += batch_loss total_accuracy += batch_accuracy*batch_size iteration += 1 gradient_means.append(mean_values) except tf.errors.OutOfRangeError: pass print(\"Total Iterations {}\".format(iteration)) acc = total_accuracy/train_samples accuracies.append(acc) losses.append(epoch_loss) print(\"Epoch: {}/{} , Loss: {} , Accuracy: {}\".format(epoch, epochs, epoch_loss, acc)) return losses, accuracies, gradient_means"
},
{
"code": null,
"e": 15489,
"s": 15390,
"text": "We have computed the mean of the gradients for each layer at every iteration using the below code."
},
{
"code": null,
"e": 15703,
"s": 15489,
"text": "var_grads = dict(zip(trainable_variables, [grad for grad,var in grads_and_vars]))weights_grads = [var_grads[var] for var in get_weights_name(num_layers)]mean_values = [np.mean(np.abs(val)) for val in weights_grads"
},
{
"code": null,
"e": 15874,
"s": 15703,
"text": "We first create a dictionary of all the trainable variables along with the gradients. Next, we extract the gradients only for weights and compute the mean for each layer."
},
{
"code": null,
"e": 16044,
"s": 15874,
"text": "We have defined all the routines we need to run the model. Let’s define the model’s hyperparameters and run the model for both the sigmoid and RELU activation functions."
},
{
"code": null,
"e": 16978,
"s": 16044,
"text": "features = x_trainlabels = y_trainepochs = 20batch_size = 256 learning_rate = 0.001num_layers = 5hidden_units = [30,30,30,30]input_units = x_train.shape[1]output_units = y_train.shape[1] # run the model for the activation functions sigmoid and reluactivation_fns = {\"sigmoid\":tf.nn.sigmoid, \"relu\":tf.nn.relu}loss = {}acc= {}grad={} for name, activation_fn in activation_fns.items(): model_name = \"Running model with activation function as {}\".format(name) print(model_name) losses, accuracies, grad_means = train_model(features = features, labels = labels, hidden_units = hidden_units, epochs = epochs, batch_size = batch_size, learning_rate = learning_rate, num_layers = num_layers, activation_fn = activation_fn) loss[name] = losses acc[name] = accuracies grad[name] = grad_means"
},
{
"code": null,
"e": 17070,
"s": 16978,
"text": "Let’s compare the accuracy and the gradients for both the models using some visualizations."
},
{
"code": null,
"e": 17079,
"s": 17070,
"text": "Accuracy"
},
{
"code": null,
"e": 17249,
"s": 17079,
"text": "def plot_accuracy(accuracies, title): for name, values in accuracies.items(): plt.plot(values, label = name) plt.legend(title=title)plot_accuracy(acc, \"Accuracy\")"
},
{
"code": null,
"e": 17550,
"s": 17249,
"text": "We can see that the accuracy of the model trained with the RELU function is more than the model trained with the sigmoid. It can also be observed that it takes more time for the sigmoid model to achieve high accuracy. WHY? Learning is slow in earlier layers due to the problem of vanishing gradients."
},
{
"code": null,
"e": 17590,
"s": 17550,
"text": "Let’s plot the gradients of each layer."
},
{
"code": null,
"e": 17954,
"s": 17590,
"text": "def plot_gradients(grads): sigmoid = np.array(grads['sigmoid']) relu = np.array(grads['relu']) for layer_num in range(num_layers): plt.figure(figsize=(20,20)) plt.subplot(5,1,layer_num+1) plt.plot(sigmoid[:,layer_num], label='Sigmoid') plt.plot(relu[:,layer_num], label='Relu') plt.legend(title='Layer{}'.format(layer_num+1))plot_gradients(grad)"
},
{
"code": null,
"e": 18010,
"s": 17954,
"text": "We can draw two major conclusions from the above graphs"
},
{
"code": null,
"e": 18251,
"s": 18010,
"text": "The magnitude of gradients in earlier layers are very low compared to the gradients in the final layers. This explains the problem of vanishing gradients.The value of gradients of the sigmoid model is very low as compared to the RELU model."
},
{
"code": null,
"e": 18406,
"s": 18251,
"text": "The magnitude of gradients in earlier layers are very low compared to the gradients in the final layers. This explains the problem of vanishing gradients."
},
{
"code": null,
"e": 18493,
"s": 18406,
"text": "The value of gradients of the sigmoid model is very low as compared to the RELU model."
},
{
"code": null,
"e": 18704,
"s": 18493,
"text": "In this blog, we have discussed the problem of vanishing gradients and how it is alleviated when we use the sigmoid function. We also discussed how the RELU function helps in reducing this problem considerably."
},
{
"code": null,
"e": 18810,
"s": 18704,
"text": "Thanks for reading the blog. Hope you liked the article. Do leave your suggestions in the below comments."
}
] |
Say Goodbye to Excel? A Simple Evaluation of Python Grid Studio Using COVID-19 Data | by Christopher Tao | Towards Data Science | Recently, I found an excellent open-source project “Grid Studio”. This library combines the advantages of the spreadsheet and Python in terms of data analytics.
Have you been thinking that
When you use MS Excel, you want to use your Python skills and libraries such as Numpy, Pandas, SciPy, Matplotlib and Scikit-learn to generate and manipulate data
When you use Python, you may think the tabular view of the data is needed to have a picture of the current dataset in real-time, but what you can do is only output df.head() manually.
OK, this library can satisfy all your requirements.
Before everything, let’s have a look at how it looks like. Grid Studio is a Web-based application. Here is the Web UI.
The UI is divided into 3 main panels.
The spreadsheet, which is the same as popular software such as Excel and Google Sheets.Code area, in which you can write your python code.File/Plots/Terminal/Stdout window, which aggregates these 4 windows as different tabs.
The spreadsheet, which is the same as popular software such as Excel and Google Sheets.
Code area, in which you can write your python code.
File/Plots/Terminal/Stdout window, which aggregates these 4 windows as different tabs.
Therefore, with this library, you can use the code area to write your Python code and run it line-by-line just like Jupyter/iPython, and the “Python out” window will show the results. Also, you may synchronise your Pandas data frame to the spreadsheet to have an instant look.
Let’s start with the installation of Grid Studio. You will need docker on your local machine to run the source code. If you don’t have a docker desktop at the moment, you can download it from here:
www.docker.com
After that, clone the repo at GitHub:
github.com
git clone https://github.com/ricklamers/gridstudio
Then, simply go to its root folder and run the starting script:
cd gridstudio && ./run.sh
It may take a couple of minutes to wait for docker to pull all the components. After that, you will be able to access the Web UI at
http://localhost:8080/
I don’t like to write examples for the sake of examples. So, let’s use some real data to do some basic data analysis using Grid Studio.
We can get COVID-19 confirmed cases data here:
www.ecdc.europa.eu
Download the data as a CSV file, which contains COVID-19 data for all countries in the world.
# Read all datadf = pd.read_csv("https://opendata.ecdc.europa.eu/covid19/casedistribution/csv").dropna()print(df.head())
We can directly read online CSV files via the link. Here I think there is an improvement of Grid Studio. That is, it does not like Jupyter Notebook that can instantly print your variables. If you want to print your variables, you have to use theprint method.
Another limitation is that it looks like the spreadsheet does not support datetime type very well. During the testing, I found that it cannot display pandas column with datetime64[ns] type. So, I would like to convert the dateRep column into integers.
# Convert date to integer (because of Grid Studio limitation)df.dateRep = pd.to_datetime(df.dateRep, format='%d/%m/%Y').dt.strftime('%Y%m%d').astype(int)
Firstly, let’s filter the data by country. For example, I’m interested in Australian data only.
# Get Australia datadf_oz = df[df.countriesAndTerritories == 'Australia']
Then, we will select only the dateRep, cases and deaths columns.
# Retain only date, cases and deaths columnsdf_oz = df_oz[['dateRep', 'cases', 'deaths']]
After that, sort the data frame by the date so that we can calculate the cumulative cases and deaths.
# Calculate cumulative cases & deathsdf_oz = df_oz.sort_values('dateRep')df_oz['cumCases'] = df_oz.cases.cumsum()df_oz['cumDeaths'] = df_oz.deaths.cumsum()
Now, we should have 5 columns in our Pandas data frame, which are date, new cases, new deaths, cumulative cases and cumulative deaths. Let’s render the data frame into the spreadsheet.
# Show in sheetsheet("A1", df_oz)
Grid Studio makes it very easy to do this. By calling its API sheet, we simply specify the top-left cell that the data frame will be rendered, and then pass on the data frame variable.
If you would like to show the headers, you can also specify header=True in the sheet method.
When the data is in the spreadsheet, we can use it just like the other regular software such as Excel and Google Sheets. I won’t demonstrate the formula features such as SUM, AVG and etc. that everyone would be familiar with.
One of the most useful features is that you can easily export the spreadsheet into CSV. That means we can use the power of Pandas data frame to easily download and transform the data, then export to use other software to do further analytics.
Another one I believe that is quite useful is plotting the data using matplotlib by clicks. For example, if we want to plot the daily new cases, just simply select the “new cases” column and right-click on it as shown in the screenshot below.
Then, on the bottom right corner, you can find the plot in the “Plots” tab.
In fact, Grid studio has done this plot by auto-generating code. Here is the code that is generated for the above chart.
data = sheet("B1:B106")data.plot()show()
So, we can add some annotations if necessary. For example, we can add a title to this chart:
data = sheet("B1:B106")data.plot(title='Daily New Cases')show()
Similarly, we can plot the 4 columns separately using the same procedures. The following 3 more charts were generated by simple clicks and adding titles which took me 30 seconds in total!
It is clear that using Grid Studio to perform some simple data analysis would be very quick and convenient. Thanks to Rick Lamers who is the author for his amazing idea.
While I really like the idea of this application that combines spreadsheet and Python, I have to say that it is still far away from mature. At least some limitations and potential improvements need to be resolved and implemented in my opinion:
Should support all the Pandas data typesShould implement more features of spreadsheets that most similar applications would have such as dragging to fillThere are some bugs in the spreadsheet that need to be fixed, for example, the loaded data seems stuck in the memory that might not be able to be deleted from the spreadsheet.Suggestion: it would be great if we can bind the sheet with a Pandas data frame. That is, when you modify the sheet, the data frame is updated, and vice versa.Suggestion: it would be great if the Python stdout output can be converted to iPython style with [1]: line number, which will make debugging much easier.
Should support all the Pandas data types
Should implement more features of spreadsheets that most similar applications would have such as dragging to fill
There are some bugs in the spreadsheet that need to be fixed, for example, the loaded data seems stuck in the memory that might not be able to be deleted from the spreadsheet.
Suggestion: it would be great if we can bind the sheet with a Pandas data frame. That is, when you modify the sheet, the data frame is updated, and vice versa.
Suggestion: it would be great if the Python stdout output can be converted to iPython style with [1]: line number, which will make debugging much easier.
medium.com
If you feel my articles are helpful, please consider joining Medium Membership to support me and thousands of other writers! (Click the link above) | [
{
"code": null,
"e": 333,
"s": 172,
"text": "Recently, I found an excellent open-source project “Grid Studio”. This library combines the advantages of the spreadsheet and Python in terms of data analytics."
},
{
"code": null,
"e": 361,
"s": 333,
"text": "Have you been thinking that"
},
{
"code": null,
"e": 523,
"s": 361,
"text": "When you use MS Excel, you want to use your Python skills and libraries such as Numpy, Pandas, SciPy, Matplotlib and Scikit-learn to generate and manipulate data"
},
{
"code": null,
"e": 707,
"s": 523,
"text": "When you use Python, you may think the tabular view of the data is needed to have a picture of the current dataset in real-time, but what you can do is only output df.head() manually."
},
{
"code": null,
"e": 759,
"s": 707,
"text": "OK, this library can satisfy all your requirements."
},
{
"code": null,
"e": 878,
"s": 759,
"text": "Before everything, let’s have a look at how it looks like. Grid Studio is a Web-based application. Here is the Web UI."
},
{
"code": null,
"e": 916,
"s": 878,
"text": "The UI is divided into 3 main panels."
},
{
"code": null,
"e": 1141,
"s": 916,
"text": "The spreadsheet, which is the same as popular software such as Excel and Google Sheets.Code area, in which you can write your python code.File/Plots/Terminal/Stdout window, which aggregates these 4 windows as different tabs."
},
{
"code": null,
"e": 1229,
"s": 1141,
"text": "The spreadsheet, which is the same as popular software such as Excel and Google Sheets."
},
{
"code": null,
"e": 1281,
"s": 1229,
"text": "Code area, in which you can write your python code."
},
{
"code": null,
"e": 1368,
"s": 1281,
"text": "File/Plots/Terminal/Stdout window, which aggregates these 4 windows as different tabs."
},
{
"code": null,
"e": 1645,
"s": 1368,
"text": "Therefore, with this library, you can use the code area to write your Python code and run it line-by-line just like Jupyter/iPython, and the “Python out” window will show the results. Also, you may synchronise your Pandas data frame to the spreadsheet to have an instant look."
},
{
"code": null,
"e": 1843,
"s": 1645,
"text": "Let’s start with the installation of Grid Studio. You will need docker on your local machine to run the source code. If you don’t have a docker desktop at the moment, you can download it from here:"
},
{
"code": null,
"e": 1858,
"s": 1843,
"text": "www.docker.com"
},
{
"code": null,
"e": 1896,
"s": 1858,
"text": "After that, clone the repo at GitHub:"
},
{
"code": null,
"e": 1907,
"s": 1896,
"text": "github.com"
},
{
"code": null,
"e": 1958,
"s": 1907,
"text": "git clone https://github.com/ricklamers/gridstudio"
},
{
"code": null,
"e": 2022,
"s": 1958,
"text": "Then, simply go to its root folder and run the starting script:"
},
{
"code": null,
"e": 2048,
"s": 2022,
"text": "cd gridstudio && ./run.sh"
},
{
"code": null,
"e": 2180,
"s": 2048,
"text": "It may take a couple of minutes to wait for docker to pull all the components. After that, you will be able to access the Web UI at"
},
{
"code": null,
"e": 2203,
"s": 2180,
"text": "http://localhost:8080/"
},
{
"code": null,
"e": 2339,
"s": 2203,
"text": "I don’t like to write examples for the sake of examples. So, let’s use some real data to do some basic data analysis using Grid Studio."
},
{
"code": null,
"e": 2386,
"s": 2339,
"text": "We can get COVID-19 confirmed cases data here:"
},
{
"code": null,
"e": 2405,
"s": 2386,
"text": "www.ecdc.europa.eu"
},
{
"code": null,
"e": 2499,
"s": 2405,
"text": "Download the data as a CSV file, which contains COVID-19 data for all countries in the world."
},
{
"code": null,
"e": 2620,
"s": 2499,
"text": "# Read all datadf = pd.read_csv(\"https://opendata.ecdc.europa.eu/covid19/casedistribution/csv\").dropna()print(df.head())"
},
{
"code": null,
"e": 2879,
"s": 2620,
"text": "We can directly read online CSV files via the link. Here I think there is an improvement of Grid Studio. That is, it does not like Jupyter Notebook that can instantly print your variables. If you want to print your variables, you have to use theprint method."
},
{
"code": null,
"e": 3131,
"s": 2879,
"text": "Another limitation is that it looks like the spreadsheet does not support datetime type very well. During the testing, I found that it cannot display pandas column with datetime64[ns] type. So, I would like to convert the dateRep column into integers."
},
{
"code": null,
"e": 3285,
"s": 3131,
"text": "# Convert date to integer (because of Grid Studio limitation)df.dateRep = pd.to_datetime(df.dateRep, format='%d/%m/%Y').dt.strftime('%Y%m%d').astype(int)"
},
{
"code": null,
"e": 3381,
"s": 3285,
"text": "Firstly, let’s filter the data by country. For example, I’m interested in Australian data only."
},
{
"code": null,
"e": 3455,
"s": 3381,
"text": "# Get Australia datadf_oz = df[df.countriesAndTerritories == 'Australia']"
},
{
"code": null,
"e": 3520,
"s": 3455,
"text": "Then, we will select only the dateRep, cases and deaths columns."
},
{
"code": null,
"e": 3610,
"s": 3520,
"text": "# Retain only date, cases and deaths columnsdf_oz = df_oz[['dateRep', 'cases', 'deaths']]"
},
{
"code": null,
"e": 3712,
"s": 3610,
"text": "After that, sort the data frame by the date so that we can calculate the cumulative cases and deaths."
},
{
"code": null,
"e": 3868,
"s": 3712,
"text": "# Calculate cumulative cases & deathsdf_oz = df_oz.sort_values('dateRep')df_oz['cumCases'] = df_oz.cases.cumsum()df_oz['cumDeaths'] = df_oz.deaths.cumsum()"
},
{
"code": null,
"e": 4053,
"s": 3868,
"text": "Now, we should have 5 columns in our Pandas data frame, which are date, new cases, new deaths, cumulative cases and cumulative deaths. Let’s render the data frame into the spreadsheet."
},
{
"code": null,
"e": 4087,
"s": 4053,
"text": "# Show in sheetsheet(\"A1\", df_oz)"
},
{
"code": null,
"e": 4272,
"s": 4087,
"text": "Grid Studio makes it very easy to do this. By calling its API sheet, we simply specify the top-left cell that the data frame will be rendered, and then pass on the data frame variable."
},
{
"code": null,
"e": 4365,
"s": 4272,
"text": "If you would like to show the headers, you can also specify header=True in the sheet method."
},
{
"code": null,
"e": 4591,
"s": 4365,
"text": "When the data is in the spreadsheet, we can use it just like the other regular software such as Excel and Google Sheets. I won’t demonstrate the formula features such as SUM, AVG and etc. that everyone would be familiar with."
},
{
"code": null,
"e": 4834,
"s": 4591,
"text": "One of the most useful features is that you can easily export the spreadsheet into CSV. That means we can use the power of Pandas data frame to easily download and transform the data, then export to use other software to do further analytics."
},
{
"code": null,
"e": 5077,
"s": 4834,
"text": "Another one I believe that is quite useful is plotting the data using matplotlib by clicks. For example, if we want to plot the daily new cases, just simply select the “new cases” column and right-click on it as shown in the screenshot below."
},
{
"code": null,
"e": 5153,
"s": 5077,
"text": "Then, on the bottom right corner, you can find the plot in the “Plots” tab."
},
{
"code": null,
"e": 5274,
"s": 5153,
"text": "In fact, Grid studio has done this plot by auto-generating code. Here is the code that is generated for the above chart."
},
{
"code": null,
"e": 5315,
"s": 5274,
"text": "data = sheet(\"B1:B106\")data.plot()show()"
},
{
"code": null,
"e": 5408,
"s": 5315,
"text": "So, we can add some annotations if necessary. For example, we can add a title to this chart:"
},
{
"code": null,
"e": 5472,
"s": 5408,
"text": "data = sheet(\"B1:B106\")data.plot(title='Daily New Cases')show()"
},
{
"code": null,
"e": 5660,
"s": 5472,
"text": "Similarly, we can plot the 4 columns separately using the same procedures. The following 3 more charts were generated by simple clicks and adding titles which took me 30 seconds in total!"
},
{
"code": null,
"e": 5830,
"s": 5660,
"text": "It is clear that using Grid Studio to perform some simple data analysis would be very quick and convenient. Thanks to Rick Lamers who is the author for his amazing idea."
},
{
"code": null,
"e": 6074,
"s": 5830,
"text": "While I really like the idea of this application that combines spreadsheet and Python, I have to say that it is still far away from mature. At least some limitations and potential improvements need to be resolved and implemented in my opinion:"
},
{
"code": null,
"e": 6715,
"s": 6074,
"text": "Should support all the Pandas data typesShould implement more features of spreadsheets that most similar applications would have such as dragging to fillThere are some bugs in the spreadsheet that need to be fixed, for example, the loaded data seems stuck in the memory that might not be able to be deleted from the spreadsheet.Suggestion: it would be great if we can bind the sheet with a Pandas data frame. That is, when you modify the sheet, the data frame is updated, and vice versa.Suggestion: it would be great if the Python stdout output can be converted to iPython style with [1]: line number, which will make debugging much easier."
},
{
"code": null,
"e": 6756,
"s": 6715,
"text": "Should support all the Pandas data types"
},
{
"code": null,
"e": 6870,
"s": 6756,
"text": "Should implement more features of spreadsheets that most similar applications would have such as dragging to fill"
},
{
"code": null,
"e": 7046,
"s": 6870,
"text": "There are some bugs in the spreadsheet that need to be fixed, for example, the loaded data seems stuck in the memory that might not be able to be deleted from the spreadsheet."
},
{
"code": null,
"e": 7206,
"s": 7046,
"text": "Suggestion: it would be great if we can bind the sheet with a Pandas data frame. That is, when you modify the sheet, the data frame is updated, and vice versa."
},
{
"code": null,
"e": 7360,
"s": 7206,
"text": "Suggestion: it would be great if the Python stdout output can be converted to iPython style with [1]: line number, which will make debugging much easier."
},
{
"code": null,
"e": 7371,
"s": 7360,
"text": "medium.com"
}
] |
Check if all array elements are distinct - GeeksforGeeks | 16 Jun, 2021
Given an array, check whether all elements in an array are distinct or not.Examples:
Input : 1, 3, 2, 4
Output : Yes
Input : "Geeks", "for", "Geeks"
Output : No
Input : "All", "Not", "Equal"
Output : Yes
One simple solution is to use two nested loops. For every element, check if it repeats or not. If any element repeats, return false. If no element repeats, return false.An efficient solution is to Hashing. We put all array elements in a HashSet. If size of HashSet remains same as array size, then we return true.
C++
Java
Python3
C#
Javascript
// C++ program to check if all array// elements are distinct#include <bits/stdc++.h>using namespace std; bool areDistinct(vector<int> arr){ int n = arr.size(); // Put all array elements in a map unordered_set<int> s; for (int i = 0; i < n; i++) { s.insert(arr[i]); } // If all elements are distinct, size of // set should be same array. return (s.size() == arr.size());} // Driver codeint main(){ std::vector<int> arr = { 1, 2, 3, 2 }; if (areDistinct(arr)) { cout << "All Elements are Distinct"; } else { cout << "Not all Elements are Distinct"; } return 0;}
// Java program to check if all array elements are// distinct or not.import java.util.Arrays;import java.util.HashSet;import java.util.Set; public class DistinctElements { public static boolean areDistinct(Integer arr[]) { // Put all array elements in a HashSet Set<Integer> s = new HashSet<Integer>(Arrays.asList(arr)); // If all elements are distinct, size of // HashSet should be same array. return (s.size() == arr.length); } // Driver code public static void main(String[] args) { Integer[] arr = { 1, 2, 3, 2 }; if (areDistinct(arr)) System.out.println("All Elements are Distinct"); else System.out.println("Not all Elements are Distinct"); }}
# Python3 program to check if all array# elements are distinctdef areDistinct(arr) : n = len(arr) # Put all array elements in a map s = set() for i in range(0, n): s.add(arr[i]) # If all elements are distinct, # size of set should be same array. return (len(s) == len(arr)) # Driver codearr = [ 1, 2, 3, 2 ] if (areDistinct(arr)): print("All Elements are Distinct") else : print("Not all Elements are Distinct") # This code is contributed by ihritik
// C# program to check if all array elements are// distinct or not.using System;using System.Collections.Generic; public class DistinctElements{ public static bool areDistinct(int []arr) { // Put all array elements in a HashSet HashSet<int> s = new HashSet<int>(arr); // If all elements are distinct, size of // HashSet should be same array. return (s.Count == arr.Length); } // Driver code public static void Main(String[] args) { int[] arr = { 1, 2, 3, 2 }; if (areDistinct(arr)) Console.WriteLine("All Elements are Distinct"); else Console.WriteLine("Not all Elements are Distinct"); }} // This code has been contributed by 29AjayKumar
<script>// Javascript program to check if all array// elements are distinctfunction areDistinct(arr){ let n = arr.length; // Put all array elements in a map let s = new Set(); for (let i = 0; i < n; i++) { s.add(arr[i]); } // If all elements are distinct, size of // set should be same array. return (s.size == arr.length);} // Driver code let arr = [ 1, 2, 3, 2 ]; if (areDistinct(arr)) { document.write("All Elements are Distinct"); } else { document.write("Not all Elements are Distinct"); } // This code is contributed// by _saurabh_jaiswal</script>
Not all Elements are Distinct
Subhashni Singh
29AjayKumar
ihritik
_saurabh_jaiswal
java-hashset
Arrays
Hash
Java Programs
Arrays
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Trapping Rain Water
Program to find sum of elements in a given array
Reversal algorithm for array rotation
Window Sliding Technique
Find duplicates in O(n) time and O(1) extra space | Set 1
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Hashing | Set 3 (Open Addressing)
Count pairs with given sum
Hashing | Set 2 (Separate Chaining) | [
{
"code": null,
"e": 24741,
"s": 24713,
"text": "\n16 Jun, 2021"
},
{
"code": null,
"e": 24828,
"s": 24741,
"text": "Given an array, check whether all elements in an array are distinct or not.Examples: "
},
{
"code": null,
"e": 24949,
"s": 24828,
"text": "Input : 1, 3, 2, 4\nOutput : Yes\n\nInput : \"Geeks\", \"for\", \"Geeks\"\nOutput : No\n\nInput : \"All\", \"Not\", \"Equal\"\nOutput : Yes"
},
{
"code": null,
"e": 25266,
"s": 24951,
"text": "One simple solution is to use two nested loops. For every element, check if it repeats or not. If any element repeats, return false. If no element repeats, return false.An efficient solution is to Hashing. We put all array elements in a HashSet. If size of HashSet remains same as array size, then we return true. "
},
{
"code": null,
"e": 25270,
"s": 25266,
"text": "C++"
},
{
"code": null,
"e": 25275,
"s": 25270,
"text": "Java"
},
{
"code": null,
"e": 25283,
"s": 25275,
"text": "Python3"
},
{
"code": null,
"e": 25286,
"s": 25283,
"text": "C#"
},
{
"code": null,
"e": 25297,
"s": 25286,
"text": "Javascript"
},
{
"code": "// C++ program to check if all array// elements are distinct#include <bits/stdc++.h>using namespace std; bool areDistinct(vector<int> arr){ int n = arr.size(); // Put all array elements in a map unordered_set<int> s; for (int i = 0; i < n; i++) { s.insert(arr[i]); } // If all elements are distinct, size of // set should be same array. return (s.size() == arr.size());} // Driver codeint main(){ std::vector<int> arr = { 1, 2, 3, 2 }; if (areDistinct(arr)) { cout << \"All Elements are Distinct\"; } else { cout << \"Not all Elements are Distinct\"; } return 0;}",
"e": 25924,
"s": 25297,
"text": null
},
{
"code": "// Java program to check if all array elements are// distinct or not.import java.util.Arrays;import java.util.HashSet;import java.util.Set; public class DistinctElements { public static boolean areDistinct(Integer arr[]) { // Put all array elements in a HashSet Set<Integer> s = new HashSet<Integer>(Arrays.asList(arr)); // If all elements are distinct, size of // HashSet should be same array. return (s.size() == arr.length); } // Driver code public static void main(String[] args) { Integer[] arr = { 1, 2, 3, 2 }; if (areDistinct(arr)) System.out.println(\"All Elements are Distinct\"); else System.out.println(\"Not all Elements are Distinct\"); }}",
"e": 26685,
"s": 25924,
"text": null
},
{
"code": "# Python3 program to check if all array# elements are distinctdef areDistinct(arr) : n = len(arr) # Put all array elements in a map s = set() for i in range(0, n): s.add(arr[i]) # If all elements are distinct, # size of set should be same array. return (len(s) == len(arr)) # Driver codearr = [ 1, 2, 3, 2 ] if (areDistinct(arr)): print(\"All Elements are Distinct\") else : print(\"Not all Elements are Distinct\") # This code is contributed by ihritik",
"e": 27176,
"s": 26685,
"text": null
},
{
"code": "// C# program to check if all array elements are// distinct or not.using System;using System.Collections.Generic; public class DistinctElements{ public static bool areDistinct(int []arr) { // Put all array elements in a HashSet HashSet<int> s = new HashSet<int>(arr); // If all elements are distinct, size of // HashSet should be same array. return (s.Count == arr.Length); } // Driver code public static void Main(String[] args) { int[] arr = { 1, 2, 3, 2 }; if (areDistinct(arr)) Console.WriteLine(\"All Elements are Distinct\"); else Console.WriteLine(\"Not all Elements are Distinct\"); }} // This code has been contributed by 29AjayKumar",
"e": 27916,
"s": 27176,
"text": null
},
{
"code": "<script>// Javascript program to check if all array// elements are distinctfunction areDistinct(arr){ let n = arr.length; // Put all array elements in a map let s = new Set(); for (let i = 0; i < n; i++) { s.add(arr[i]); } // If all elements are distinct, size of // set should be same array. return (s.size == arr.length);} // Driver code let arr = [ 1, 2, 3, 2 ]; if (areDistinct(arr)) { document.write(\"All Elements are Distinct\"); } else { document.write(\"Not all Elements are Distinct\"); } // This code is contributed// by _saurabh_jaiswal</script>",
"e": 28533,
"s": 27916,
"text": null
},
{
"code": null,
"e": 28563,
"s": 28533,
"text": "Not all Elements are Distinct"
},
{
"code": null,
"e": 28581,
"s": 28565,
"text": "Subhashni Singh"
},
{
"code": null,
"e": 28593,
"s": 28581,
"text": "29AjayKumar"
},
{
"code": null,
"e": 28601,
"s": 28593,
"text": "ihritik"
},
{
"code": null,
"e": 28618,
"s": 28601,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 28631,
"s": 28618,
"text": "java-hashset"
},
{
"code": null,
"e": 28638,
"s": 28631,
"text": "Arrays"
},
{
"code": null,
"e": 28643,
"s": 28638,
"text": "Hash"
},
{
"code": null,
"e": 28657,
"s": 28643,
"text": "Java Programs"
},
{
"code": null,
"e": 28664,
"s": 28657,
"text": "Arrays"
},
{
"code": null,
"e": 28669,
"s": 28664,
"text": "Hash"
},
{
"code": null,
"e": 28767,
"s": 28669,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28776,
"s": 28767,
"text": "Comments"
},
{
"code": null,
"e": 28789,
"s": 28776,
"text": "Old Comments"
},
{
"code": null,
"e": 28809,
"s": 28789,
"text": "Trapping Rain Water"
},
{
"code": null,
"e": 28858,
"s": 28809,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 28896,
"s": 28858,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 28921,
"s": 28896,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 28979,
"s": 28921,
"text": "Find duplicates in O(n) time and O(1) extra space | Set 1"
},
{
"code": null,
"e": 29015,
"s": 28979,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 29046,
"s": 29015,
"text": "Hashing | Set 1 (Introduction)"
},
{
"code": null,
"e": 29080,
"s": 29046,
"text": "Hashing | Set 3 (Open Addressing)"
},
{
"code": null,
"e": 29107,
"s": 29080,
"text": "Count pairs with given sum"
}
] |
Bayesian method (1). The prior distribution | by Xichu Zhang | Towards Data Science | It is easy to find a huge amount of good articles on the introduction of Bayesian statistics. However, most of them introduce only what Bayesian statistics is and how does Bayesian inference work and not many mathematical details are involved. In addition, it is a fun and challenging area to explore.
Therefore, I am planning to make a series of articles to share more about the theory of Bayesian statistics, which will include the selection of the prior, the loss function in the Bayesian inference and the relation between Bayesian statistics and some frequentists approaches. In this post, the prior distribution used in Bayesian statistics will be introduced. Why do we need to learn this? Because picking a prior distribution is one first steps we need to use Bayesian inference. And knowing more about them helps with choosing.
Here we start with a brief overview of how Bayesian statistics works and some notations we will use later are also introduced here. In Bayesian statistics, we assume a prior probability distribution and then update the prior using the data we have. This updating gives us the posterior probability distribution. We denote the posterior probability as π(θ|x) (π might seem to be very annoying since it’s also a very common constant in math, but in this context, π reminds us that the distribution is related to the parameter of the population distribution), and it is calculated as
where Θ is the space (here, by “space”, we mean a “sample space”) of all the possible parameters values and π(x|θ) is the likelihood — the conditional probability that given the true parameter value being θ, output x is observed. Since θ∈Θ is the parameter related to the prior distribution, instead of the distribution of the population, we can θ the hyperparameter. And like always, we use the bold font (x) to denote a vector. The denominator is also known as the evidence, which is a normalizing factor (a constant) to make the posterior probability π(θ|x) be a probability distribution (sum up to one). This is very easy to verify
And the normalizing factor can be ignored in inference, we can see this in some pieces of literature, such as [1], since leaving out the constant doesn’t change the shape of the curve.
Then the prior probability can be written in the form
Once we have the posterior distribution, which is the distribution of the parameter (keep this in mind), we can calculate the predictive distribution. It is a conditional probability, which is the probability distribution of observing y, given data x. It is calculated as
where the red part is the probability density function of the new observation, given the parameter θ. Equation 1.3 might seem a bit messy at first, but after a close look, we can see that it’s in fact calculated using the law of total probability (which is as simple as a weighted average) — it is the integration of the product of the probability distribution of Y given the parameter value θ and the probability of the parameter taking value θ given data x.
The prior is sometimes described as the “belief” about the data. [2] This means that we choose the prior according to our knowledge of the data. Of course, it’s not completely a subjective matter as the word “belief” might suggest.
Note that the distribution of the parameter can be unbounded, which means that the probability densities of it are nonnegative, but their sum or integral is infinite. We call this kind of distribution of the parameter improper prior distribution.
According to Wikipedia, an informative prior expresses specific, definite information about a variable. Usually, it is avoided at all costs, but if prior information is available, the informative priors are an appropriate way of introducing the information into the model. [7]
When we don’t know much about our data and the distribution of the parameter, it makes sense to choose a so-called “vague prior”, which reflects minimal knowledge. Therefore, we need a prior distribution with no population base, which makes it difficult to construct, and plays a minimal role in the posterior distribution. Such prior density is called noninformative prior, or diffuse prior. And some people rather think that the prior distribution always contains some information. Sometimes improper priors are used to represent such vague prior. Later we will see examples of this.
A related term is weakly informative prior, which contains partial information, which means it’s enough to give the posterior distribution reasonable bounds, but doesn’t fully capture one’s scientific knowledge about the parameter. [3]
A very interesting property of the prior is conjugacy, which means that the posterior distribution has the same parametric form as the prior distribution. We can see that this kind of prior is strongly related to the posterior, thus we say that it contains strong prior knowledge. [5] The benefit of conjugate priors is obvious — the posterior distribution will be a known distribution.
Uniform prior
Uniform prior
The most intuitive and easiest prior is a uniform prior distribution if the value of the parameter is bounded. This prior is noninformative (sometimes it’s also called “a low information prior” [2]), it assumes that all the parameters in the parameter space Θ are equally likely. For example, if we want to use Bernoulli distribution to model the data (as in the famous example — coin tossing), the parameter p is a probability, which falls in the interval [0, 1]. In this case, the prior probability becomes π(θ) = 1, for θ in [0, 1].
2. Haldane prior
Minimal knowledge doesn’t necessarily have to mean that all the parameters are equally likely. A lot of other noninformative priors are also possible. Another example of the noninformative prior is Haldane prior, which is proposed by J. B. S. Haldane for the estimation of rare events. The Haldane prior is actually the beta distribution with parameter α=0, β=0. Therefore the Haldane prior is
where B(α, β) is the beta function. As a reminder, the Beta function looks like this:
which can be also written in terms of the gamma function
Note that Beta(0,0) is not defined, but we can consider what it approximates to at point (0,0), which is shown in the following graph
The posterior distribution π(θ|x) is proportional to θ−1(1-θ)−1 (recall that the Bayesian theorem can be written in the form Equation 1.2), which means
This prior gives the most weight to θ=1 and θ=0. This can be made clear using the example from [5]: consider the scenario that we are observing whether an unknown compound will dissolve in water. At first, we are completely ignorant of the result. Therefore, after observing that a small sample dissolves, we immediately assume that all the samples will do so; if it doesn’t, we assume that no sample can dissolve.
3. Conjugate prior — beta distribution
A third example is the beta distribution, it is a conjugate prior of the binomial distribution. And note that, since the Bernoulli distribution is a special case of the binomial distribution (the same as B(1, 1)), Beta distribution is also a conjugate prior of the Bernoulli distribution. It is a typical example of conjugate prior (it has appeared on Wikipedia, [3] and ).
Here we will show why the beta distribution is conjugate to the binomial distribution. Firstly recall that the probability mass function of the binomial distribution is
where n is the total number of trials, k is the number of successes and p is the probability of success. Therefore, the likelihood is
Referring to what we have seen in the section of basics, the likelihood is denoted as π(x|θ), where x is the observed value, so x = (k, n-k). This means
the parameters of the binomial distribution become the observed value and the “parameter” in this likelihood is the hyperparameter.
Then we choose beta distribution to be the prior. What we want to do is to show that the posterior distribution is the same type as the prior distribution.
The posterior distribution is derived as follows
we can see that the posterior distribution is again beta distribution.
4. Jeffreys Prior
The Jeffreys prior is a non-informative prior defined in terms of the square root of the determinant of the Fisher information matrix.
The Fisher information and Fisher information matrix were introduced here, but for convenience, we also mention it again here. Originally, the Fisher information is defined as the variance of the score
where the lower index θ means that the expected value is with regard to θ, and the matrix form is written as
but under some certain conditions (the density function f being second-order differentiable and regularity conditions, a good summary of which can be found here).
Equation 2.14 is the formula for the single variable case (when there are multiple parameters, we use the matrix form). Let’s try to calculate the Jeffreys prior of a Bernoulli trial, which is a single variable case. There are reasons why we use this distribution for demonstration, which we will see later. We know that the probability distribution of the Bernoulli distribution is
Now we need to calculate the Fisher information of the density function (Equation 2.15)
Since the parameter is just one-dimensional (single-variable), the Fisher information is just a number, which is also the determinant, and we have the prior distribution
Look at Equation 1.27 carefully and we will find out that the Jeffreys prior is similar to the Haldane prior. But unlike Haldane prior, Jeffreys prior is proper. The plot of Equation 1.27 looks as follows
It is also related to the Beta distribution since Equation 1.27 equals Beta(1/2, 1/2).
Summary
This post is mainly about the prior distribution in Bayesian inference. In the beginning, the basics of Bayesian inference are briefly introduced. Then we look at the types of the prior distributions and then some common prior distributions are selected.
References:
[1] Lee, T. S., & Mumford, D. (2003). Hierarchical Bayesian inference in the visual cortex. JOSA A, 20(7), 1434–1448.
[2] Surya, Tokdar, Choosing a prior distribution, accessed 4 December 2021.
[3] Gelman, A., Carlin, J. B., Stern, H. S., & Rubin, D. B. (1995). Bayesian data analysis. Chapman and Hall/CRC.
[4] Etz, A., & Wagenmakers, E. J. (2017). JBS Haldane’s contribution to the Bayes factor hypothesis test. Statistical Science, 313–329.
[5] Jaynes, E. T. (1968). Prior probabilities. IEEE Transactions on systems science and cybernetics, 4(3), 227–241.
[6] Stanford, J. L., & Vardeman, S. B. (1994). Statistical methods for physical science (Vol. 28). Academic Press.
[7] Golchi, S. (2016, October). Informative priors and Bayesian computation. In 2016 IEEE international conference on data science and advanced analytics (DSAA) (pp. 782–789). IEEE.
[8] Nicenboim, B., Schad, D. J., & Vasishth, S. (2021). An introduction to bayesian data analysis for cognitive science.
[9] Jeremy Orloff and Jonathan Bloom, Conjugate priors: Beta and normal, accessed 11 December 2021.
[10] The prior distribution, accessed 1 January 2022.
Further reading:
For more about probability theory:
towardsdatascience.com
For more about the comparison between Bayesian and frequentist approaches:
medium.com
Supplement:
code used to generate Figure 0.1
x.v <- seq(0, 1, by=0.01)n <- length(x.v)m <- matrix(nrow=n, ncol=1)for (i in seq(0.1, 5, 0.3)) { y.v <- dbeta(x.v, shape1=i, shape2=15) m <- cbind(y.v, m)}for (j in seq(0.1, 5, 0.3)) { y.v <- dbeta(x.v, shape1=15, shape2=j) m <- cbind(y.v, m)}for (i in seq(0.1, 10, 1)) { y.v <- dbeta(x.v, shape1=i, shape2=i) m <- cbind(y.v, m)}n.c <- ncol(m)n.c# remove last column with Nasm <- m[,-n.c]par(mar = c(3, 4, 1, 2))matplot(x=x.v, y=m, type="l", col="black", ylim=c(0,11), xlab="", ylab="PDF") | [
{
"code": null,
"e": 467,
"s": 165,
"text": "It is easy to find a huge amount of good articles on the introduction of Bayesian statistics. However, most of them introduce only what Bayesian statistics is and how does Bayesian inference work and not many mathematical details are involved. In addition, it is a fun and challenging area to explore."
},
{
"code": null,
"e": 1001,
"s": 467,
"text": "Therefore, I am planning to make a series of articles to share more about the theory of Bayesian statistics, which will include the selection of the prior, the loss function in the Bayesian inference and the relation between Bayesian statistics and some frequentists approaches. In this post, the prior distribution used in Bayesian statistics will be introduced. Why do we need to learn this? Because picking a prior distribution is one first steps we need to use Bayesian inference. And knowing more about them helps with choosing."
},
{
"code": null,
"e": 1582,
"s": 1001,
"text": "Here we start with a brief overview of how Bayesian statistics works and some notations we will use later are also introduced here. In Bayesian statistics, we assume a prior probability distribution and then update the prior using the data we have. This updating gives us the posterior probability distribution. We denote the posterior probability as π(θ|x) (π might seem to be very annoying since it’s also a very common constant in math, but in this context, π reminds us that the distribution is related to the parameter of the population distribution), and it is calculated as"
},
{
"code": null,
"e": 2218,
"s": 1582,
"text": "where Θ is the space (here, by “space”, we mean a “sample space”) of all the possible parameters values and π(x|θ) is the likelihood — the conditional probability that given the true parameter value being θ, output x is observed. Since θ∈Θ is the parameter related to the prior distribution, instead of the distribution of the population, we can θ the hyperparameter. And like always, we use the bold font (x) to denote a vector. The denominator is also known as the evidence, which is a normalizing factor (a constant) to make the posterior probability π(θ|x) be a probability distribution (sum up to one). This is very easy to verify"
},
{
"code": null,
"e": 2403,
"s": 2218,
"text": "And the normalizing factor can be ignored in inference, we can see this in some pieces of literature, such as [1], since leaving out the constant doesn’t change the shape of the curve."
},
{
"code": null,
"e": 2457,
"s": 2403,
"text": "Then the prior probability can be written in the form"
},
{
"code": null,
"e": 2729,
"s": 2457,
"text": "Once we have the posterior distribution, which is the distribution of the parameter (keep this in mind), we can calculate the predictive distribution. It is a conditional probability, which is the probability distribution of observing y, given data x. It is calculated as"
},
{
"code": null,
"e": 3189,
"s": 2729,
"text": "where the red part is the probability density function of the new observation, given the parameter θ. Equation 1.3 might seem a bit messy at first, but after a close look, we can see that it’s in fact calculated using the law of total probability (which is as simple as a weighted average) — it is the integration of the product of the probability distribution of Y given the parameter value θ and the probability of the parameter taking value θ given data x."
},
{
"code": null,
"e": 3421,
"s": 3189,
"text": "The prior is sometimes described as the “belief” about the data. [2] This means that we choose the prior according to our knowledge of the data. Of course, it’s not completely a subjective matter as the word “belief” might suggest."
},
{
"code": null,
"e": 3668,
"s": 3421,
"text": "Note that the distribution of the parameter can be unbounded, which means that the probability densities of it are nonnegative, but their sum or integral is infinite. We call this kind of distribution of the parameter improper prior distribution."
},
{
"code": null,
"e": 3945,
"s": 3668,
"text": "According to Wikipedia, an informative prior expresses specific, definite information about a variable. Usually, it is avoided at all costs, but if prior information is available, the informative priors are an appropriate way of introducing the information into the model. [7]"
},
{
"code": null,
"e": 4531,
"s": 3945,
"text": "When we don’t know much about our data and the distribution of the parameter, it makes sense to choose a so-called “vague prior”, which reflects minimal knowledge. Therefore, we need a prior distribution with no population base, which makes it difficult to construct, and plays a minimal role in the posterior distribution. Such prior density is called noninformative prior, or diffuse prior. And some people rather think that the prior distribution always contains some information. Sometimes improper priors are used to represent such vague prior. Later we will see examples of this."
},
{
"code": null,
"e": 4767,
"s": 4531,
"text": "A related term is weakly informative prior, which contains partial information, which means it’s enough to give the posterior distribution reasonable bounds, but doesn’t fully capture one’s scientific knowledge about the parameter. [3]"
},
{
"code": null,
"e": 5154,
"s": 4767,
"text": "A very interesting property of the prior is conjugacy, which means that the posterior distribution has the same parametric form as the prior distribution. We can see that this kind of prior is strongly related to the posterior, thus we say that it contains strong prior knowledge. [5] The benefit of conjugate priors is obvious — the posterior distribution will be a known distribution."
},
{
"code": null,
"e": 5168,
"s": 5154,
"text": "Uniform prior"
},
{
"code": null,
"e": 5182,
"s": 5168,
"text": "Uniform prior"
},
{
"code": null,
"e": 5718,
"s": 5182,
"text": "The most intuitive and easiest prior is a uniform prior distribution if the value of the parameter is bounded. This prior is noninformative (sometimes it’s also called “a low information prior” [2]), it assumes that all the parameters in the parameter space Θ are equally likely. For example, if we want to use Bernoulli distribution to model the data (as in the famous example — coin tossing), the parameter p is a probability, which falls in the interval [0, 1]. In this case, the prior probability becomes π(θ) = 1, for θ in [0, 1]."
},
{
"code": null,
"e": 5735,
"s": 5718,
"text": "2. Haldane prior"
},
{
"code": null,
"e": 6129,
"s": 5735,
"text": "Minimal knowledge doesn’t necessarily have to mean that all the parameters are equally likely. A lot of other noninformative priors are also possible. Another example of the noninformative prior is Haldane prior, which is proposed by J. B. S. Haldane for the estimation of rare events. The Haldane prior is actually the beta distribution with parameter α=0, β=0. Therefore the Haldane prior is"
},
{
"code": null,
"e": 6215,
"s": 6129,
"text": "where B(α, β) is the beta function. As a reminder, the Beta function looks like this:"
},
{
"code": null,
"e": 6272,
"s": 6215,
"text": "which can be also written in terms of the gamma function"
},
{
"code": null,
"e": 6406,
"s": 6272,
"text": "Note that Beta(0,0) is not defined, but we can consider what it approximates to at point (0,0), which is shown in the following graph"
},
{
"code": null,
"e": 6558,
"s": 6406,
"text": "The posterior distribution π(θ|x) is proportional to θ−1(1-θ)−1 (recall that the Bayesian theorem can be written in the form Equation 1.2), which means"
},
{
"code": null,
"e": 6973,
"s": 6558,
"text": "This prior gives the most weight to θ=1 and θ=0. This can be made clear using the example from [5]: consider the scenario that we are observing whether an unknown compound will dissolve in water. At first, we are completely ignorant of the result. Therefore, after observing that a small sample dissolves, we immediately assume that all the samples will do so; if it doesn’t, we assume that no sample can dissolve."
},
{
"code": null,
"e": 7012,
"s": 6973,
"text": "3. Conjugate prior — beta distribution"
},
{
"code": null,
"e": 7386,
"s": 7012,
"text": "A third example is the beta distribution, it is a conjugate prior of the binomial distribution. And note that, since the Bernoulli distribution is a special case of the binomial distribution (the same as B(1, 1)), Beta distribution is also a conjugate prior of the Bernoulli distribution. It is a typical example of conjugate prior (it has appeared on Wikipedia, [3] and )."
},
{
"code": null,
"e": 7555,
"s": 7386,
"text": "Here we will show why the beta distribution is conjugate to the binomial distribution. Firstly recall that the probability mass function of the binomial distribution is"
},
{
"code": null,
"e": 7689,
"s": 7555,
"text": "where n is the total number of trials, k is the number of successes and p is the probability of success. Therefore, the likelihood is"
},
{
"code": null,
"e": 7842,
"s": 7689,
"text": "Referring to what we have seen in the section of basics, the likelihood is denoted as π(x|θ), where x is the observed value, so x = (k, n-k). This means"
},
{
"code": null,
"e": 7974,
"s": 7842,
"text": "the parameters of the binomial distribution become the observed value and the “parameter” in this likelihood is the hyperparameter."
},
{
"code": null,
"e": 8130,
"s": 7974,
"text": "Then we choose beta distribution to be the prior. What we want to do is to show that the posterior distribution is the same type as the prior distribution."
},
{
"code": null,
"e": 8179,
"s": 8130,
"text": "The posterior distribution is derived as follows"
},
{
"code": null,
"e": 8250,
"s": 8179,
"text": "we can see that the posterior distribution is again beta distribution."
},
{
"code": null,
"e": 8268,
"s": 8250,
"text": "4. Jeffreys Prior"
},
{
"code": null,
"e": 8403,
"s": 8268,
"text": "The Jeffreys prior is a non-informative prior defined in terms of the square root of the determinant of the Fisher information matrix."
},
{
"code": null,
"e": 8605,
"s": 8403,
"text": "The Fisher information and Fisher information matrix were introduced here, but for convenience, we also mention it again here. Originally, the Fisher information is defined as the variance of the score"
},
{
"code": null,
"e": 8714,
"s": 8605,
"text": "where the lower index θ means that the expected value is with regard to θ, and the matrix form is written as"
},
{
"code": null,
"e": 8877,
"s": 8714,
"text": "but under some certain conditions (the density function f being second-order differentiable and regularity conditions, a good summary of which can be found here)."
},
{
"code": null,
"e": 9260,
"s": 8877,
"text": "Equation 2.14 is the formula for the single variable case (when there are multiple parameters, we use the matrix form). Let’s try to calculate the Jeffreys prior of a Bernoulli trial, which is a single variable case. There are reasons why we use this distribution for demonstration, which we will see later. We know that the probability distribution of the Bernoulli distribution is"
},
{
"code": null,
"e": 9348,
"s": 9260,
"text": "Now we need to calculate the Fisher information of the density function (Equation 2.15)"
},
{
"code": null,
"e": 9518,
"s": 9348,
"text": "Since the parameter is just one-dimensional (single-variable), the Fisher information is just a number, which is also the determinant, and we have the prior distribution"
},
{
"code": null,
"e": 9723,
"s": 9518,
"text": "Look at Equation 1.27 carefully and we will find out that the Jeffreys prior is similar to the Haldane prior. But unlike Haldane prior, Jeffreys prior is proper. The plot of Equation 1.27 looks as follows"
},
{
"code": null,
"e": 9810,
"s": 9723,
"text": "It is also related to the Beta distribution since Equation 1.27 equals Beta(1/2, 1/2)."
},
{
"code": null,
"e": 9818,
"s": 9810,
"text": "Summary"
},
{
"code": null,
"e": 10073,
"s": 9818,
"text": "This post is mainly about the prior distribution in Bayesian inference. In the beginning, the basics of Bayesian inference are briefly introduced. Then we look at the types of the prior distributions and then some common prior distributions are selected."
},
{
"code": null,
"e": 10085,
"s": 10073,
"text": "References:"
},
{
"code": null,
"e": 10203,
"s": 10085,
"text": "[1] Lee, T. S., & Mumford, D. (2003). Hierarchical Bayesian inference in the visual cortex. JOSA A, 20(7), 1434–1448."
},
{
"code": null,
"e": 10279,
"s": 10203,
"text": "[2] Surya, Tokdar, Choosing a prior distribution, accessed 4 December 2021."
},
{
"code": null,
"e": 10393,
"s": 10279,
"text": "[3] Gelman, A., Carlin, J. B., Stern, H. S., & Rubin, D. B. (1995). Bayesian data analysis. Chapman and Hall/CRC."
},
{
"code": null,
"e": 10529,
"s": 10393,
"text": "[4] Etz, A., & Wagenmakers, E. J. (2017). JBS Haldane’s contribution to the Bayes factor hypothesis test. Statistical Science, 313–329."
},
{
"code": null,
"e": 10645,
"s": 10529,
"text": "[5] Jaynes, E. T. (1968). Prior probabilities. IEEE Transactions on systems science and cybernetics, 4(3), 227–241."
},
{
"code": null,
"e": 10760,
"s": 10645,
"text": "[6] Stanford, J. L., & Vardeman, S. B. (1994). Statistical methods for physical science (Vol. 28). Academic Press."
},
{
"code": null,
"e": 10942,
"s": 10760,
"text": "[7] Golchi, S. (2016, October). Informative priors and Bayesian computation. In 2016 IEEE international conference on data science and advanced analytics (DSAA) (pp. 782–789). IEEE."
},
{
"code": null,
"e": 11063,
"s": 10942,
"text": "[8] Nicenboim, B., Schad, D. J., & Vasishth, S. (2021). An introduction to bayesian data analysis for cognitive science."
},
{
"code": null,
"e": 11163,
"s": 11063,
"text": "[9] Jeremy Orloff and Jonathan Bloom, Conjugate priors: Beta and normal, accessed 11 December 2021."
},
{
"code": null,
"e": 11217,
"s": 11163,
"text": "[10] The prior distribution, accessed 1 January 2022."
},
{
"code": null,
"e": 11234,
"s": 11217,
"text": "Further reading:"
},
{
"code": null,
"e": 11269,
"s": 11234,
"text": "For more about probability theory:"
},
{
"code": null,
"e": 11292,
"s": 11269,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 11367,
"s": 11292,
"text": "For more about the comparison between Bayesian and frequentist approaches:"
},
{
"code": null,
"e": 11378,
"s": 11367,
"text": "medium.com"
},
{
"code": null,
"e": 11390,
"s": 11378,
"text": "Supplement:"
},
{
"code": null,
"e": 11423,
"s": 11390,
"text": "code used to generate Figure 0.1"
}
] |
Import and Merge Multiple CSV Files in R - GeeksforGeeks | 17 Jun, 2021
In this article, we will be looking at the approach to merge multiple CSV files in the R programming language.
dplyr: This is a structure of data manipulation that provides a uniform set of verbs, helping to resolve the most frequent data manipulation hurdles.
plyr: plyr is an R package that makes it simple to split data apart, do stuff to it, and mash it back together.
readr: This provides a fast and friendly way to read rectangular data (like ‘csv’, ‘tsv’, and ‘fwf’).
list.files() function: This function produces a character vector of the names of files or directories in the named directory.
Syntax: list.files(path = “.”, pattern = NULL, all.files = FALSE,full.names = FALSE, recursive = FALSE, ignore.case = FALSE, include.dirs = FALSE, no.. = FALSE)
lapply() function: This function returns a list of the same length as X, each element of which is the result of applying FUN to the corresponding element of X.
Syntax: lapply(X, FUN, ...)
bind_rows() function: This function is an efficient implementation of the common pattern of do.call(rbind, dfs) or do.call(cbind, dfs) for binding many data frames into one.
Syntax:
bind_rows(..., .id = NULL)
Parameter:
...: Data frames to combine.
.id: Data frame identifier.
To merge multiple CSV files, the user needs to install and import dplyr,plyr, and readr packages in the R console to call the functions which are list.files(), lapply(), and bind_rows() from these packages and pass the required parameters to these functions to merge the given multiple CSV files to a single data frame in the R programming language.
Data in Use:
Example:
R
library("dplyr") library("plyr") library("readr") gfg_data <- list.files(path = "C:/Users/Geetansh Sahni/Documents/R/Data", pattern = "*.csv", full.names = TRUE) %>% lapply(read_csv) %>% bind_rows gfg_data
Output:
Picked
R-CSV
R Language
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
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
R - if statement
How to filter R dataframe by multiple conditions?
Plot mean and standard deviation using ggplot2 in R
How to import an Excel File into R ? | [
{
"code": null,
"e": 26487,
"s": 26459,
"text": "\n17 Jun, 2021"
},
{
"code": null,
"e": 26598,
"s": 26487,
"text": "In this article, we will be looking at the approach to merge multiple CSV files in the R programming language."
},
{
"code": null,
"e": 26748,
"s": 26598,
"text": "dplyr: This is a structure of data manipulation that provides a uniform set of verbs, helping to resolve the most frequent data manipulation hurdles."
},
{
"code": null,
"e": 26860,
"s": 26748,
"text": "plyr: plyr is an R package that makes it simple to split data apart, do stuff to it, and mash it back together."
},
{
"code": null,
"e": 26962,
"s": 26860,
"text": "readr: This provides a fast and friendly way to read rectangular data (like ‘csv’, ‘tsv’, and ‘fwf’)."
},
{
"code": null,
"e": 27088,
"s": 26962,
"text": "list.files() function: This function produces a character vector of the names of files or directories in the named directory."
},
{
"code": null,
"e": 27249,
"s": 27088,
"text": "Syntax: list.files(path = “.”, pattern = NULL, all.files = FALSE,full.names = FALSE, recursive = FALSE, ignore.case = FALSE, include.dirs = FALSE, no.. = FALSE)"
},
{
"code": null,
"e": 27409,
"s": 27249,
"text": "lapply() function: This function returns a list of the same length as X, each element of which is the result of applying FUN to the corresponding element of X."
},
{
"code": null,
"e": 27437,
"s": 27409,
"text": "Syntax: lapply(X, FUN, ...)"
},
{
"code": null,
"e": 27611,
"s": 27437,
"text": "bind_rows() function: This function is an efficient implementation of the common pattern of do.call(rbind, dfs) or do.call(cbind, dfs) for binding many data frames into one."
},
{
"code": null,
"e": 27619,
"s": 27611,
"text": "Syntax:"
},
{
"code": null,
"e": 27646,
"s": 27619,
"text": "bind_rows(..., .id = NULL)"
},
{
"code": null,
"e": 27657,
"s": 27646,
"text": "Parameter:"
},
{
"code": null,
"e": 27686,
"s": 27657,
"text": "...: Data frames to combine."
},
{
"code": null,
"e": 27714,
"s": 27686,
"text": ".id: Data frame identifier."
},
{
"code": null,
"e": 28064,
"s": 27714,
"text": "To merge multiple CSV files, the user needs to install and import dplyr,plyr, and readr packages in the R console to call the functions which are list.files(), lapply(), and bind_rows() from these packages and pass the required parameters to these functions to merge the given multiple CSV files to a single data frame in the R programming language."
},
{
"code": null,
"e": 28077,
"s": 28064,
"text": "Data in Use:"
},
{
"code": null,
"e": 28086,
"s": 28077,
"text": "Example:"
},
{
"code": null,
"e": 28088,
"s": 28086,
"text": "R"
},
{
"code": "library(\"dplyr\") library(\"plyr\") library(\"readr\") gfg_data <- list.files(path = \"C:/Users/Geetansh Sahni/Documents/R/Data\", pattern = \"*.csv\", full.names = TRUE) %>% lapply(read_csv) %>% bind_rows gfg_data",
"e": 28509,
"s": 28088,
"text": null
},
{
"code": null,
"e": 28518,
"s": 28509,
"text": " Output:"
},
{
"code": null,
"e": 28525,
"s": 28518,
"text": "Picked"
},
{
"code": null,
"e": 28531,
"s": 28525,
"text": "R-CSV"
},
{
"code": null,
"e": 28542,
"s": 28531,
"text": "R Language"
},
{
"code": null,
"e": 28640,
"s": 28542,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28692,
"s": 28640,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 28727,
"s": 28692,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 28765,
"s": 28727,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 28823,
"s": 28765,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 28866,
"s": 28823,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 28915,
"s": 28866,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 28932,
"s": 28915,
"text": "R - if statement"
},
{
"code": null,
"e": 28982,
"s": 28932,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 29034,
"s": 28982,
"text": "Plot mean and standard deviation using ggplot2 in R"
}
] |
Machine Learning Models as Micro Services in Docker | by Sambit Mahapatra | Towards Data Science | One of the biggest underrated challenges in machine learning development is the deployment of the trained models in production that too in a scalable way. One joke on it I have read is “Most common way, Machine Learning gets deployed today is powerpoint slides :)”.
Docker is a containerization platform which packages an application & all its dependencies into a container.
Activating this container results in the application being active.
Docker is used when you have a lot of services which work in an isolated manner and serve as a data provider to a web application. Depending on the load, the instances can be spun off on demand on the basis of the rules set up.
Production deployment of regular software applications is hard. If that software is a Machine Learning pipeline, it’s worse! And in today’s scenario, you can’t get away from machine learning, as it is the most competitive edge you can get in the business. In production, a Machine Learning powered application would be using several models for several purposes. Some major practical challenges in Machine Learning models deployment that can be handled through docker are:
Ununiform environments across models.
Ununiform environments across models.
There can be cases where for one model you need LANG_LEVEL set to ‘c’ while for another LANG_LEVEL should be ‘en_us.UTF-8’. Put different models in different containers so that isolated environments for different models will be obtained.
2. Ununiform library requirements across models.
You have developed a text summarizer using tensorflow 1.10. Now we want to have a sentiment analysis using transfer learning which is supported by tensorflow2.0(suppose). Putting them in different containers will not break the app.
Another major use case is, you develop ML models in python. But the application you want to make in Go language (for some technical advantages), then exposing the ml model through docker to the app will solve it.
3. Ununiform resource requirements across models.
You have a very complex object detection model which requires GPU, and you have 5 different neural networks for other purposes which are good to run on CPU. Then on deploying the models in containers, you get the flexibility of assigning resources as per requirement.
4. Ununiform traffics across models.
Suppose you have a question identifier model and answer generation mode.w The former is called frequently while the latter one is not called that frequent. Then you need more instances of question identifier than answer generator. This can be easily handled by docker.
Another scenario is, at 10 am you have 10000 requests for your model whereas at 8 pm it is only 100. So you need to spin off more serving instances as per your requirements, which is easier in docker.
5. Scaling at model level
Suppose you have a statistical model which serves 100000 requests per second, whereas a deep learning model capable of serving 100 requests per second. Then for 10000 requests, you need to scale up only the deep learning model. This can be done by docker.
Now let’s see how to create a container of a deep learning model. Here the model I have built is a question topic identifier on the question classifier dataset available at http://cogcomp.org/Data/QA/QC/. Google’s Universal Sentence Encoder is used for word embedding.
While creating a container for a model, the workflow normally has to be followed is:
Build and train the model.Create an API of the model. (Here we have put it in a flask API).Create the requirements file containing all the required libraries.Create the docker file with necessary environment setup and start-up operations.Build the docker image.Now run the container and dance as you are done :)
Build and train the model.
Create an API of the model. (Here we have put it in a flask API).
Create the requirements file containing all the required libraries.
Create the docker file with necessary environment setup and start-up operations.
Build the docker image.
Now run the container and dance as you are done :)
github.com
Build and train the model.
To build and train the model, a basic workflow is to get the data, do the cleaning and processing of the data and then fed the data to the model architecture to get a trained model.
For example, I have built a question intent classifier model on the TREC dataset available at http://cogcomp.org/Data/QA/QC/. The training data has 6 intents with the number of instances of each is as follows:
Counter({'DESC': 1162, 'ENTY': 1250, 'ABBR': 86, 'HUM': 1223, 'NUM': 896, 'LOC': 835})
The model creation can be seen at https://github.com/sambit9238/QuestionTopicAnalysis/blob/master/question_topic.ipynb
The processing steps followed here are:
Dealing with contractions like I‘ll, I‘ve etc.Dealing with hyperlinks, mail addresses etc.Dealing with numbers and ids.Dealing with punctuations.
Dealing with contractions like I‘ll, I‘ve etc.
Dealing with hyperlinks, mail addresses etc.
Dealing with numbers and ids.
Dealing with punctuations.
For embedding, Google's universal sentence encoder is used from tensorflow-hub.
The model architecture followed is a neural network with 2 hidden layers each with 256 neurons. To avoid overfitting, L2 regularization is used.
Layer (type) Output Shape Param # =================================================================input_1 (InputLayer) (None, 1) 0 _________________________________________________________________lambda_1 (Lambda) (None, 512) 0 _________________________________________________________________dense_1 (Dense) (None, 256) 131328 _________________________________________________________________dense_2 (Dense) (None, 256) 65792 _________________________________________________________________dense_3 (Dense) (None, 6) 1542 =================================================================Total params: 198,662Trainable params: 198,662Non-trainable params: 0_________________________________
The model is stored in .h5 file for reuse. Label encoder is stored in the pickle file for reuse.
Create an API of the model. (Here we have put it in a flask API).
The stored model is put in Flask api so that it can be used in production (https://github.com/sambit9238/QuestionTopicAnalysis/blob/master/docker_question_topic/app.py.)
The API expects a list of texts, as multiple sentences will come while using in real time. It goes through cleaning and processing to fed for prediction. The predicted results are scaled to represent the confidence percentage of each intent. The scaled results are then sent in JSON format.
For example,
input: [ “What is your salary?”]
output: {‘ABBR’: 0.0012655753, ‘DESC’: 0.0079659065, ‘ENTY’: 0.011016952, ‘HUM’: 0.028764706, ‘LOC’: 0.013653239, ‘NUM’: 0.93733364}
That means the model is 93% confident that the answer should be a number for this question.
Create the requirements file containing all the required libraries.
To create a Docker image to serve our API, we need to create a requirement file with all the used libraries along with their versions.
Create the Dockerfile with necessary environment setup and start-up operations.
A Dockerfile is a text document that contains all the commands a user could call on the command line to assemble an image.
For our example, the pre-built python-3.6 image is taken as a base image. Then the pre-trained Universal Sentence Encoder model files have been downloaded followed by the installation of required libraries. The 5000 port of docker is exposed, this is the port where flask app will run as it is in the default configuration.
Build the docker image. and run the container
Now we have the Dockerfile, flask API and trained model files in a directory. Hence we need to create the docker image out of it. The command for that can be:
docker build -t question_topic .#the last option is location of the directory. Since I am in the directory so '.' is put, which represents current directory in unix.
Now the docker image is created, we need to run the image in a container docker run -p 8888:5000 --name question_topic question_topic
It will make the created docker image run. The port 5000 in the docker is mapped to 8888 port of host machine. Hence, the API will receive and response requests at port 8888. If you want to run the docker in the background and detach it from the command prompt (which will be the case in real time), run it with ‘-d’ option.
To check the outputs of the docker let’s send a post request using curl.
input:
To supply the input, curl — request POST — url http://0.0.0.0:8888/predict_topic — header ‘content-type: application/json’ — data ‘{“rawtext_list”:[“Where do you work now?”, “What is your salary?”]}’
output:
{
“input”: “[‘Where do you work now?’, ‘What is your salary?’]”,
“output”: “[ {‘ABBR’: 0.0033528977, ‘DESC’: 0.0013749895, ‘ENTY’: 0.0068545835, ‘HUM’: 0.7283039, ‘LOC’: 0.25804028, ‘NUM’: 0.0020733867},
{‘ABBR’: 0.0012655753, ‘DESC’: 0.0079659065, ‘ENTY’: 0.011016952, ‘HUM’: 0.028764706, ‘LOC’: 0.013653239, ‘NUM’: 0.93733364} ]”
}
It seems the docker is running fine :)
Notes:
The mentioned example is not production ready. But it can be production ready by following few things like:
At Model level, more processing and model hyper-parameters’ tuning can be made to make model better.At API level, initialization of the session and variables need not to be done at each request. It can be done once at the app startup by drastically reducing the response time of API.At Docker level, The Docker file is not optimized, hence docker image can be bigger than required in terms of size.
At Model level, more processing and model hyper-parameters’ tuning can be made to make model better.
At API level, initialization of the session and variables need not to be done at each request. It can be done once at the app startup by drastically reducing the response time of API.
At Docker level, The Docker file is not optimized, hence docker image can be bigger than required in terms of size. | [
{
"code": null,
"e": 438,
"s": 172,
"text": "One of the biggest underrated challenges in machine learning development is the deployment of the trained models in production that too in a scalable way. One joke on it I have read is “Most common way, Machine Learning gets deployed today is powerpoint slides :)”."
},
{
"code": null,
"e": 547,
"s": 438,
"text": "Docker is a containerization platform which packages an application & all its dependencies into a container."
},
{
"code": null,
"e": 614,
"s": 547,
"text": "Activating this container results in the application being active."
},
{
"code": null,
"e": 842,
"s": 614,
"text": "Docker is used when you have a lot of services which work in an isolated manner and serve as a data provider to a web application. Depending on the load, the instances can be spun off on demand on the basis of the rules set up."
},
{
"code": null,
"e": 1314,
"s": 842,
"text": "Production deployment of regular software applications is hard. If that software is a Machine Learning pipeline, it’s worse! And in today’s scenario, you can’t get away from machine learning, as it is the most competitive edge you can get in the business. In production, a Machine Learning powered application would be using several models for several purposes. Some major practical challenges in Machine Learning models deployment that can be handled through docker are:"
},
{
"code": null,
"e": 1352,
"s": 1314,
"text": "Ununiform environments across models."
},
{
"code": null,
"e": 1390,
"s": 1352,
"text": "Ununiform environments across models."
},
{
"code": null,
"e": 1628,
"s": 1390,
"text": "There can be cases where for one model you need LANG_LEVEL set to ‘c’ while for another LANG_LEVEL should be ‘en_us.UTF-8’. Put different models in different containers so that isolated environments for different models will be obtained."
},
{
"code": null,
"e": 1677,
"s": 1628,
"text": "2. Ununiform library requirements across models."
},
{
"code": null,
"e": 1909,
"s": 1677,
"text": "You have developed a text summarizer using tensorflow 1.10. Now we want to have a sentiment analysis using transfer learning which is supported by tensorflow2.0(suppose). Putting them in different containers will not break the app."
},
{
"code": null,
"e": 2122,
"s": 1909,
"text": "Another major use case is, you develop ML models in python. But the application you want to make in Go language (for some technical advantages), then exposing the ml model through docker to the app will solve it."
},
{
"code": null,
"e": 2172,
"s": 2122,
"text": "3. Ununiform resource requirements across models."
},
{
"code": null,
"e": 2440,
"s": 2172,
"text": "You have a very complex object detection model which requires GPU, and you have 5 different neural networks for other purposes which are good to run on CPU. Then on deploying the models in containers, you get the flexibility of assigning resources as per requirement."
},
{
"code": null,
"e": 2477,
"s": 2440,
"text": "4. Ununiform traffics across models."
},
{
"code": null,
"e": 2746,
"s": 2477,
"text": "Suppose you have a question identifier model and answer generation mode.w The former is called frequently while the latter one is not called that frequent. Then you need more instances of question identifier than answer generator. This can be easily handled by docker."
},
{
"code": null,
"e": 2947,
"s": 2746,
"text": "Another scenario is, at 10 am you have 10000 requests for your model whereas at 8 pm it is only 100. So you need to spin off more serving instances as per your requirements, which is easier in docker."
},
{
"code": null,
"e": 2973,
"s": 2947,
"text": "5. Scaling at model level"
},
{
"code": null,
"e": 3229,
"s": 2973,
"text": "Suppose you have a statistical model which serves 100000 requests per second, whereas a deep learning model capable of serving 100 requests per second. Then for 10000 requests, you need to scale up only the deep learning model. This can be done by docker."
},
{
"code": null,
"e": 3498,
"s": 3229,
"text": "Now let’s see how to create a container of a deep learning model. Here the model I have built is a question topic identifier on the question classifier dataset available at http://cogcomp.org/Data/QA/QC/. Google’s Universal Sentence Encoder is used for word embedding."
},
{
"code": null,
"e": 3583,
"s": 3498,
"text": "While creating a container for a model, the workflow normally has to be followed is:"
},
{
"code": null,
"e": 3895,
"s": 3583,
"text": "Build and train the model.Create an API of the model. (Here we have put it in a flask API).Create the requirements file containing all the required libraries.Create the docker file with necessary environment setup and start-up operations.Build the docker image.Now run the container and dance as you are done :)"
},
{
"code": null,
"e": 3922,
"s": 3895,
"text": "Build and train the model."
},
{
"code": null,
"e": 3988,
"s": 3922,
"text": "Create an API of the model. (Here we have put it in a flask API)."
},
{
"code": null,
"e": 4056,
"s": 3988,
"text": "Create the requirements file containing all the required libraries."
},
{
"code": null,
"e": 4137,
"s": 4056,
"text": "Create the docker file with necessary environment setup and start-up operations."
},
{
"code": null,
"e": 4161,
"s": 4137,
"text": "Build the docker image."
},
{
"code": null,
"e": 4212,
"s": 4161,
"text": "Now run the container and dance as you are done :)"
},
{
"code": null,
"e": 4223,
"s": 4212,
"text": "github.com"
},
{
"code": null,
"e": 4250,
"s": 4223,
"text": "Build and train the model."
},
{
"code": null,
"e": 4432,
"s": 4250,
"text": "To build and train the model, a basic workflow is to get the data, do the cleaning and processing of the data and then fed the data to the model architecture to get a trained model."
},
{
"code": null,
"e": 4642,
"s": 4432,
"text": "For example, I have built a question intent classifier model on the TREC dataset available at http://cogcomp.org/Data/QA/QC/. The training data has 6 intents with the number of instances of each is as follows:"
},
{
"code": null,
"e": 4769,
"s": 4642,
"text": "Counter({'DESC': 1162, 'ENTY': 1250, 'ABBR': 86, 'HUM': 1223, 'NUM': 896, 'LOC': 835})"
},
{
"code": null,
"e": 4888,
"s": 4769,
"text": "The model creation can be seen at https://github.com/sambit9238/QuestionTopicAnalysis/blob/master/question_topic.ipynb"
},
{
"code": null,
"e": 4928,
"s": 4888,
"text": "The processing steps followed here are:"
},
{
"code": null,
"e": 5074,
"s": 4928,
"text": "Dealing with contractions like I‘ll, I‘ve etc.Dealing with hyperlinks, mail addresses etc.Dealing with numbers and ids.Dealing with punctuations."
},
{
"code": null,
"e": 5121,
"s": 5074,
"text": "Dealing with contractions like I‘ll, I‘ve etc."
},
{
"code": null,
"e": 5166,
"s": 5121,
"text": "Dealing with hyperlinks, mail addresses etc."
},
{
"code": null,
"e": 5196,
"s": 5166,
"text": "Dealing with numbers and ids."
},
{
"code": null,
"e": 5223,
"s": 5196,
"text": "Dealing with punctuations."
},
{
"code": null,
"e": 5303,
"s": 5223,
"text": "For embedding, Google's universal sentence encoder is used from tensorflow-hub."
},
{
"code": null,
"e": 5448,
"s": 5303,
"text": "The model architecture followed is a neural network with 2 hidden layers each with 256 neurons. To avoid overfitting, L2 regularization is used."
},
{
"code": null,
"e": 6331,
"s": 5448,
"text": "Layer (type) Output Shape Param # =================================================================input_1 (InputLayer) (None, 1) 0 _________________________________________________________________lambda_1 (Lambda) (None, 512) 0 _________________________________________________________________dense_1 (Dense) (None, 256) 131328 _________________________________________________________________dense_2 (Dense) (None, 256) 65792 _________________________________________________________________dense_3 (Dense) (None, 6) 1542 =================================================================Total params: 198,662Trainable params: 198,662Non-trainable params: 0_________________________________"
},
{
"code": null,
"e": 6428,
"s": 6331,
"text": "The model is stored in .h5 file for reuse. Label encoder is stored in the pickle file for reuse."
},
{
"code": null,
"e": 6494,
"s": 6428,
"text": "Create an API of the model. (Here we have put it in a flask API)."
},
{
"code": null,
"e": 6664,
"s": 6494,
"text": "The stored model is put in Flask api so that it can be used in production (https://github.com/sambit9238/QuestionTopicAnalysis/blob/master/docker_question_topic/app.py.)"
},
{
"code": null,
"e": 6955,
"s": 6664,
"text": "The API expects a list of texts, as multiple sentences will come while using in real time. It goes through cleaning and processing to fed for prediction. The predicted results are scaled to represent the confidence percentage of each intent. The scaled results are then sent in JSON format."
},
{
"code": null,
"e": 6968,
"s": 6955,
"text": "For example,"
},
{
"code": null,
"e": 7001,
"s": 6968,
"text": "input: [ “What is your salary?”]"
},
{
"code": null,
"e": 7134,
"s": 7001,
"text": "output: {‘ABBR’: 0.0012655753, ‘DESC’: 0.0079659065, ‘ENTY’: 0.011016952, ‘HUM’: 0.028764706, ‘LOC’: 0.013653239, ‘NUM’: 0.93733364}"
},
{
"code": null,
"e": 7226,
"s": 7134,
"text": "That means the model is 93% confident that the answer should be a number for this question."
},
{
"code": null,
"e": 7294,
"s": 7226,
"text": "Create the requirements file containing all the required libraries."
},
{
"code": null,
"e": 7429,
"s": 7294,
"text": "To create a Docker image to serve our API, we need to create a requirement file with all the used libraries along with their versions."
},
{
"code": null,
"e": 7509,
"s": 7429,
"text": "Create the Dockerfile with necessary environment setup and start-up operations."
},
{
"code": null,
"e": 7632,
"s": 7509,
"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": 7956,
"s": 7632,
"text": "For our example, the pre-built python-3.6 image is taken as a base image. Then the pre-trained Universal Sentence Encoder model files have been downloaded followed by the installation of required libraries. The 5000 port of docker is exposed, this is the port where flask app will run as it is in the default configuration."
},
{
"code": null,
"e": 8002,
"s": 7956,
"text": "Build the docker image. and run the container"
},
{
"code": null,
"e": 8161,
"s": 8002,
"text": "Now we have the Dockerfile, flask API and trained model files in a directory. Hence we need to create the docker image out of it. The command for that can be:"
},
{
"code": null,
"e": 8327,
"s": 8161,
"text": "docker build -t question_topic .#the last option is location of the directory. Since I am in the directory so '.' is put, which represents current directory in unix."
},
{
"code": null,
"e": 8461,
"s": 8327,
"text": "Now the docker image is created, we need to run the image in a container docker run -p 8888:5000 --name question_topic question_topic"
},
{
"code": null,
"e": 8786,
"s": 8461,
"text": "It will make the created docker image run. The port 5000 in the docker is mapped to 8888 port of host machine. Hence, the API will receive and response requests at port 8888. If you want to run the docker in the background and detach it from the command prompt (which will be the case in real time), run it with ‘-d’ option."
},
{
"code": null,
"e": 8859,
"s": 8786,
"text": "To check the outputs of the docker let’s send a post request using curl."
},
{
"code": null,
"e": 8866,
"s": 8859,
"text": "input:"
},
{
"code": null,
"e": 9066,
"s": 8866,
"text": "To supply the input, curl — request POST — url http://0.0.0.0:8888/predict_topic — header ‘content-type: application/json’ — data ‘{“rawtext_list”:[“Where do you work now?”, “What is your salary?”]}’"
},
{
"code": null,
"e": 9074,
"s": 9066,
"text": "output:"
},
{
"code": null,
"e": 9076,
"s": 9074,
"text": "{"
},
{
"code": null,
"e": 9139,
"s": 9076,
"text": "“input”: “[‘Where do you work now?’, ‘What is your salary?’]”,"
},
{
"code": null,
"e": 9278,
"s": 9139,
"text": "“output”: “[ {‘ABBR’: 0.0033528977, ‘DESC’: 0.0013749895, ‘ENTY’: 0.0068545835, ‘HUM’: 0.7283039, ‘LOC’: 0.25804028, ‘NUM’: 0.0020733867},"
},
{
"code": null,
"e": 9406,
"s": 9278,
"text": "{‘ABBR’: 0.0012655753, ‘DESC’: 0.0079659065, ‘ENTY’: 0.011016952, ‘HUM’: 0.028764706, ‘LOC’: 0.013653239, ‘NUM’: 0.93733364} ]”"
},
{
"code": null,
"e": 9408,
"s": 9406,
"text": "}"
},
{
"code": null,
"e": 9447,
"s": 9408,
"text": "It seems the docker is running fine :)"
},
{
"code": null,
"e": 9454,
"s": 9447,
"text": "Notes:"
},
{
"code": null,
"e": 9562,
"s": 9454,
"text": "The mentioned example is not production ready. But it can be production ready by following few things like:"
},
{
"code": null,
"e": 9961,
"s": 9562,
"text": "At Model level, more processing and model hyper-parameters’ tuning can be made to make model better.At API level, initialization of the session and variables need not to be done at each request. It can be done once at the app startup by drastically reducing the response time of API.At Docker level, The Docker file is not optimized, hence docker image can be bigger than required in terms of size."
},
{
"code": null,
"e": 10062,
"s": 9961,
"text": "At Model level, more processing and model hyper-parameters’ tuning can be made to make model better."
},
{
"code": null,
"e": 10246,
"s": 10062,
"text": "At API level, initialization of the session and variables need not to be done at each request. It can be done once at the app startup by drastically reducing the response time of API."
}
] |
Exploratory Data Analysis in R for beginners (Part 2) | by Joe Tran | Towards Data Science | In my previous article, ‘Exploratory Data Analysis in R for beginners (Part 1)’, I have introduced a basic step-by-step approach from data importing to cleaning and visualization. Here is a quick summary of Part 1:
Import data appropriately with fileEncoding and na.strings arguments. I showed how it is different from the normal way of importing csv file with read.csv().
Some basic cleaning the data with ‘tidyverse’ package
Visualization with Boxplot, Barplot, Correlation plot in ‘ggplot2’ package
Those are the basic steps in performing simple EDA. However, to make our plots, charts and graphs more informative and of course visually appealing, we need to make one step further. What do I mean by that? Let’s find it out!
Doing EDA is not merely about plotting graphs. It is about making informative graphs. In this article, you would expect to find the following tricks:
How to play around with the dataset to get the best version for each type of analysis? There is no one-size-fits-all dataset. Each analysis and visualization have different purposes, hence there comes different data structures.Change the order of the legends in the plotLet R identify the outliers and label them on the plotCombine graphs with the use of ‘gridExtra’ package
How to play around with the dataset to get the best version for each type of analysis? There is no one-size-fits-all dataset. Each analysis and visualization have different purposes, hence there comes different data structures.
Change the order of the legends in the plot
Let R identify the outliers and label them on the plot
Combine graphs with the use of ‘gridExtra’ package
By the end of this article, you would be able to generate the following plots:
Let’s get started, folks!!!!
Let’s quickly look at the types of datasets that we created in Part 1 of this series.
view(df)
View(df2)
View(df4) ## df3 combines with df2 to get df4
Please refer back to my previous article for a detailed explanation on how to manipulate the original dataset to get these various versions.
Great! Let’s start our new visual plots now
First of all, we want to achieve this kind of boxplot
In order to get this, we must have a data frame where the rows are the countries and 4 columns, namely, Country names, % difference in Maths, Reading and Science. Now refer back to all the dataframes we created earlier, we can see that df has all of these requirements. Hence we will select relevant columns from df and name it as df5
df5 = df[,c(1,11,12,13)]boxplot(df5$Maths.Diff, df5$Reading.Diff, df5$Science.Diff, main = 'Are Males better than Females?', names = c('Maths','Reading','Science'), col = 'green' )
Done! Following this code, you should be able to get the plot as above.
Now we want to move on to the next level. This is the plot that we want to get
Notice the following differences:
The subtitleThe titles of the axesThe layout and color of outliers.The caption
The subtitle
The titles of the axes
The layout and color of outliers.
The caption
Thankfully, the ‘ggplot2’ package has everything we need. It is just a matter of whether we can find these arguments and functions in the ‘ggplot2’ package. But before we even move on to what arguments and functions to use, we need to determine what kind of data frame/structure the dataset should be. By looking at this plot, we can see that the data frame must have 1 column of 3 categories (Maths, Reading and Science), 1 column of numeric results for the % difference in performance in each subject and of course, 1 column for the country name. Hence 3 columns in total.
Now we have df5 that looks like this
How would we transform this into a data frame described above? Remember a trick I introduced in Part 1 of this series, the magical function is pivot_longer(). Now, lets do it:
df6 = df5 %>% pivot_longer(c(2,3,4))names(df6) = c('Country','Test Diff','Result')View(df6)
new = rep(c('Maths', 'Reading', 'Science'),68) #to create a new column indicating 'Maths', 'Reading' and 'Science'df6 = cbind(df6, new)names(df6) = c('Country','Test Diff','Result', 'Test') #change column namesView(df6)
The column ‘Test Diff’ is now redundant so you can choose to delete that, simply use the code below. (This step is not compulsory)
df6$'Test Diff' = NULL
Here, I will not delete it.
Great! Now that we have the data set in the right structure ready for visualization, let’s use ggplot now
To get the title, subtitle, caption, use labs(title = ‘ ...’ , y = ‘ ...’, x = ‘ ...’, caption = ‘ ...’, subtitle = ‘ ...’)If the title or caption is long, use ‘ .... \n ...’ to break it down into 2 lines.To indicate outliers, inside geom_boxplot()
To get the title, subtitle, caption, use labs(title = ‘ ...’ , y = ‘ ...’, x = ‘ ...’, caption = ‘ ...’, subtitle = ‘ ...’)
If the title or caption is long, use ‘ .... \n ...’ to break it down into 2 lines.
To indicate outliers, inside geom_boxplot()
geom_boxplot(alpha = 0.7, outlier.colour='blue', #color of outlier outlier.shape=19, #shape of outlier outlier.size=3, #size of outlier width = 0.6, color = "#1F3552", fill = "#4271AE" )
Combine everything together:
ggplot(data = df6, aes(x=Test,y=Result, fill=Test)) + geom_boxplot(alpha = 0.7, outlier.colour='blue', outlier.shape=19, outlier.size=3, width = 0.6, color = "#1F3552", fill = "#4271AE" )+ theme_grey() + labs(title = 'Did males perform better than females?', y='% Difference from FEMALES',x='', caption = 'Positive % Difference means Males performed \n better than Females and vice versa', subtitle = 'Based on PISA Score 2015')
Is this good enough? The answer is NO: Caption, titles and subtitles are too small, the proportion and size of the plot is not as good as the plot we introduced at the start of this section.
We can do a better job.
To adjust the size and so on, use theme () function
theme(axis.text=element_text(size=20), plot.title = element_text(size = 20, face = "bold"), plot.subtitle = element_text(size = 10), plot.caption = element_text(color = "Red", face = "italic", size = 13) )
Here, don’t ask me how I got those numbers to put. This is trial and error. You can just simply try out any numbers until you get the perfect size and position.
Let’s now combine everything together
ggplot(data = df6, aes(x=Test,y=Result, fill=Test)) + geom_boxplot(alpha = 0.7, outlier.colour='blue', outlier.shape=19, outlier.size=3, width = 0.6, color = "#1F3552", fill = "#4271AE" )+ theme_grey() + labs(title = 'Did males perform better than females?', y='% Difference from FEMALES',x='', caption = 'Positive % Difference means Males performed \n better than Females and vice versa', subtitle = 'Based on PISA Score 2015') + theme(axis.text=element_text(size=20), plot.title = element_text(size = 20, face = "bold"), plot.subtitle = element_text(size = 10), plot.caption = element_text(color = "Red", face = "italic", size = 13))
The plot looks much better now. You can stop here. However, I would like to introduce a way to rearrange the order of variables to get a decreasing trend. Simply use
scale_x_discrete(limits=c("Maths","Science","Reading"))
Hence, combining everything
ggplot(data = df6, aes(x=Test,y=Result, fill=Test)) + geom_boxplot(alpha = 0.7, outlier.colour='blue', outlier.shape=19, outlier.size=3, width = 0.6, color = "#1F3552", fill = "#4271AE" )+scale_x_discrete(limits=c("Maths","Science","Reading"))+ theme_grey() + labs(title = 'Did males perform better than females?', y='% Difference from FEMALES',x='', caption = 'Positive % Difference means Males performed \n better than Females and vice versa', subtitle = 'Based on PISA Score 2015') + theme(axis.text=element_text(size=20), plot.title = element_text(size = 20, face = "bold"), plot.subtitle = element_text(size = 10), plot.caption = element_text(color = "Red", face = "italic", size = 13))
Awesome!! Now the plot looks really informative. However, better data analysts would produce something even more informative like the following:
df6$Test = factor(df6$Test, levels = c("Maths","Science","Reading")) # To change order of legend
Let’s define the outlier. This part requires a bit of Statistics knowledge. I would recommend you to read Michael Galarnyk’s article here. He explains the concepts pretty well.
is_outlier <- function(x) { return(x < quantile(x, 0.25) - 1.5 * IQR(x) | x > quantile(x, 0.75) + 1.5 * IQR(x))} # define a function to detect outliersstr(df6)
Notice that the columns ‘Country’ and ‘Test’ are factors. First let’s change it to characters.
df6$Country = as.character(df6$Country)df7 <- df6 %>% group_by(as.character(Test)) %>% mutate(is_outlier=ifelse(is_outlier(Result), Country, as.numeric(NA)))### What we are doing now is that we are creating a new data frame with the last column 'is_outlier' indicating whether the data point is an outlier or notView(df7)
As you can see, the last column of the data frame shows that Jordan is an outlier. Now, at the ‘Country’ column, we want to make sure that only the outliers are labeled, the rest should be put as ‘NA’. This will be helpful for us later when we code the visualization plot.
df7$Country[which(is.na(df7$is_outlier))] <- as.numeric(NA)View(df7)
Now, let’s plot the graph. The same code as above. However we need to add in geom_text () to label the outliers
ggplot(data = df7, aes(x=Test,y=Result, fill=Test)) + geom_boxplot(alpha = 0.7, outlier.colour='red', outlier.shape=19, outlier.size=3, width = 0.6)+ geom_text(aes(label = Country), na.rm = TRUE, hjust = -0.2)+ theme_grey() + labs(title = 'Did males perform better than females?', y='% Difference from FEMALES',x='', caption = 'Positive % Difference means Males performed \n better than Females and vice versa', subtitle = 'Based on PISA Score 2015') + theme(axis.text=element_text(size=20), legend.text = element_text(size = 16), legend.title = element_text(size = 16), legend.position = 'right', aspect.ratio = 1.4, plot.title = element_text(size = 20, face = "bold"), plot.subtitle = element_text(size = 10), plot.caption = element_text(color = "Red", face = "italic", size = 13) )
For each of the plot in the combined plot above, we have gone through how to create it in Part 1 of this series. Here is the recap:
plot1 = ggplot(data=df, aes(x=reorder(Country.Name, Maths.Diff), y=Maths.Diff)) + geom_bar(stat = "identity", aes(fill=Maths.Diff)) + coord_flip() + theme_light() + geom_hline(yintercept = mean(df$Maths.Diff), size=1, color="black") + labs(x="", y="Maths")+ scale_fill_gradient(name="% Difference Level", low = "red", high = "green")+ theme(legend.position = "none")plot2 = ggplot(data=df, aes(x=reorder(Country.Name, Reading.Diff), y=Reading.Diff)) + geom_bar(stat = "identity", aes(fill=Reading.Diff)) + coord_flip() + theme_light() + geom_hline(yintercept = mean(df$Reading.Diff), size=1, color="black") + labs(x="", y="Reading")+ scale_fill_gradient(name="% Difference Level", low = "red", high = "green") + theme(legend.position = "none")plot3 = ggplot(data=df, aes(x=reorder(Country.Name, Science.Diff), y=Science.Diff)) + geom_bar(stat = "identity", aes(fill=Science.Diff)) + coord_flip() + theme_light() + geom_hline(yintercept = mean(df$Science.Diff), size=1, color="black") + labs(x="", y="Science")+ scale_fill_gradient(name="% Difference", low = "red", high = "green") + theme(legend.position = "none")
To combine them all together, use ‘gridExtra’ package.
install.packages('gridExtra')library(gridExtra)grid.arrange(plot1, plot2,plot3, nrow = 1, top = 'Are Males better than Females?', bottom = '% Difference from Females' )#nrow=1 means all the plots are placed in one row
That is it! Again, I hope you guys enjoyed and picked up something from this article. Of course, this guide is not exhaustive, and there are a lot of other techniques we can use to do EDA. However, I believe this guide will more or less give you some ideas of how to do improve from a simple plot to a more complicated and informative plot with R.
If you have any questions, feel free to put them down in the comment section below. Once again, thank you for your read. Have a great day and happy programming!!! | [
{
"code": null,
"e": 387,
"s": 172,
"text": "In my previous article, ‘Exploratory Data Analysis in R for beginners (Part 1)’, I have introduced a basic step-by-step approach from data importing to cleaning and visualization. Here is a quick summary of Part 1:"
},
{
"code": null,
"e": 545,
"s": 387,
"text": "Import data appropriately with fileEncoding and na.strings arguments. I showed how it is different from the normal way of importing csv file with read.csv()."
},
{
"code": null,
"e": 599,
"s": 545,
"text": "Some basic cleaning the data with ‘tidyverse’ package"
},
{
"code": null,
"e": 674,
"s": 599,
"text": "Visualization with Boxplot, Barplot, Correlation plot in ‘ggplot2’ package"
},
{
"code": null,
"e": 900,
"s": 674,
"text": "Those are the basic steps in performing simple EDA. However, to make our plots, charts and graphs more informative and of course visually appealing, we need to make one step further. What do I mean by that? Let’s find it out!"
},
{
"code": null,
"e": 1050,
"s": 900,
"text": "Doing EDA is not merely about plotting graphs. It is about making informative graphs. In this article, you would expect to find the following tricks:"
},
{
"code": null,
"e": 1425,
"s": 1050,
"text": "How to play around with the dataset to get the best version for each type of analysis? There is no one-size-fits-all dataset. Each analysis and visualization have different purposes, hence there comes different data structures.Change the order of the legends in the plotLet R identify the outliers and label them on the plotCombine graphs with the use of ‘gridExtra’ package"
},
{
"code": null,
"e": 1653,
"s": 1425,
"text": "How to play around with the dataset to get the best version for each type of analysis? There is no one-size-fits-all dataset. Each analysis and visualization have different purposes, hence there comes different data structures."
},
{
"code": null,
"e": 1697,
"s": 1653,
"text": "Change the order of the legends in the plot"
},
{
"code": null,
"e": 1752,
"s": 1697,
"text": "Let R identify the outliers and label them on the plot"
},
{
"code": null,
"e": 1803,
"s": 1752,
"text": "Combine graphs with the use of ‘gridExtra’ package"
},
{
"code": null,
"e": 1882,
"s": 1803,
"text": "By the end of this article, you would be able to generate the following plots:"
},
{
"code": null,
"e": 1911,
"s": 1882,
"text": "Let’s get started, folks!!!!"
},
{
"code": null,
"e": 1997,
"s": 1911,
"text": "Let’s quickly look at the types of datasets that we created in Part 1 of this series."
},
{
"code": null,
"e": 2006,
"s": 1997,
"text": "view(df)"
},
{
"code": null,
"e": 2016,
"s": 2006,
"text": "View(df2)"
},
{
"code": null,
"e": 2062,
"s": 2016,
"text": "View(df4) ## df3 combines with df2 to get df4"
},
{
"code": null,
"e": 2203,
"s": 2062,
"text": "Please refer back to my previous article for a detailed explanation on how to manipulate the original dataset to get these various versions."
},
{
"code": null,
"e": 2247,
"s": 2203,
"text": "Great! Let’s start our new visual plots now"
},
{
"code": null,
"e": 2301,
"s": 2247,
"text": "First of all, we want to achieve this kind of boxplot"
},
{
"code": null,
"e": 2636,
"s": 2301,
"text": "In order to get this, we must have a data frame where the rows are the countries and 4 columns, namely, Country names, % difference in Maths, Reading and Science. Now refer back to all the dataframes we created earlier, we can see that df has all of these requirements. Hence we will select relevant columns from df and name it as df5"
},
{
"code": null,
"e": 2845,
"s": 2636,
"text": "df5 = df[,c(1,11,12,13)]boxplot(df5$Maths.Diff, df5$Reading.Diff, df5$Science.Diff, main = 'Are Males better than Females?', names = c('Maths','Reading','Science'), col = 'green' )"
},
{
"code": null,
"e": 2917,
"s": 2845,
"text": "Done! Following this code, you should be able to get the plot as above."
},
{
"code": null,
"e": 2996,
"s": 2917,
"text": "Now we want to move on to the next level. This is the plot that we want to get"
},
{
"code": null,
"e": 3030,
"s": 2996,
"text": "Notice the following differences:"
},
{
"code": null,
"e": 3109,
"s": 3030,
"text": "The subtitleThe titles of the axesThe layout and color of outliers.The caption"
},
{
"code": null,
"e": 3122,
"s": 3109,
"text": "The subtitle"
},
{
"code": null,
"e": 3145,
"s": 3122,
"text": "The titles of the axes"
},
{
"code": null,
"e": 3179,
"s": 3145,
"text": "The layout and color of outliers."
},
{
"code": null,
"e": 3191,
"s": 3179,
"text": "The caption"
},
{
"code": null,
"e": 3766,
"s": 3191,
"text": "Thankfully, the ‘ggplot2’ package has everything we need. It is just a matter of whether we can find these arguments and functions in the ‘ggplot2’ package. But before we even move on to what arguments and functions to use, we need to determine what kind of data frame/structure the dataset should be. By looking at this plot, we can see that the data frame must have 1 column of 3 categories (Maths, Reading and Science), 1 column of numeric results for the % difference in performance in each subject and of course, 1 column for the country name. Hence 3 columns in total."
},
{
"code": null,
"e": 3803,
"s": 3766,
"text": "Now we have df5 that looks like this"
},
{
"code": null,
"e": 3979,
"s": 3803,
"text": "How would we transform this into a data frame described above? Remember a trick I introduced in Part 1 of this series, the magical function is pivot_longer(). Now, lets do it:"
},
{
"code": null,
"e": 4071,
"s": 3979,
"text": "df6 = df5 %>% pivot_longer(c(2,3,4))names(df6) = c('Country','Test Diff','Result')View(df6)"
},
{
"code": null,
"e": 4295,
"s": 4071,
"text": "new = rep(c('Maths', 'Reading', 'Science'),68) #to create a new column indicating 'Maths', 'Reading' and 'Science'df6 = cbind(df6, new)names(df6) = c('Country','Test Diff','Result', 'Test') #change column namesView(df6)"
},
{
"code": null,
"e": 4426,
"s": 4295,
"text": "The column ‘Test Diff’ is now redundant so you can choose to delete that, simply use the code below. (This step is not compulsory)"
},
{
"code": null,
"e": 4449,
"s": 4426,
"text": "df6$'Test Diff' = NULL"
},
{
"code": null,
"e": 4477,
"s": 4449,
"text": "Here, I will not delete it."
},
{
"code": null,
"e": 4583,
"s": 4477,
"text": "Great! Now that we have the data set in the right structure ready for visualization, let’s use ggplot now"
},
{
"code": null,
"e": 4832,
"s": 4583,
"text": "To get the title, subtitle, caption, use labs(title = ‘ ...’ , y = ‘ ...’, x = ‘ ...’, caption = ‘ ...’, subtitle = ‘ ...’)If the title or caption is long, use ‘ .... \\n ...’ to break it down into 2 lines.To indicate outliers, inside geom_boxplot()"
},
{
"code": null,
"e": 4956,
"s": 4832,
"text": "To get the title, subtitle, caption, use labs(title = ‘ ...’ , y = ‘ ...’, x = ‘ ...’, caption = ‘ ...’, subtitle = ‘ ...’)"
},
{
"code": null,
"e": 5039,
"s": 4956,
"text": "If the title or caption is long, use ‘ .... \\n ...’ to break it down into 2 lines."
},
{
"code": null,
"e": 5083,
"s": 5039,
"text": "To indicate outliers, inside geom_boxplot()"
},
{
"code": null,
"e": 5358,
"s": 5083,
"text": "geom_boxplot(alpha = 0.7, outlier.colour='blue', #color of outlier outlier.shape=19, #shape of outlier outlier.size=3, #size of outlier width = 0.6, color = \"#1F3552\", fill = \"#4271AE\" )"
},
{
"code": null,
"e": 5387,
"s": 5358,
"text": "Combine everything together:"
},
{
"code": null,
"e": 5912,
"s": 5387,
"text": "ggplot(data = df6, aes(x=Test,y=Result, fill=Test)) + geom_boxplot(alpha = 0.7, outlier.colour='blue', outlier.shape=19, outlier.size=3, width = 0.6, color = \"#1F3552\", fill = \"#4271AE\" )+ theme_grey() + labs(title = 'Did males perform better than females?', y='% Difference from FEMALES',x='', caption = 'Positive % Difference means Males performed \\n better than Females and vice versa', subtitle = 'Based on PISA Score 2015')"
},
{
"code": null,
"e": 6103,
"s": 5912,
"text": "Is this good enough? The answer is NO: Caption, titles and subtitles are too small, the proportion and size of the plot is not as good as the plot we introduced at the start of this section."
},
{
"code": null,
"e": 6127,
"s": 6103,
"text": "We can do a better job."
},
{
"code": null,
"e": 6179,
"s": 6127,
"text": "To adjust the size and so on, use theme () function"
},
{
"code": null,
"e": 6419,
"s": 6179,
"text": "theme(axis.text=element_text(size=20), plot.title = element_text(size = 20, face = \"bold\"), plot.subtitle = element_text(size = 10), plot.caption = element_text(color = \"Red\", face = \"italic\", size = 13) )"
},
{
"code": null,
"e": 6580,
"s": 6419,
"text": "Here, don’t ask me how I got those numbers to put. This is trial and error. You can just simply try out any numbers until you get the perfect size and position."
},
{
"code": null,
"e": 6618,
"s": 6580,
"text": "Let’s now combine everything together"
},
{
"code": null,
"e": 7371,
"s": 6618,
"text": "ggplot(data = df6, aes(x=Test,y=Result, fill=Test)) + geom_boxplot(alpha = 0.7, outlier.colour='blue', outlier.shape=19, outlier.size=3, width = 0.6, color = \"#1F3552\", fill = \"#4271AE\" )+ theme_grey() + labs(title = 'Did males perform better than females?', y='% Difference from FEMALES',x='', caption = 'Positive % Difference means Males performed \\n better than Females and vice versa', subtitle = 'Based on PISA Score 2015') + theme(axis.text=element_text(size=20), plot.title = element_text(size = 20, face = \"bold\"), plot.subtitle = element_text(size = 10), plot.caption = element_text(color = \"Red\", face = \"italic\", size = 13))"
},
{
"code": null,
"e": 7537,
"s": 7371,
"text": "The plot looks much better now. You can stop here. However, I would like to introduce a way to rearrange the order of variables to get a decreasing trend. Simply use"
},
{
"code": null,
"e": 7593,
"s": 7537,
"text": "scale_x_discrete(limits=c(\"Maths\",\"Science\",\"Reading\"))"
},
{
"code": null,
"e": 7621,
"s": 7593,
"text": "Hence, combining everything"
},
{
"code": null,
"e": 8430,
"s": 7621,
"text": "ggplot(data = df6, aes(x=Test,y=Result, fill=Test)) + geom_boxplot(alpha = 0.7, outlier.colour='blue', outlier.shape=19, outlier.size=3, width = 0.6, color = \"#1F3552\", fill = \"#4271AE\" )+scale_x_discrete(limits=c(\"Maths\",\"Science\",\"Reading\"))+ theme_grey() + labs(title = 'Did males perform better than females?', y='% Difference from FEMALES',x='', caption = 'Positive % Difference means Males performed \\n better than Females and vice versa', subtitle = 'Based on PISA Score 2015') + theme(axis.text=element_text(size=20), plot.title = element_text(size = 20, face = \"bold\"), plot.subtitle = element_text(size = 10), plot.caption = element_text(color = \"Red\", face = \"italic\", size = 13))"
},
{
"code": null,
"e": 8575,
"s": 8430,
"text": "Awesome!! Now the plot looks really informative. However, better data analysts would produce something even more informative like the following:"
},
{
"code": null,
"e": 8673,
"s": 8575,
"text": "df6$Test = factor(df6$Test, levels = c(\"Maths\",\"Science\",\"Reading\")) # To change order of legend"
},
{
"code": null,
"e": 8850,
"s": 8673,
"text": "Let’s define the outlier. This part requires a bit of Statistics knowledge. I would recommend you to read Michael Galarnyk’s article here. He explains the concepts pretty well."
},
{
"code": null,
"e": 9014,
"s": 8850,
"text": "is_outlier <- function(x) { return(x < quantile(x, 0.25) - 1.5 * IQR(x) | x > quantile(x, 0.75) + 1.5 * IQR(x))} # define a function to detect outliersstr(df6)"
},
{
"code": null,
"e": 9109,
"s": 9014,
"text": "Notice that the columns ‘Country’ and ‘Test’ are factors. First let’s change it to characters."
},
{
"code": null,
"e": 9434,
"s": 9109,
"text": "df6$Country = as.character(df6$Country)df7 <- df6 %>% group_by(as.character(Test)) %>% mutate(is_outlier=ifelse(is_outlier(Result), Country, as.numeric(NA)))### What we are doing now is that we are creating a new data frame with the last column 'is_outlier' indicating whether the data point is an outlier or notView(df7)"
},
{
"code": null,
"e": 9707,
"s": 9434,
"text": "As you can see, the last column of the data frame shows that Jordan is an outlier. Now, at the ‘Country’ column, we want to make sure that only the outliers are labeled, the rest should be put as ‘NA’. This will be helpful for us later when we code the visualization plot."
},
{
"code": null,
"e": 9776,
"s": 9707,
"text": "df7$Country[which(is.na(df7$is_outlier))] <- as.numeric(NA)View(df7)"
},
{
"code": null,
"e": 9888,
"s": 9776,
"text": "Now, let’s plot the graph. The same code as above. However we need to add in geom_text () to label the outliers"
},
{
"code": null,
"e": 10819,
"s": 9888,
"text": "ggplot(data = df7, aes(x=Test,y=Result, fill=Test)) + geom_boxplot(alpha = 0.7, outlier.colour='red', outlier.shape=19, outlier.size=3, width = 0.6)+ geom_text(aes(label = Country), na.rm = TRUE, hjust = -0.2)+ theme_grey() + labs(title = 'Did males perform better than females?', y='% Difference from FEMALES',x='', caption = 'Positive % Difference means Males performed \\n better than Females and vice versa', subtitle = 'Based on PISA Score 2015') + theme(axis.text=element_text(size=20), legend.text = element_text(size = 16), legend.title = element_text(size = 16), legend.position = 'right', aspect.ratio = 1.4, plot.title = element_text(size = 20, face = \"bold\"), plot.subtitle = element_text(size = 10), plot.caption = element_text(color = \"Red\", face = \"italic\", size = 13) )"
},
{
"code": null,
"e": 10951,
"s": 10819,
"text": "For each of the plot in the combined plot above, we have gone through how to create it in Part 1 of this series. Here is the recap:"
},
{
"code": null,
"e": 12087,
"s": 10951,
"text": "plot1 = ggplot(data=df, aes(x=reorder(Country.Name, Maths.Diff), y=Maths.Diff)) + geom_bar(stat = \"identity\", aes(fill=Maths.Diff)) + coord_flip() + theme_light() + geom_hline(yintercept = mean(df$Maths.Diff), size=1, color=\"black\") + labs(x=\"\", y=\"Maths\")+ scale_fill_gradient(name=\"% Difference Level\", low = \"red\", high = \"green\")+ theme(legend.position = \"none\")plot2 = ggplot(data=df, aes(x=reorder(Country.Name, Reading.Diff), y=Reading.Diff)) + geom_bar(stat = \"identity\", aes(fill=Reading.Diff)) + coord_flip() + theme_light() + geom_hline(yintercept = mean(df$Reading.Diff), size=1, color=\"black\") + labs(x=\"\", y=\"Reading\")+ scale_fill_gradient(name=\"% Difference Level\", low = \"red\", high = \"green\") + theme(legend.position = \"none\")plot3 = ggplot(data=df, aes(x=reorder(Country.Name, Science.Diff), y=Science.Diff)) + geom_bar(stat = \"identity\", aes(fill=Science.Diff)) + coord_flip() + theme_light() + geom_hline(yintercept = mean(df$Science.Diff), size=1, color=\"black\") + labs(x=\"\", y=\"Science\")+ scale_fill_gradient(name=\"% Difference\", low = \"red\", high = \"green\") + theme(legend.position = \"none\")"
},
{
"code": null,
"e": 12142,
"s": 12087,
"text": "To combine them all together, use ‘gridExtra’ package."
},
{
"code": null,
"e": 12396,
"s": 12142,
"text": "install.packages('gridExtra')library(gridExtra)grid.arrange(plot1, plot2,plot3, nrow = 1, top = 'Are Males better than Females?', bottom = '% Difference from Females' )#nrow=1 means all the plots are placed in one row"
},
{
"code": null,
"e": 12744,
"s": 12396,
"text": "That is it! Again, I hope you guys enjoyed and picked up something from this article. Of course, this guide is not exhaustive, and there are a lot of other techniques we can use to do EDA. However, I believe this guide will more or less give you some ideas of how to do improve from a simple plot to a more complicated and informative plot with R."
}
] |
Introduction to OpenVINO. A comprehensive guide for understanding... | by Dhairya Kumar | Towards Data Science | A comprehensive guide for understanding the functioning of the OpenVINO toolkit
OpenVINO stands for Open Visual Inference and Neural Network Optimization. It is a toolkit provided by Intel to facilitate faster inference of deep learning models. It helps developers to create cost-effective and robust computer vision applications. It enables deep learning inference at the edge and supports heterogeneous execution across computer vision accelerators — CPU, GPU, Intel® MovidiusTM Neural Compute Stick, and FPGA. It supports a large number of deep learning models out of the box. You can check out this link to know more about the model zoo.
If you want to run the code sample provided at the end of this article, then make sure that you have properly downloaded and configured the OpenVINO toolkit.
software.intel.com
software.intel.com
The execution process is as follows —
We feed a pre-trained model to the Model Optimizer. It optimizes the model and converts it into its intermediate representation (.xml and .bin file).
The Inference Engine helps in the proper execution of the model on different devices. It manages the libraries required to run the code properly on different platforms.
The two main components of the OpenVINO toolkit are Model Optimizer and Inference Engine. So, we will dive into their details, to better understand their role and internal working.
Model optimizer is a cross-platform command-line tool that facilitates the transition between the training and deployment environment. It adjusts the deep learning models for optimal execution on end-point target devices.
Model Optimizer loads a model into memory, reads it, builds the internal representation of the model, optimizes it, and produces the Intermediate Representation. Intermediate Representation is the only format that the Inference Engine accepts and understands.
The Model Optimizer does not infer models. It is an offline tool that runs before the inference takes place.
Model Optimizer has two main purposes:
Produce a valid Intermediate Representation. The primary responsibility of the Model Optimizer is to produce two files (.xml and .bin) that form the Intermediate Representation.
Produce an optimized Intermediate Representation. Pretrained models contain layers that are important for training, such as the Dropout layer. These layers are useless during inference and might increase the inference time. In many cases, these layers can be automatically removed from the resulting Intermediate Representation. However, if a group of layers can be represented as one mathematical operation, and thus as a single layer, the Model Optimizer recognizes such patterns and replaces these layers with only one. The result is an Intermediate Representation that has fewer layers than the original model. This decreases the inference time.
Reshaping —
Reshaping —
The Model Optimizer allows us to reshape our input images. Suppose you have trained your model with an image size of 256 * 256 and you want to convert the image size to 100 * 100, then you can simply pass on the new image size as a command-line argument and the Model Optimizer will handle the rest for you.
2. Batching —
We can change the batch size of our model at inference time. We can just pass the value of batch size as a command-line argument.
We can also pass our image size like this [4,3,100,100]. Here we are specifying that we need 4 images with dimensions 100*100*3 i.e RGB images having 3 channels and having width and height as 100. Important thing to note here is that now the inference will be slower as we are using a batch of 4 images for inference rather than using just a single image.
3. Modifying the Network Structure —
We can modify the structure of our network, i.e we can remove layers from the top or from the bottom. We can specify a particular layer from where we want the execution to begin or where we want the execution to end.
4. Standardizing and Scaling —
We can perform operations like normalization (mean subtraction) and standardization on our input data.
It is an important step in the optimization process. Most deep learning models generally use the FP32 format for their input data. The FP32 format consumes a lot of memory and hence increases the inference time. So, intuitively we may think, that we can reduce our inference time by changing the format of our input data. There are various other formats like FP16 and INT8 which we can use, but we need to be careful while performing quantization as it can also result in loss of accuracy.
Using the INT8 format can help us in reducing our inference time significantly, but currently, only certain layers are compatible with the INT8 format: Convolution, ReLU, Pooling, Eltwise and Concat. So, we essentially perform hybrid execution where some layers use FP32 format whereas some layers use INT8 format. There is a separate layer that handles these conversions. i.e we don’t have to explicitly specify the type conversion from one layer to another.
Calibrate layer handles all these intricate type conversions. The way it works is as follows —
Initially, we need to define a threshold value. It determines the drop in accuracy are we willing to accept.
The Calibrate layer then takes a subset of data and tries to convert the data format of layers from FP32 to INT8 or FP16.
It then checks the accuracy drop and if it less than the specified threshold value, then the conversion takes place.
After using the Model Optimizer to create an intermediate representation (IR), we use the Inference Engine to infer input data.
The Inference Engine is a C++ library with a set of C++ classes to infer input data (images) and get a result. The C++ library provides an API to read the Intermediate Representation, set the input and output formats, and execute the model on devices.
The heterogeneous execution of the model is possible because of the Inference Engine. It uses different plug-ins for different devices.
We can execute the same program on multiple devices. We just need to pass in the target device as a command-line argument and the Inference Engine will take care of the rest i.e. we can run the same piece of code on a CPU, GPU, VPU or any other device compatible with the OpenVINO toolkit.
We can also execute parts of our program on different devices i.e. some part of our program might run on CPU and other parts might be running on a FPGA or a GPU. If we specify HETERO: FPGA, CPU then the code will run primarily on an FPGA, but if suppose it encounters a particular operation which is not compatible with FPGA then it will switch to CPU.
We can also execute certain layers on a specific device. Suppose you want to run the Convolution layer only on your GPU then you can explicitly specify it.
The important thing to note here is that we need to be careful about the data format while specifying different hardware. Not all devices work with all the data types. Example — The Neural Compute Stick NCS2, which comes with a Movidius chip, doesn’t support the INT8 format. You can check out this link to get complete information about the supported devices and their respective formats.
The original code sample provided by Intel can be found here.I modified the code sample to make it simpler and my version can be found here.
I will only explain the OpenVINO specific code here.
# Initialize the classinfer_network = Network()# Load the network to IE plugin to get shape of input layern, c, h, w = infer_network.load_model(args.model, args.device, 1, 1, 2, args.cpu_extension)[1]
We are initializing the Network class and loading the model using the load_model function.The load_model function returns the plugin along with the input shape.We only need the input shape that’s why we have specified [1] after the function call.
infer_network.exec_net(next_request_id, in_frame)
The exec_net function will start an asynchronous inference request.We need to pass in the request id and the input frame.
res = infer_network.get_output(cur_request_id)for obj in res[0][0]: if obj[2] > args.prob_threshold: xmin = int(obj[3] * initial_w) ymin = int(obj[4] * initial_h) xmax = int(obj[5] * initial_w) ymax = int(obj[6] * initial_h) class_id = int(obj[1])
This is the most important part of the code.The get_output function will give us the model’s result.Each detection is represented in the following format — [image_id,class_label,confidence,x_min,y_min,x_max,y_max]
Here, we have extracted the bounding box coordinates and the class id.
github.com
This project borrows heavily from store-aisle-monitor-python project from the Intel IOT Devkit.
github.com
To explore other exciting projects by Intel, check out the Intel IoT Developer Kit.
github.com
And with that, we have come to the end of this article. Thanks a ton for reading it.
My LinkedIn, Twitter and Github.You can check out my website to know more about me and my work. | [
{
"code": null,
"e": 127,
"s": 47,
"text": "A comprehensive guide for understanding the functioning of the OpenVINO toolkit"
},
{
"code": null,
"e": 689,
"s": 127,
"text": "OpenVINO stands for Open Visual Inference and Neural Network Optimization. It is a toolkit provided by Intel to facilitate faster inference of deep learning models. It helps developers to create cost-effective and robust computer vision applications. It enables deep learning inference at the edge and supports heterogeneous execution across computer vision accelerators — CPU, GPU, Intel® MovidiusTM Neural Compute Stick, and FPGA. It supports a large number of deep learning models out of the box. You can check out this link to know more about the model zoo."
},
{
"code": null,
"e": 847,
"s": 689,
"text": "If you want to run the code sample provided at the end of this article, then make sure that you have properly downloaded and configured the OpenVINO toolkit."
},
{
"code": null,
"e": 866,
"s": 847,
"text": "software.intel.com"
},
{
"code": null,
"e": 885,
"s": 866,
"text": "software.intel.com"
},
{
"code": null,
"e": 923,
"s": 885,
"text": "The execution process is as follows —"
},
{
"code": null,
"e": 1073,
"s": 923,
"text": "We feed a pre-trained model to the Model Optimizer. It optimizes the model and converts it into its intermediate representation (.xml and .bin file)."
},
{
"code": null,
"e": 1242,
"s": 1073,
"text": "The Inference Engine helps in the proper execution of the model on different devices. It manages the libraries required to run the code properly on different platforms."
},
{
"code": null,
"e": 1423,
"s": 1242,
"text": "The two main components of the OpenVINO toolkit are Model Optimizer and Inference Engine. So, we will dive into their details, to better understand their role and internal working."
},
{
"code": null,
"e": 1645,
"s": 1423,
"text": "Model optimizer is a cross-platform command-line tool that facilitates the transition between the training and deployment environment. It adjusts the deep learning models for optimal execution on end-point target devices."
},
{
"code": null,
"e": 1905,
"s": 1645,
"text": "Model Optimizer loads a model into memory, reads it, builds the internal representation of the model, optimizes it, and produces the Intermediate Representation. Intermediate Representation is the only format that the Inference Engine accepts and understands."
},
{
"code": null,
"e": 2014,
"s": 1905,
"text": "The Model Optimizer does not infer models. It is an offline tool that runs before the inference takes place."
},
{
"code": null,
"e": 2053,
"s": 2014,
"text": "Model Optimizer has two main purposes:"
},
{
"code": null,
"e": 2231,
"s": 2053,
"text": "Produce a valid Intermediate Representation. The primary responsibility of the Model Optimizer is to produce two files (.xml and .bin) that form the Intermediate Representation."
},
{
"code": null,
"e": 2881,
"s": 2231,
"text": "Produce an optimized Intermediate Representation. Pretrained models contain layers that are important for training, such as the Dropout layer. These layers are useless during inference and might increase the inference time. In many cases, these layers can be automatically removed from the resulting Intermediate Representation. However, if a group of layers can be represented as one mathematical operation, and thus as a single layer, the Model Optimizer recognizes such patterns and replaces these layers with only one. The result is an Intermediate Representation that has fewer layers than the original model. This decreases the inference time."
},
{
"code": null,
"e": 2893,
"s": 2881,
"text": "Reshaping —"
},
{
"code": null,
"e": 2905,
"s": 2893,
"text": "Reshaping —"
},
{
"code": null,
"e": 3213,
"s": 2905,
"text": "The Model Optimizer allows us to reshape our input images. Suppose you have trained your model with an image size of 256 * 256 and you want to convert the image size to 100 * 100, then you can simply pass on the new image size as a command-line argument and the Model Optimizer will handle the rest for you."
},
{
"code": null,
"e": 3227,
"s": 3213,
"text": "2. Batching —"
},
{
"code": null,
"e": 3357,
"s": 3227,
"text": "We can change the batch size of our model at inference time. We can just pass the value of batch size as a command-line argument."
},
{
"code": null,
"e": 3713,
"s": 3357,
"text": "We can also pass our image size like this [4,3,100,100]. Here we are specifying that we need 4 images with dimensions 100*100*3 i.e RGB images having 3 channels and having width and height as 100. Important thing to note here is that now the inference will be slower as we are using a batch of 4 images for inference rather than using just a single image."
},
{
"code": null,
"e": 3750,
"s": 3713,
"text": "3. Modifying the Network Structure —"
},
{
"code": null,
"e": 3967,
"s": 3750,
"text": "We can modify the structure of our network, i.e we can remove layers from the top or from the bottom. We can specify a particular layer from where we want the execution to begin or where we want the execution to end."
},
{
"code": null,
"e": 3998,
"s": 3967,
"text": "4. Standardizing and Scaling —"
},
{
"code": null,
"e": 4101,
"s": 3998,
"text": "We can perform operations like normalization (mean subtraction) and standardization on our input data."
},
{
"code": null,
"e": 4591,
"s": 4101,
"text": "It is an important step in the optimization process. Most deep learning models generally use the FP32 format for their input data. The FP32 format consumes a lot of memory and hence increases the inference time. So, intuitively we may think, that we can reduce our inference time by changing the format of our input data. There are various other formats like FP16 and INT8 which we can use, but we need to be careful while performing quantization as it can also result in loss of accuracy."
},
{
"code": null,
"e": 5051,
"s": 4591,
"text": "Using the INT8 format can help us in reducing our inference time significantly, but currently, only certain layers are compatible with the INT8 format: Convolution, ReLU, Pooling, Eltwise and Concat. So, we essentially perform hybrid execution where some layers use FP32 format whereas some layers use INT8 format. There is a separate layer that handles these conversions. i.e we don’t have to explicitly specify the type conversion from one layer to another."
},
{
"code": null,
"e": 5146,
"s": 5051,
"text": "Calibrate layer handles all these intricate type conversions. The way it works is as follows —"
},
{
"code": null,
"e": 5255,
"s": 5146,
"text": "Initially, we need to define a threshold value. It determines the drop in accuracy are we willing to accept."
},
{
"code": null,
"e": 5377,
"s": 5255,
"text": "The Calibrate layer then takes a subset of data and tries to convert the data format of layers from FP32 to INT8 or FP16."
},
{
"code": null,
"e": 5494,
"s": 5377,
"text": "It then checks the accuracy drop and if it less than the specified threshold value, then the conversion takes place."
},
{
"code": null,
"e": 5622,
"s": 5494,
"text": "After using the Model Optimizer to create an intermediate representation (IR), we use the Inference Engine to infer input data."
},
{
"code": null,
"e": 5874,
"s": 5622,
"text": "The Inference Engine is a C++ library with a set of C++ classes to infer input data (images) and get a result. The C++ library provides an API to read the Intermediate Representation, set the input and output formats, and execute the model on devices."
},
{
"code": null,
"e": 6010,
"s": 5874,
"text": "The heterogeneous execution of the model is possible because of the Inference Engine. It uses different plug-ins for different devices."
},
{
"code": null,
"e": 6300,
"s": 6010,
"text": "We can execute the same program on multiple devices. We just need to pass in the target device as a command-line argument and the Inference Engine will take care of the rest i.e. we can run the same piece of code on a CPU, GPU, VPU or any other device compatible with the OpenVINO toolkit."
},
{
"code": null,
"e": 6653,
"s": 6300,
"text": "We can also execute parts of our program on different devices i.e. some part of our program might run on CPU and other parts might be running on a FPGA or a GPU. If we specify HETERO: FPGA, CPU then the code will run primarily on an FPGA, but if suppose it encounters a particular operation which is not compatible with FPGA then it will switch to CPU."
},
{
"code": null,
"e": 6809,
"s": 6653,
"text": "We can also execute certain layers on a specific device. Suppose you want to run the Convolution layer only on your GPU then you can explicitly specify it."
},
{
"code": null,
"e": 7199,
"s": 6809,
"text": "The important thing to note here is that we need to be careful about the data format while specifying different hardware. Not all devices work with all the data types. Example — The Neural Compute Stick NCS2, which comes with a Movidius chip, doesn’t support the INT8 format. You can check out this link to get complete information about the supported devices and their respective formats."
},
{
"code": null,
"e": 7340,
"s": 7199,
"text": "The original code sample provided by Intel can be found here.I modified the code sample to make it simpler and my version can be found here."
},
{
"code": null,
"e": 7393,
"s": 7340,
"text": "I will only explain the OpenVINO specific code here."
},
{
"code": null,
"e": 7594,
"s": 7393,
"text": "# Initialize the classinfer_network = Network()# Load the network to IE plugin to get shape of input layern, c, h, w = infer_network.load_model(args.model, args.device, 1, 1, 2, args.cpu_extension)[1]"
},
{
"code": null,
"e": 7841,
"s": 7594,
"text": "We are initializing the Network class and loading the model using the load_model function.The load_model function returns the plugin along with the input shape.We only need the input shape that’s why we have specified [1] after the function call."
},
{
"code": null,
"e": 7891,
"s": 7841,
"text": "infer_network.exec_net(next_request_id, in_frame)"
},
{
"code": null,
"e": 8013,
"s": 7891,
"text": "The exec_net function will start an asynchronous inference request.We need to pass in the request id and the input frame."
},
{
"code": null,
"e": 8277,
"s": 8013,
"text": "res = infer_network.get_output(cur_request_id)for obj in res[0][0]: if obj[2] > args.prob_threshold: xmin = int(obj[3] * initial_w) ymin = int(obj[4] * initial_h) xmax = int(obj[5] * initial_w) ymax = int(obj[6] * initial_h) class_id = int(obj[1])"
},
{
"code": null,
"e": 8491,
"s": 8277,
"text": "This is the most important part of the code.The get_output function will give us the model’s result.Each detection is represented in the following format — [image_id,class_label,confidence,x_min,y_min,x_max,y_max]"
},
{
"code": null,
"e": 8562,
"s": 8491,
"text": "Here, we have extracted the bounding box coordinates and the class id."
},
{
"code": null,
"e": 8573,
"s": 8562,
"text": "github.com"
},
{
"code": null,
"e": 8669,
"s": 8573,
"text": "This project borrows heavily from store-aisle-monitor-python project from the Intel IOT Devkit."
},
{
"code": null,
"e": 8680,
"s": 8669,
"text": "github.com"
},
{
"code": null,
"e": 8764,
"s": 8680,
"text": "To explore other exciting projects by Intel, check out the Intel IoT Developer Kit."
},
{
"code": null,
"e": 8775,
"s": 8764,
"text": "github.com"
},
{
"code": null,
"e": 8860,
"s": 8775,
"text": "And with that, we have come to the end of this article. Thanks a ton for reading it."
}
] |
How to disable ONLY_FULL_GROUP_BY in MySQL? | You can enable ONLY_FULL_GROUP_BY in MySQL as shown in the following query −
mysql> SET sql_mode = 'ONLY_FULL_GROUP_BY';
Query OK, 0 rows affected (0.01 sec)
As shown above, we can enable ONLY_FULL_GROUP_BY with the help of SET command.
To disable ONLY_FULL_GROUP_BY with the help of the following query −
mysql> SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));
Query OK, 0 rows affected (0.04 sec)
We have disabled ONLY_FULL_GROUP_BY successfully. | [
{
"code": null,
"e": 1139,
"s": 1062,
"text": "You can enable ONLY_FULL_GROUP_BY in MySQL as shown in the following query −"
},
{
"code": null,
"e": 1220,
"s": 1139,
"text": "mysql> SET sql_mode = 'ONLY_FULL_GROUP_BY';\nQuery OK, 0 rows affected (0.01 sec)"
},
{
"code": null,
"e": 1299,
"s": 1220,
"text": "As shown above, we can enable ONLY_FULL_GROUP_BY with the help of SET command."
},
{
"code": null,
"e": 1368,
"s": 1299,
"text": "To disable ONLY_FULL_GROUP_BY with the help of the following query −"
},
{
"code": null,
"e": 1486,
"s": 1368,
"text": "mysql> SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));\nQuery OK, 0 rows affected (0.04 sec)"
},
{
"code": null,
"e": 1536,
"s": 1486,
"text": "We have disabled ONLY_FULL_GROUP_BY successfully."
}
] |
Angular PrimeNG Dropdown Component - GeeksforGeeks | 11 Sep, 2021
Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the Dropdown component in Angular ngx Bootstrap. We will also learn about the various properties, events, methods & styling along with their syntaxes that will be used in the code example.
Dropdown component: It is used to make to choose the objects from the given list of items.
Properties:
options: It is an array object representing select items to display as the available options. It is of array data type, the default value is null.
optionLabel: It is used to give the name to a label of an option. It is of string data type, the default value is the label.
optionValue: It is used to give the name to a value of an option, defaults to the option itself when not defined. It is of string data type, the default value is value.
optionGroupLabel: It is used to give a name to a label in the option group. It is of string data type, the default value is the label.
optionGroupChildren: It is used to give a name to the options field in the option group. It is of string data type, the default value is item.
name: It is used to set the name of the input element. It is of string data type, the default value is null.
scrollHeight: It is used to set the height of the viewport in pixels, a scrollbar is defined if the height of the list exceeds this value. It is of string data type, the default value is 200px.
style: It is used to set an inline style of the element. It is of string data type, the default value is null.
styleClass: It is used to set the style class of the element. It is of string data type, the default value is null.
filter: It is used to display an input field to filter the items on keyup. It is of boolean data type, the default value is false.
filterValue: It is a filter displayed with this value. It is of string data type, the default value is null.
filterBy: It decides which field or fields (comma separated) to search against. It is of string data type, the default value is null.
filterMatchMode: It is used to define how the items are filtered. It is of string data type, the default value is contains.
filterPlaceholder: It is used to set the placeholder text to show when filter input is empty. It is of string data type, the default value is null.
filterLocale: It is used to set the locale to use in filtering. The default locale is the host environment’s current locale. It is of string data type, the default value is undefined.
required: It specifies that an input field must be filled out before submitting the form. It is of the boolean data type, the default value is false.
disabled: It specifies that the component should be disabled. It is of the boolean data type, the default value is false.
readonly: It specifies that the component cannot be edited. It is of the boolean data type, the default value is false.
emptyMessage: It is used to set the text to display when there is no data. It is of string data type.
emptyFilterMessage: It is used to set the text to display when filtering does not return any results. It is of string data type.
ariaLabelledBy: It is the ariaLabelledBy property that establishes relationships between the component and label(s) where its value should be one or more element IDs. It is of string data type, the default value is null.
editable: It is used to specify the custom value instead of predefined options that can be entered using the editable input field. It is of the boolean data type, the default value is false.
maxlength: It is used to specify the maximum number of characters allowed in the editable input field, It is of number datatype, the default value is null.
appendTo: This property takes the ID of the element on which overlay is appended to. It accepts any data type, the default value is null.
tabindex: It is used to set the index of the element in tabbing order. It is of number datatype, the default value is null.
inputId: It is an ID identifier of the underlying input element. It is of string data type, the default value is null.
dataKey: It is a property to uniquely identify a value in options. It is of string data type, the default value is null.
autofocus: it specifies that the component should automatically focus on load. It is of the boolean data type, the default value is false.
autofocusFilter: It is used to apply focus to the filter element when the overlay is shown. It is of the boolean data type, the default value is false.
resetFilterOnHide: It is used to clear the filter value when hiding the dropdown. It is of the boolean data type, the default value is false.
dropdownIcon: It is used to set the icon class of the dropdown icon. It is of string data type, the default value is pi pi-chevron-down.
emptyFilterMessage: It is used to set the text to display when filtering does not return any results. It is of string data type.
autoDisplayFirst: It is used to specify whether to display the first item as the label if no placeholder is defined and the value is null. It is of the boolean data type, the default value is true.
group: It is used to specify whether to display options as grouped when nested options are provided. It is of the boolean data type, the default value is false.
showClear: It is used to show the clear icon which is displayed to clear the value. It is of boolean data type, the default value is false.
baseZIndex: It is used to set the base zIndex value to use in the layering. It is of number datatype, the default value is 0.
autoZIndex: It is used to specify whether to automatically manage the layering. It is of the boolean data type, the default value is true.
showTransitionOptions: It is used to set the Transition options of the show animation. It is of string data type, the default value is .12s cubic-bezier(0, 0, 0.2, 1).
hideTransitionOptions: It is used to set the transition options of the hide animation. It is of string data type, the default value is .1s linear.
ariaFilterLabel: It is used to define a string that labels the filter input. It is of string data type, the default value is null.
tooltip: It is used to show the advisory information to display in a tooltip on hover. It accepts any data type, the default value is null.
tooltipStyleClass: It is used to set the Style class of the tooltip. It is of string data type, the default value is null.
tooltipPosition: It is used to set the position of the tooltip, the valid values are right, left, top and bottom. It is of string data type, the default value is top.
tooltipPositionStyle: It is used to set the type of CSS position. It is of string data type, the default value is absolute.
Events:
onClick: It is a callback that is fired when the component is clicked.
onChange: It is a callback that is fired when the value of the dropdown changes.
onFilter: It is a callback that is fired when data is filtered.
onFocus: It is a callback that is fired when dropdown gets focus.
onBlur: It is a callback that is fired when dropdown loses focus.
onShow: It is a callback that is fired when the dropdown overlay gets visible.
onHide: It is a callback that is fired when the dropdown overlay gets hidden.
Methods:
resetFilter: It is used to resets the filter.
focus: It is used to apply the focus.
show: It is used to displays the panel.
hide: It is used to hides the panel.
Styling:
p-dropdown: It is a styling container element.
p-dropdown-clearable: It is a styling container element when showClear is on.
p-dropdown-label: It is a styling element to display the label of the selected option.
p-dropdown-trigger: It is a styling icon element.
p-dropdown-panel: It is a styling panel element.
p-dropdown-items-wrapper: It is a styling wrapper element of the items list.
p-dropdown-items: It is a styling list element of items.
p-dropdown-item: It is a list item.
p-dropdown-filter-container: It is a styling container of filter input.
p-dropdown-filter: It is a styling filter element.
p-dropdown-open: It is a styling container element when the overlay is visible.
Creating Angular application & module installation:
Step 1: Create an Angular application using the following command.
ng new appname
Step 2: After creating your project folder i.e. appname, move to it using the following command.
cd appname
Step 3: Install PrimeNG in your given directory.
npm install primeng --save
npm install primeicons --save
Project Structure: It will look like the following:
Example 1: This is the basic example that shows how to use the dropdown component.
app.component.html
<h2>GeeksforGeeks</h2>
<h5>PrimeNG dropdowm component</h5>
<p-dropdown
[options]="lang"
placeholder="Select a Language"
optionLabel="name"
[showClear]="true">
</p-dropdown>
app.component.ts
import { Component } from "@angular/core";
@Component({
selector: "my-app",
templateUrl: "./app.component.html"
})
export class AppComponent {
lang = [
{ name: "HTML" },
{ name: "ReactJS" },
{ name: "Angular" },
{ name: "Bootstrap" },
{ name: "PrimeNG" },
];
}
app.module.ts
import { NgModule } from "@angular/core";
import { BrowserModule } from "@angular/platform-browser";
import { FormsModule } from "@angular/forms";
import { BrowserAnimationsModule }
from "@angular/platform-browser/animations";
import { AppComponent } from "./app.component";
import { DropdownModule } from "primeng/dropdown";
@NgModule({
imports: [
BrowserModule,
BrowserAnimationsModule,
DropdownModule,
FormsModule,
],
declarations: [AppComponent],
bootstrap: [AppComponent],
})
export class AppModule {}
Output:
Example 2: In this example, we will know how to use editable property in the dropdown component.
app.component.html
<h2>GeeksforGeeks</h2>
<h5>PrimeNG dropdowm component</h5>
<p-dropdown
[options]='[{name: "Editable1"}, {name: "Editable2"},
{name: "Editable3"}, {name: "Editable4"},
{name: "Editable5"}]'
editable="true"
placeholder="Select a Language"
optionLabel="name"
[showClear]="true">
</p-dropdown>
app.component.ts
import { Component } from "@angular/core";
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.scss"],
})
export class AppComponent {
}
app.module.ts
import { NgModule } from "@angular/core";
import { BrowserModule } from "@angular/platform-browser";
import { FormsModule } from "@angular/forms";
import { BrowserAnimationsModule }
from "@angular/platform-browser/animations";
import { AppComponent } from "./app.component";
import { DropdownModule } from "primeng/dropdown";
@NgModule({
imports: [
BrowserModule,
BrowserAnimationsModule,
DropdownModule,
FormsModule,
],
declarations: [AppComponent],
bootstrap: [AppComponent],
})
export class AppModule {}
Output:
Reference: https://primefaces.org/primeng/showcase/#/dropdown
Angular-PrimeNG
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Auth Guards in Angular 9/10/11
What is AOT and JIT Compiler in Angular ?
How to set focus on input field automatically on page load in AngularJS ?
How to make a Bootstrap Modal Popup in Angular 9/8 ?
Angular 10 (blur) Event
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 24148,
"s": 24117,
"text": " \n11 Sep, 2021\n"
},
{
"code": null,
"e": 24579,
"s": 24148,
"text": "Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the Dropdown component in Angular ngx Bootstrap. We will also learn about the various properties, events, methods & styling along with their syntaxes that will be used in the code example. "
},
{
"code": null,
"e": 24671,
"s": 24579,
"text": "Dropdown component: It is used to make to choose the objects from the given list of items. "
},
{
"code": null,
"e": 24683,
"s": 24671,
"text": "Properties:"
},
{
"code": null,
"e": 24830,
"s": 24683,
"text": "options: It is an array object representing select items to display as the available options. It is of array data type, the default value is null."
},
{
"code": null,
"e": 24955,
"s": 24830,
"text": "optionLabel: It is used to give the name to a label of an option. It is of string data type, the default value is the label."
},
{
"code": null,
"e": 25124,
"s": 24955,
"text": "optionValue: It is used to give the name to a value of an option, defaults to the option itself when not defined. It is of string data type, the default value is value."
},
{
"code": null,
"e": 25259,
"s": 25124,
"text": "optionGroupLabel: It is used to give a name to a label in the option group. It is of string data type, the default value is the label."
},
{
"code": null,
"e": 25402,
"s": 25259,
"text": "optionGroupChildren: It is used to give a name to the options field in the option group. It is of string data type, the default value is item."
},
{
"code": null,
"e": 25511,
"s": 25402,
"text": "name: It is used to set the name of the input element. It is of string data type, the default value is null."
},
{
"code": null,
"e": 25705,
"s": 25511,
"text": "scrollHeight: It is used to set the height of the viewport in pixels, a scrollbar is defined if the height of the list exceeds this value. It is of string data type, the default value is 200px."
},
{
"code": null,
"e": 25816,
"s": 25705,
"text": "style: It is used to set an inline style of the element. It is of string data type, the default value is null."
},
{
"code": null,
"e": 25933,
"s": 25816,
"text": "styleClass: It is used to set the style class of the element. It is of string data type, the default value is null."
},
{
"code": null,
"e": 26064,
"s": 25933,
"text": "filter: It is used to display an input field to filter the items on keyup. It is of boolean data type, the default value is false."
},
{
"code": null,
"e": 26173,
"s": 26064,
"text": "filterValue: It is a filter displayed with this value. It is of string data type, the default value is null."
},
{
"code": null,
"e": 26307,
"s": 26173,
"text": "filterBy: It decides which field or fields (comma separated) to search against. It is of string data type, the default value is null."
},
{
"code": null,
"e": 26431,
"s": 26307,
"text": "filterMatchMode: It is used to define how the items are filtered. It is of string data type, the default value is contains."
},
{
"code": null,
"e": 26579,
"s": 26431,
"text": "filterPlaceholder: It is used to set the placeholder text to show when filter input is empty. It is of string data type, the default value is null."
},
{
"code": null,
"e": 26763,
"s": 26579,
"text": "filterLocale: It is used to set the locale to use in filtering. The default locale is the host environment’s current locale. It is of string data type, the default value is undefined."
},
{
"code": null,
"e": 26913,
"s": 26763,
"text": "required: It specifies that an input field must be filled out before submitting the form. It is of the boolean data type, the default value is false."
},
{
"code": null,
"e": 27035,
"s": 26913,
"text": "disabled: It specifies that the component should be disabled. It is of the boolean data type, the default value is false."
},
{
"code": null,
"e": 27155,
"s": 27035,
"text": "readonly: It specifies that the component cannot be edited. It is of the boolean data type, the default value is false."
},
{
"code": null,
"e": 27257,
"s": 27155,
"text": "emptyMessage: It is used to set the text to display when there is no data. It is of string data type."
},
{
"code": null,
"e": 27386,
"s": 27257,
"text": "emptyFilterMessage: It is used to set the text to display when filtering does not return any results. It is of string data type."
},
{
"code": null,
"e": 27607,
"s": 27386,
"text": "ariaLabelledBy: It is the ariaLabelledBy property that establishes relationships between the component and label(s) where its value should be one or more element IDs. It is of string data type, the default value is null."
},
{
"code": null,
"e": 27798,
"s": 27607,
"text": "editable: It is used to specify the custom value instead of predefined options that can be entered using the editable input field. It is of the boolean data type, the default value is false."
},
{
"code": null,
"e": 27954,
"s": 27798,
"text": "maxlength: It is used to specify the maximum number of characters allowed in the editable input field, It is of number datatype, the default value is null."
},
{
"code": null,
"e": 28092,
"s": 27954,
"text": "appendTo: This property takes the ID of the element on which overlay is appended to. It accepts any data type, the default value is null."
},
{
"code": null,
"e": 28216,
"s": 28092,
"text": "tabindex: It is used to set the index of the element in tabbing order. It is of number datatype, the default value is null."
},
{
"code": null,
"e": 28336,
"s": 28216,
"text": "inputId: It is an ID identifier of the underlying input element. It is of string data type, the default value is null."
},
{
"code": null,
"e": 28457,
"s": 28336,
"text": "dataKey: It is a property to uniquely identify a value in options. It is of string data type, the default value is null."
},
{
"code": null,
"e": 28596,
"s": 28457,
"text": "autofocus: it specifies that the component should automatically focus on load. It is of the boolean data type, the default value is false."
},
{
"code": null,
"e": 28748,
"s": 28596,
"text": "autofocusFilter: It is used to apply focus to the filter element when the overlay is shown. It is of the boolean data type, the default value is false."
},
{
"code": null,
"e": 28890,
"s": 28748,
"text": "resetFilterOnHide: It is used to clear the filter value when hiding the dropdown. It is of the boolean data type, the default value is false."
},
{
"code": null,
"e": 29027,
"s": 28890,
"text": "dropdownIcon: It is used to set the icon class of the dropdown icon. It is of string data type, the default value is pi pi-chevron-down."
},
{
"code": null,
"e": 29156,
"s": 29027,
"text": "emptyFilterMessage: It is used to set the text to display when filtering does not return any results. It is of string data type."
},
{
"code": null,
"e": 29354,
"s": 29156,
"text": "autoDisplayFirst: It is used to specify whether to display the first item as the label if no placeholder is defined and the value is null. It is of the boolean data type, the default value is true."
},
{
"code": null,
"e": 29515,
"s": 29354,
"text": "group: It is used to specify whether to display options as grouped when nested options are provided. It is of the boolean data type, the default value is false."
},
{
"code": null,
"e": 29655,
"s": 29515,
"text": "showClear: It is used to show the clear icon which is displayed to clear the value. It is of boolean data type, the default value is false."
},
{
"code": null,
"e": 29781,
"s": 29655,
"text": "baseZIndex: It is used to set the base zIndex value to use in the layering. It is of number datatype, the default value is 0."
},
{
"code": null,
"e": 29920,
"s": 29781,
"text": "autoZIndex: It is used to specify whether to automatically manage the layering. It is of the boolean data type, the default value is true."
},
{
"code": null,
"e": 30088,
"s": 29920,
"text": "showTransitionOptions: It is used to set the Transition options of the show animation. It is of string data type, the default value is .12s cubic-bezier(0, 0, 0.2, 1)."
},
{
"code": null,
"e": 30235,
"s": 30088,
"text": "hideTransitionOptions: It is used to set the transition options of the hide animation. It is of string data type, the default value is .1s linear."
},
{
"code": null,
"e": 30366,
"s": 30235,
"text": "ariaFilterLabel: It is used to define a string that labels the filter input. It is of string data type, the default value is null."
},
{
"code": null,
"e": 30506,
"s": 30366,
"text": "tooltip: It is used to show the advisory information to display in a tooltip on hover. It accepts any data type, the default value is null."
},
{
"code": null,
"e": 30629,
"s": 30506,
"text": "tooltipStyleClass: It is used to set the Style class of the tooltip. It is of string data type, the default value is null."
},
{
"code": null,
"e": 30796,
"s": 30629,
"text": "tooltipPosition: It is used to set the position of the tooltip, the valid values are right, left, top and bottom. It is of string data type, the default value is top."
},
{
"code": null,
"e": 30920,
"s": 30796,
"text": "tooltipPositionStyle: It is used to set the type of CSS position. It is of string data type, the default value is absolute."
},
{
"code": null,
"e": 30928,
"s": 30920,
"text": "Events:"
},
{
"code": null,
"e": 30999,
"s": 30928,
"text": "onClick: It is a callback that is fired when the component is clicked."
},
{
"code": null,
"e": 31080,
"s": 30999,
"text": "onChange: It is a callback that is fired when the value of the dropdown changes."
},
{
"code": null,
"e": 31144,
"s": 31080,
"text": "onFilter: It is a callback that is fired when data is filtered."
},
{
"code": null,
"e": 31210,
"s": 31144,
"text": "onFocus: It is a callback that is fired when dropdown gets focus."
},
{
"code": null,
"e": 31276,
"s": 31210,
"text": "onBlur: It is a callback that is fired when dropdown loses focus."
},
{
"code": null,
"e": 31355,
"s": 31276,
"text": "onShow: It is a callback that is fired when the dropdown overlay gets visible."
},
{
"code": null,
"e": 31433,
"s": 31355,
"text": "onHide: It is a callback that is fired when the dropdown overlay gets hidden."
},
{
"code": null,
"e": 31444,
"s": 31435,
"text": "Methods:"
},
{
"code": null,
"e": 31490,
"s": 31444,
"text": "resetFilter: It is used to resets the filter."
},
{
"code": null,
"e": 31528,
"s": 31490,
"text": "focus: It is used to apply the focus."
},
{
"code": null,
"e": 31568,
"s": 31528,
"text": "show: It is used to displays the panel."
},
{
"code": null,
"e": 31605,
"s": 31568,
"text": "hide: It is used to hides the panel."
},
{
"code": null,
"e": 31614,
"s": 31605,
"text": "Styling:"
},
{
"code": null,
"e": 31661,
"s": 31614,
"text": "p-dropdown: It is a styling container element."
},
{
"code": null,
"e": 31739,
"s": 31661,
"text": "p-dropdown-clearable: It is a styling container element when showClear is on."
},
{
"code": null,
"e": 31826,
"s": 31739,
"text": "p-dropdown-label: It is a styling element to display the label of the selected option."
},
{
"code": null,
"e": 31876,
"s": 31826,
"text": "p-dropdown-trigger: It is a styling icon element."
},
{
"code": null,
"e": 31925,
"s": 31876,
"text": "p-dropdown-panel: It is a styling panel element."
},
{
"code": null,
"e": 32002,
"s": 31925,
"text": "p-dropdown-items-wrapper: It is a styling wrapper element of the items list."
},
{
"code": null,
"e": 32059,
"s": 32002,
"text": "p-dropdown-items: It is a styling list element of items."
},
{
"code": null,
"e": 32095,
"s": 32059,
"text": "p-dropdown-item: It is a list item."
},
{
"code": null,
"e": 32167,
"s": 32095,
"text": "p-dropdown-filter-container: It is a styling container of filter input."
},
{
"code": null,
"e": 32218,
"s": 32167,
"text": "p-dropdown-filter: It is a styling filter element."
},
{
"code": null,
"e": 32298,
"s": 32218,
"text": "p-dropdown-open: It is a styling container element when the overlay is visible."
},
{
"code": null,
"e": 32351,
"s": 32298,
"text": "Creating Angular application & module installation:"
},
{
"code": null,
"e": 32418,
"s": 32351,
"text": "Step 1: Create an Angular application using the following command."
},
{
"code": null,
"e": 32433,
"s": 32418,
"text": "ng new appname"
},
{
"code": null,
"e": 32530,
"s": 32433,
"text": "Step 2: After creating your project folder i.e. appname, move to it using the following command."
},
{
"code": null,
"e": 32541,
"s": 32530,
"text": "cd appname"
},
{
"code": null,
"e": 32590,
"s": 32541,
"text": "Step 3: Install PrimeNG in your given directory."
},
{
"code": null,
"e": 32647,
"s": 32590,
"text": "npm install primeng --save\nnpm install primeicons --save"
},
{
"code": null,
"e": 32699,
"s": 32647,
"text": "Project Structure: It will look like the following:"
},
{
"code": null,
"e": 32782,
"s": 32699,
"text": "Example 1: This is the basic example that shows how to use the dropdown component."
},
{
"code": null,
"e": 32801,
"s": 32782,
"text": "app.component.html"
},
{
"code": "\n\n\n\n\n\n\n<h2>GeeksforGeeks</h2> \n<h5>PrimeNG dropdowm component</h5> \n<p-dropdown\n [options]=\"lang\" \n placeholder=\"Select a Language\"\n optionLabel=\"name\"\n [showClear]=\"true\"> \n</p-dropdown> \n\n\n\n\n\n",
"e": 33010,
"s": 32811,
"text": null
},
{
"code": null,
"e": 33029,
"s": 33012,
"text": "app.component.ts"
},
{
"code": "\n\n\n\n\n\n\nimport { Component } from \"@angular/core\"; \n \n@Component({ \n selector: \"my-app\", \n templateUrl: \"./app.component.html\"\n}) \nexport class AppComponent { \n lang = [ \n { name: \"HTML\" }, \n { name: \"ReactJS\" }, \n { name: \"Angular\" }, \n { name: \"Bootstrap\" }, \n { name: \"PrimeNG\" }, \n ]; \n}\n\n\n\n\n\n",
"e": 33356,
"s": 33039,
"text": null
},
{
"code": null,
"e": 33370,
"s": 33356,
"text": "app.module.ts"
},
{
"code": "\n\n\n\n\n\n\nimport { NgModule } from \"@angular/core\"; \nimport { BrowserModule } from \"@angular/platform-browser\"; \nimport { FormsModule } from \"@angular/forms\"; \nimport { BrowserAnimationsModule } \n from \"@angular/platform-browser/animations\"; \n \nimport { AppComponent } from \"./app.component\"; \nimport { DropdownModule } from \"primeng/dropdown\"; \n \n@NgModule({ \n imports: [ \n BrowserModule, \n BrowserAnimationsModule, \n DropdownModule, \n FormsModule, \n ], \n declarations: [AppComponent], \n bootstrap: [AppComponent], \n}) \nexport class AppModule {}\n\n\n\n\n\n",
"e": 33952,
"s": 33380,
"text": null
},
{
"code": null,
"e": 33960,
"s": 33952,
"text": "Output:"
},
{
"code": null,
"e": 34058,
"s": 33960,
"text": "Example 2: In this example, we will know how to use editable property in the dropdown component. "
},
{
"code": null,
"e": 34077,
"s": 34058,
"text": "app.component.html"
},
{
"code": "\n\n\n\n\n\n\n<h2>GeeksforGeeks</h2> \n<h5>PrimeNG dropdowm component</h5> \n<p-dropdown\n [options]='[{name: \"Editable1\"}, {name: \"Editable2\"}, \n {name: \"Editable3\"}, {name: \"Editable4\"}, \n {name: \"Editable5\"}]' \n editable=\"true\"\n placeholder=\"Select a Language\"\n optionLabel=\"name\"\n [showClear]=\"true\"> \n</p-dropdown> \n\n\n\n\n\n",
"e": 34435,
"s": 34087,
"text": null
},
{
"code": null,
"e": 34452,
"s": 34435,
"text": "app.component.ts"
},
{
"code": "\n\n\n\n\n\n\nimport { Component } from \"@angular/core\"; \n \n@Component({ \n selector: \"my-app\", \n templateUrl: \"./app.component.html\", \n styleUrls: [\"./app.component.scss\"], \n}) \nexport class AppComponent { \n \n}\n\n\n\n\n\n",
"e": 34677,
"s": 34462,
"text": null
},
{
"code": null,
"e": 34691,
"s": 34677,
"text": "app.module.ts"
},
{
"code": "\n\n\n\n\n\n\nimport { NgModule } from \"@angular/core\"; \nimport { BrowserModule } from \"@angular/platform-browser\"; \nimport { FormsModule } from \"@angular/forms\"; \nimport { BrowserAnimationsModule } \n from \"@angular/platform-browser/animations\"; \n \nimport { AppComponent } from \"./app.component\"; \nimport { DropdownModule } from \"primeng/dropdown\"; \n \n@NgModule({ \n imports: [ \n BrowserModule, \n BrowserAnimationsModule, \n DropdownModule, \n FormsModule, \n ], \n declarations: [AppComponent], \n bootstrap: [AppComponent], \n}) \nexport class AppModule {}\n\n\n\n\n\n",
"e": 35273,
"s": 34701,
"text": null
},
{
"code": null,
"e": 35281,
"s": 35273,
"text": "Output:"
},
{
"code": null,
"e": 35343,
"s": 35281,
"text": "Reference: https://primefaces.org/primeng/showcase/#/dropdown"
},
{
"code": null,
"e": 35361,
"s": 35343,
"text": "\nAngular-PrimeNG\n"
},
{
"code": null,
"e": 35373,
"s": 35361,
"text": "\nAngularJS\n"
},
{
"code": null,
"e": 35392,
"s": 35373,
"text": "\nWeb Technologies\n"
},
{
"code": null,
"e": 35597,
"s": 35392,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 35628,
"s": 35597,
"text": "Auth Guards in Angular 9/10/11"
},
{
"code": null,
"e": 35670,
"s": 35628,
"text": "What is AOT and JIT Compiler in Angular ?"
},
{
"code": null,
"e": 35744,
"s": 35670,
"text": "How to set focus on input field automatically on page load in AngularJS ?"
},
{
"code": null,
"e": 35797,
"s": 35744,
"text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?"
},
{
"code": null,
"e": 35821,
"s": 35797,
"text": "Angular 10 (blur) Event"
},
{
"code": null,
"e": 35877,
"s": 35821,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 35910,
"s": 35877,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 35972,
"s": 35910,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 36015,
"s": 35972,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Min Stack in Python | Here we will see how to make a stack, that can perform push, pop, top, and retrieve the min element in constant time. So the functions will be push(x), pop(), top() and getMin()
To solve this, we will follow these steps −
Initialize the stack by min element as infinity
For push operation push(x)if x < min, then update min := x,push x into stack
if x < min, then update min := x,
push x into stack
For pop operation pop()t := top elementdelete t from stackif t is min, then min := top element of the stack
t := top element
delete t from stack
if t is min, then min := top element of the stack
For top operation top()simply return the top element
simply return the top element
for getMin operation getMin()return the min element
return the min element
Let us see the following implementation to get better understanding −
class MinStack(object):
min=float('inf')
def __init__(self):
self.min=float('inf')
self.stack = []
def push(self, x):
if x<=self.min:
self.stack.append(self.min)
self.min = x
self.stack.append(x)
def pop(self):
t = self.stack[-1]
self.stack.pop()
if self.min == t:
self.min = self.stack[-1]
self.stack.pop()
def top(self):
return self.stack[-1]
def getMin(self):
return self.min
m = MinStack()
m.push(-2)
m.push(0)
m.push(-3)
print(m.getMin())
m.pop()
print(m.top())
print(m.getMin())
m = MinStack()
m.push(-2)
m.push(0)
m.push(-3)
print(m.getMin())
m.pop()
print(m.top())
print(m.getMin())
-3
0
-2 | [
{
"code": null,
"e": 1240,
"s": 1062,
"text": "Here we will see how to make a stack, that can perform push, pop, top, and retrieve the min element in constant time. So the functions will be push(x), pop(), top() and getMin()"
},
{
"code": null,
"e": 1284,
"s": 1240,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1332,
"s": 1284,
"text": "Initialize the stack by min element as infinity"
},
{
"code": null,
"e": 1409,
"s": 1332,
"text": "For push operation push(x)if x < min, then update min := x,push x into stack"
},
{
"code": null,
"e": 1443,
"s": 1409,
"text": "if x < min, then update min := x,"
},
{
"code": null,
"e": 1461,
"s": 1443,
"text": "push x into stack"
},
{
"code": null,
"e": 1569,
"s": 1461,
"text": "For pop operation pop()t := top elementdelete t from stackif t is min, then min := top element of the stack"
},
{
"code": null,
"e": 1586,
"s": 1569,
"text": "t := top element"
},
{
"code": null,
"e": 1606,
"s": 1586,
"text": "delete t from stack"
},
{
"code": null,
"e": 1656,
"s": 1606,
"text": "if t is min, then min := top element of the stack"
},
{
"code": null,
"e": 1709,
"s": 1656,
"text": "For top operation top()simply return the top element"
},
{
"code": null,
"e": 1739,
"s": 1709,
"text": "simply return the top element"
},
{
"code": null,
"e": 1791,
"s": 1739,
"text": "for getMin operation getMin()return the min element"
},
{
"code": null,
"e": 1814,
"s": 1791,
"text": "return the min element"
},
{
"code": null,
"e": 1884,
"s": 1814,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 2477,
"s": 1884,
"text": "class MinStack(object):\n min=float('inf')\n def __init__(self):\n self.min=float('inf')\n self.stack = []\n def push(self, x):\n if x<=self.min:\n self.stack.append(self.min)\n self.min = x\n self.stack.append(x)\n def pop(self):\n t = self.stack[-1]\n self.stack.pop()\n if self.min == t:\n self.min = self.stack[-1]\n self.stack.pop()\n def top(self):\n return self.stack[-1]\n def getMin(self):\n return self.min\nm = MinStack()\nm.push(-2)\nm.push(0)\nm.push(-3)\nprint(m.getMin())\nm.pop()\nprint(m.top())\nprint(m.getMin())"
},
{
"code": null,
"e": 2583,
"s": 2477,
"text": "m = MinStack()\nm.push(-2)\nm.push(0)\nm.push(-3)\nprint(m.getMin())\nm.pop()\nprint(m.top())\nprint(m.getMin())"
},
{
"code": null,
"e": 2591,
"s": 2583,
"text": "-3\n0\n-2"
}
] |
Java Program to Remove an Element from ArrayList using ListIterator - GeeksforGeeks | 20 Dec, 2021
ListIterator.remove() method removes the last element from the list that was returned by next() or previous() cursor positions. It can be called only once per call to next or previous. It can be made only if the operation — add(E) has not called after the last call to next or previous.
Internal working in ArrayList is shown below be its removal or addition of elements to it. Considering generic removal of elements prior to the switch to ListIterator.
Syntax:
listIterator.remove();
Index to be removedIndex value to be removed
Index to be removed
Index value to be removed
Illustration:
Input: ArrayList = [“Red”, “White”, “Blue”, “Pink”]
Output: ArrayList = [“Red”, “Blue”, “Pink”]
Remove element “White” or 2nd element in the ArrayList.
Input: ArrayList = [“Red”, “White”, “Blue”, “Pink”]
Output : ArrayList = [“Red”, “White”, “Blue”, “Pink”]
Remove element “Black” or 5th element in the ArrayList. Since the element that has to be removed is not in the ArrayList so nothing will be removed.
Procedure: To Remove an element from ArrayList using ListIterator is as follows:
Create ArrayList instance new ArrayList<String>();Add elements in ArrayList colors using colors.add(“Red”);Create ListIterator instance of colors.listIterator();Print list elements before removing elements.Increment the iterator by listIterator.next() and move to element which you want to remove;Remove the element by listIterator.remove();Print the list after removing the element. In this example, we have removed the element “White.
Create ArrayList instance new ArrayList<String>();
Add elements in ArrayList colors using colors.add(“Red”);
Create ListIterator instance of colors.listIterator();
Print list elements before removing elements.
Increment the iterator by listIterator.next() and move to element which you want to remove;
Remove the element by listIterator.remove();
Print the list after removing the element. In this example, we have removed the element “White.
State transactions while deleting an element from ArrayList
Case 1: Using loops if the index of the element to be removed is known
Java
// Java Program to Remove an element from ArrayList// using ListIterator // Importing ArrayList and ListIterator classes// of java.util packageimport java.util.ArrayList;import java.util.ListIterator; public class GFG { // Main driver method public static void main(String[] args) { // Create an ArrayList ArrayList<String> colors = new ArrayList<String>(); // Add elements to above ArrayList colors.add("Red"); colors.add("White"); colors.add("Blue"); colors.add("Pink"); colors.add("Black"); colors.add("Green"); // ArrayList ={Red, White, Blue, Pink, Black, Green} ListIterator<String> listIterator = colors.listIterator(); System.out.println("List Before remove() method = " + colors); // Removing ith element from ArrayList // using listiterator // Suppose i = 3, so traversing // till that element for (int i = 0; i < 3; i++) { listIterator.next(); } // Removes one more element from list // 'blue' element is removed from arraylist listIterator.remove(); // Printing the final ArrayList after removing // elements from originally created ArrayList System.out.println("List After remove() method = " + colors); }}
List Before remove() method = [Red, White, Blue, Pink, Black, Green]
List After remove() method = [Red, White, Pink, Black, Green]
Case 2: If the element to be removed is known
Iterator/traverse over the ArrayList and increment the list Iterator. If we reached the required element then break the loop else we reach the end and nothing will be deleted.
Java
// Java Program to Remove an element from ArrayList// using ListIterator // Importing ArrayList and ListIterator classes// of java.util packageimport java.util.ArrayList;import java.util.ListIterator; public class GFG { // Main driver method public static void main(String[] args) { // Create an ArrayList ArrayList<String> colors = new ArrayList<String>(); // Adding elements to the arraylist colors.add("Red"); colors.add("White"); colors.add("Blue"); colors.add("Pink"); colors.add("Black"); colors.add("Green"); ListIterator<String> listIterator = colors.listIterator(); // Print the original ArrayList created System.out.println("List Before remove() :- " + colors); // we want to remove Blue element from the arraylist for (String it : colors) { listIterator.next(); // if we reached to required element break the // loop if (it == "Blue") break; } // remove color blue from arraylist listIterator.remove(); System.out.println("List After remove():- " + colors); }}
List Before remove() :- [Red, White, Blue, Pink, black, green]
List After remove():- [Red, White, Pink, black, green]
anikakapoor
varshagumber28
surinderdawra388
Java-ArrayList
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Hashtable in Java
Constructors in Java
Different ways of Reading a text file in Java
Comparator Interface in Java with Examples
Java Math random() method with Examples
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": 23557,
"s": 23529,
"text": "\n20 Dec, 2021"
},
{
"code": null,
"e": 23844,
"s": 23557,
"text": "ListIterator.remove() method removes the last element from the list that was returned by next() or previous() cursor positions. It can be called only once per call to next or previous. It can be made only if the operation — add(E) has not called after the last call to next or previous."
},
{
"code": null,
"e": 24012,
"s": 23844,
"text": "Internal working in ArrayList is shown below be its removal or addition of elements to it. Considering generic removal of elements prior to the switch to ListIterator."
},
{
"code": null,
"e": 24020,
"s": 24012,
"text": "Syntax:"
},
{
"code": null,
"e": 24043,
"s": 24020,
"text": "listIterator.remove();"
},
{
"code": null,
"e": 24088,
"s": 24043,
"text": "Index to be removedIndex value to be removed"
},
{
"code": null,
"e": 24108,
"s": 24088,
"text": "Index to be removed"
},
{
"code": null,
"e": 24134,
"s": 24108,
"text": "Index value to be removed"
},
{
"code": null,
"e": 24148,
"s": 24134,
"text": "Illustration:"
},
{
"code": null,
"e": 24204,
"s": 24148,
"text": "Input: ArrayList = [“Red”, “White”, “Blue”, “Pink”]"
},
{
"code": null,
"e": 24248,
"s": 24204,
"text": "Output: ArrayList = [“Red”, “Blue”, “Pink”]"
},
{
"code": null,
"e": 24304,
"s": 24248,
"text": "Remove element “White” or 2nd element in the ArrayList."
},
{
"code": null,
"e": 24360,
"s": 24304,
"text": "Input: ArrayList = [“Red”, “White”, “Blue”, “Pink”]"
},
{
"code": null,
"e": 24414,
"s": 24360,
"text": "Output : ArrayList = [“Red”, “White”, “Blue”, “Pink”]"
},
{
"code": null,
"e": 24563,
"s": 24414,
"text": "Remove element “Black” or 5th element in the ArrayList. Since the element that has to be removed is not in the ArrayList so nothing will be removed."
},
{
"code": null,
"e": 24644,
"s": 24563,
"text": "Procedure: To Remove an element from ArrayList using ListIterator is as follows:"
},
{
"code": null,
"e": 25081,
"s": 24644,
"text": "Create ArrayList instance new ArrayList<String>();Add elements in ArrayList colors using colors.add(“Red”);Create ListIterator instance of colors.listIterator();Print list elements before removing elements.Increment the iterator by listIterator.next() and move to element which you want to remove;Remove the element by listIterator.remove();Print the list after removing the element. In this example, we have removed the element “White."
},
{
"code": null,
"e": 25132,
"s": 25081,
"text": "Create ArrayList instance new ArrayList<String>();"
},
{
"code": null,
"e": 25190,
"s": 25132,
"text": "Add elements in ArrayList colors using colors.add(“Red”);"
},
{
"code": null,
"e": 25245,
"s": 25190,
"text": "Create ListIterator instance of colors.listIterator();"
},
{
"code": null,
"e": 25291,
"s": 25245,
"text": "Print list elements before removing elements."
},
{
"code": null,
"e": 25383,
"s": 25291,
"text": "Increment the iterator by listIterator.next() and move to element which you want to remove;"
},
{
"code": null,
"e": 25428,
"s": 25383,
"text": "Remove the element by listIterator.remove();"
},
{
"code": null,
"e": 25524,
"s": 25428,
"text": "Print the list after removing the element. In this example, we have removed the element “White."
},
{
"code": null,
"e": 25584,
"s": 25524,
"text": "State transactions while deleting an element from ArrayList"
},
{
"code": null,
"e": 25656,
"s": 25584,
"text": "Case 1: Using loops if the index of the element to be removed is known "
},
{
"code": null,
"e": 25661,
"s": 25656,
"text": "Java"
},
{
"code": "// Java Program to Remove an element from ArrayList// using ListIterator // Importing ArrayList and ListIterator classes// of java.util packageimport java.util.ArrayList;import java.util.ListIterator; public class GFG { // Main driver method public static void main(String[] args) { // Create an ArrayList ArrayList<String> colors = new ArrayList<String>(); // Add elements to above ArrayList colors.add(\"Red\"); colors.add(\"White\"); colors.add(\"Blue\"); colors.add(\"Pink\"); colors.add(\"Black\"); colors.add(\"Green\"); // ArrayList ={Red, White, Blue, Pink, Black, Green} ListIterator<String> listIterator = colors.listIterator(); System.out.println(\"List Before remove() method = \" + colors); // Removing ith element from ArrayList // using listiterator // Suppose i = 3, so traversing // till that element for (int i = 0; i < 3; i++) { listIterator.next(); } // Removes one more element from list // 'blue' element is removed from arraylist listIterator.remove(); // Printing the final ArrayList after removing // elements from originally created ArrayList System.out.println(\"List After remove() method = \" + colors); }}",
"e": 27046,
"s": 25661,
"text": null
},
{
"code": null,
"e": 27178,
"s": 27046,
"text": "List Before remove() method = [Red, White, Blue, Pink, Black, Green]\nList After remove() method = [Red, White, Pink, Black, Green]"
},
{
"code": null,
"e": 27224,
"s": 27178,
"text": "Case 2: If the element to be removed is known"
},
{
"code": null,
"e": 27401,
"s": 27224,
"text": "Iterator/traverse over the ArrayList and increment the list Iterator. If we reached the required element then break the loop else we reach the end and nothing will be deleted. "
},
{
"code": null,
"e": 27406,
"s": 27401,
"text": "Java"
},
{
"code": "// Java Program to Remove an element from ArrayList// using ListIterator // Importing ArrayList and ListIterator classes// of java.util packageimport java.util.ArrayList;import java.util.ListIterator; public class GFG { // Main driver method public static void main(String[] args) { // Create an ArrayList ArrayList<String> colors = new ArrayList<String>(); // Adding elements to the arraylist colors.add(\"Red\"); colors.add(\"White\"); colors.add(\"Blue\"); colors.add(\"Pink\"); colors.add(\"Black\"); colors.add(\"Green\"); ListIterator<String> listIterator = colors.listIterator(); // Print the original ArrayList created System.out.println(\"List Before remove() :- \" + colors); // we want to remove Blue element from the arraylist for (String it : colors) { listIterator.next(); // if we reached to required element break the // loop if (it == \"Blue\") break; } // remove color blue from arraylist listIterator.remove(); System.out.println(\"List After remove():- \" + colors); }}",
"e": 28646,
"s": 27406,
"text": null
},
{
"code": null,
"e": 28764,
"s": 28646,
"text": "List Before remove() :- [Red, White, Blue, Pink, black, green]\nList After remove():- [Red, White, Pink, black, green]"
},
{
"code": null,
"e": 28778,
"s": 28766,
"text": "anikakapoor"
},
{
"code": null,
"e": 28793,
"s": 28778,
"text": "varshagumber28"
},
{
"code": null,
"e": 28810,
"s": 28793,
"text": "surinderdawra388"
},
{
"code": null,
"e": 28825,
"s": 28810,
"text": "Java-ArrayList"
},
{
"code": null,
"e": 28832,
"s": 28825,
"text": "Picked"
},
{
"code": null,
"e": 28837,
"s": 28832,
"text": "Java"
},
{
"code": null,
"e": 28851,
"s": 28837,
"text": "Java Programs"
},
{
"code": null,
"e": 28856,
"s": 28851,
"text": "Java"
},
{
"code": null,
"e": 28954,
"s": 28856,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28963,
"s": 28954,
"text": "Comments"
},
{
"code": null,
"e": 28976,
"s": 28963,
"text": "Old Comments"
},
{
"code": null,
"e": 28994,
"s": 28976,
"text": "Hashtable in Java"
},
{
"code": null,
"e": 29015,
"s": 28994,
"text": "Constructors in Java"
},
{
"code": null,
"e": 29061,
"s": 29015,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 29104,
"s": 29061,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 29144,
"s": 29104,
"text": "Java Math random() method with Examples"
},
{
"code": null,
"e": 29188,
"s": 29144,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 29214,
"s": 29188,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 29248,
"s": 29214,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 29295,
"s": 29248,
"text": "Implementing a Linked List in Java using Class"
}
] |
Building Face Recognition Model Under 30 Minutes | by Parth Rajesh Dedhia | Towards Data Science | In this blog post, I am going to give a walk-through of some implementation details of the face recognition model. I have also designed a browser-based UI for adding a new person to the database. Explaining the web-development part is out of the scope for this blog.
This post assumes an understanding of the Siamese Network model and Triplet Loss function. If you prefer to run the model first, then you can clone it from my repository here.
This blog post is structured as follows:
Model Architecture
Dataset
Triplet Generation
Miscellaneous Details
Conclusion
We all know that training a Convolution Neural Network(CNN) from scratch takes a lot of data and also compute power. So we instead use transfer learning, where a model trained on similar data is fine-tuned as per our requirement. The Visual Geometry Group (VGG) at Oxford has built three models — VGG-16, ResNet-50, and SeNet-50 trained for face recognition as well as for face classification. I have used the VGG-16 model as it is a smaller model and the prediction in real-time can work on my local system without GPU.
Note: To avoid confusion between the VGG-16 Deep Learning model and Oxford’s Visual Geometry Group (VGG), I will be calling the later as the Oxford group.
This implementation has the entire model in Keras with TensorFlow v1.14 as backend. I had planned to build the same in TensorFlow v2.3, so I created a virtualenv in my local system and extracted the model weights. These extracted weights were stored in vgg_face_weights.h5 and later loaded them on an untrained VGG-16 (in TensorFlow v2.3) network shown in this paper. If you wish to use ResNet-50 or SeNet-50 then you can use Refik Can Malli’s repository to obtain the model and the weights.
The VGG-16 model was trained on the dataset shown in this paper, where they had trained the classification model on 2622 different faces. The second to last layer has 4096 Dense Units, to which we append a 128 unit Dense layer, without the bias term, and remove the classification/softmax layer containing 2622 units. All the layers before the 128 Dense layer are frozen (trainable = False) and only the newly added dense layer needs to be trained.
Now for training this network, we use a Triplet Loss function. The triplet loss function takes three, 128-D features generated from the above network. Let these three be known as an anchor, a positive, and a negative where
Anchor: An image of a person that will be used for comparison.
Positive: An image of the same person as that of the anchor.
Negative: An image of a different person than the anchor.
Triplet loss tries to reduce the distance between the anchor and the positive pair and increase the distance between the anchor and the negative pair. There is also another parameter alpha = 0.2 which adds a margin thus making the training harder and giving better convergence. The parameters — 128D dense unit and the loss function parameter alpha are selected based on the analysis show in this paper.
Let’s sum up until now!! The VGG-16 Network gives us 128D features for anchor, positive, and negative images, which are then fed to the Loss function.
Now for training, one option is to call the same model three times on each of the anchor, positive and negative image, and then give the value to the loss function. However, running them one after another would be a bad idea. So I have instead wrap them in a Siamese Network class that extends the tf.keras.Model and leave the parallelization to the TensorFlow. Also, there is one more thing added to the model, L2 Regularization is applied to the output of the 128D Dense layer.
I have added a function get_features to the SiameseNetwork class, which is just an optimization that will be useful during testing.
Great, we have built a model!! Now let’s check out the dataset for training.
The VGGFace dataset consisting of 2622 distinct celebrity images, is used for training the VGG-16 model used above. Later, the Oxford group also released the VGGFace2 consisting of 8631 celebrity images for training, and 500 of them in the testing, each of them are distinct. Since the training set is 39GB, I downloaded only the test set, which is 2BG, and trained the last dense layer.
While using a test set for training may sound counter-intuitive, but this is the test set concerning the model trained by them. As for me, I have used it as a training set and tested my model on my family members and my friends.
The pre-processing generally depends on the underlying model. So, for training and testing, the input images have to go through the same pre-processing that is defined by the VGG-16 model implemented by Oxford Group. Images input to the model first run through a face detector described in this paper and then sent to the preprocess_input function given here. In my implementation, I have used the frontal face detector provided by the dlib library and then sent the images to the preprocess_input function.
Note: The preprocess_input function defined by the here is different than the one used by VGG-16 trained on ImageNet. Hence the code for pre-processing, in my repository, is taken from pip installed VGGFace library.
Now, I will show the directory structure of the datasets as it becomes a way to optimize memory during training. Let’s first check out the downloaded dataset directory structure. In the directory structure below, each directory(n000001, n000009, etc.) is allotted to a celebrity for all its images.
.└── vggface2_test └── test ├── n000001 │ ├── 0001_01.jpg │ ├── 0002_01.jpg │ ├── 0003_01.jpg ... ├── n000009 │ ├── 0001_01.jpg │ ├── 0002_01.jpg │ ├── 0003_01.jpg ...(so on and so forth)
As mentioned above, we used the dlib’s frontal face detector to detect images containing faces and store them in a different folder called dataset. Below is the directory tree of the face detected images. This notebook has the implementation for the same.
.└── dataset └── list.txt └── images ├── n000001 │ ├── 0001_01.jpg │ ├── 0002_01.jpg │ ├── 0003_01.jpg ... ├── n000009 │ ├── 0001_01.jpg │ ├── 0002_01.jpg │ ├── 0003_01.jpg ...(so on and so forth)
The directory structure of the vggface_test and dataset is almost similar. But, the dataset directory may contain fewer images as some of the faces may not have been detected by the dlib’s detector. Also, there is a file list.txt in the dataset directory, which contains the data as follows directory-name/image-name for each image. This list.txt is used for memory optimization during training.
For training, a model requires three images — the anchor, the positive, and the negative image. The first idea on top of my mind is to generate all the possible pairs of triplets. This may seem to have given a lot of data, but the research literature suggests that it’s inefficient. So I have used a random number generator for selecting the anchor, the positive, and the negative pairs of images. I have used a Data Generator which yields data during the training loop. If you are not familiar with Data Generator, do refer to this blog.
Fun Fact: It took me more time to write the DataGenerator class than the model took to train.
__getitem__ is the most important function. However, to understand the same, let’s check the constructor and other methods as well.
__init__: The constructor takes the path to the dataset directory defined in the previous subsection. The constructor uses the list.txt to make a dictionary. This dictionary has the directory name as its key and a list of images in that directory as its value. It is here, and in the shuffling step, that the list.txt becomes an easy way for us to have a dataset overview, thus avoiding to load images for shuffling.
__getitem__: We get the names of the people from the above dictionary keys. For 1st batch, the first 32 (batch size) people images are used as anchors, and a different image, of the same person, is used as positives. A negative image, from any other directory, is selected for training. For all of the triplets, the anchors, the positive, and the negative images are chosen randomly. The next 32 people become the anchor for the next batch.
curate_dataset: Creates the dictionary explained in the __init__
on_epoch_end: On each epoch end, the order of people is shuffled, so that in the next epoch, the first 32 images are different than the one seen in the previous epoch.
get_image: The get image function uses the preprocess_input after resizing the image to (224 x 224) size.
__len__: This will return the number of batches that will define one epoch.
Done !!!
I have used a custom training loop with tqdm (you still get Keras to feel) and trained the model for 50 epochs. On colab, the training time for each epoch is 24 seconds, so yes, the training is pretty fast.
For testing, you can save images of your family, friends, and your own in a directory and also store the 128D features generated from the dense layer for each person. You can use the get_features() function, which is defined in the SiameseNetwork class here. Also, to save you some time, I have made a notebook Real-time-prediction.ipynb, which loads the model checkpoints and also provides instruction for collecting images for testing on the fly and predicting them on a webcam-video.
In the DataGenerator, all the images are not loaded in the memory, instead, their indexes for manipulation. If you have your GPU, then the details in this sub-section may be less relevant.
I initially thought that reading and writing operations from colab to drive shall be fast, but it turns out they became slower than my local system which even does not have a GPU. To solve this issue, compressed the dataset to dataset.7z and uploaded it to my drive. Then copied the zip file from my Google drive to colab’s space given per session, extracted there, and then used for training. Using colab’s space significantly increased the speed of the training process.
However, my tensorboard summaries, and model checkpoints, were stored to the drive, as they are accessed once every epoch and do not significantly reduce the performance.
I wanted to learn some web technologies like HTML, CSS, and Javascript. The best way to learn that was by making a small project. Hence, I have tried to develop a UI based tool for collecting data for testing as well as for prediction. Steps for running the same are explained in my repository.
In this blog, we have covered key details about fine-tuning an existing network and building a Siamese Network on them. The results of the current model are much better than expected, but we could also improve them by manually creating good triplets. One could also download the entire training dataset for training the model. Literature suggests that manually selecting a set of hard triplets will significantly decrease the training time and increase the rate of convergence of the model.
You can refer to my repository for trying the Browser-based Tool as well as checking out the notebooks for training. The tool can also detect multiple people!!
O. M. Parkhi, A. Vedaldi, A. Zisserman, Deep Face Recognition, British Machine Vision Conference, 2015.
Q. Cao, L. Shen, W. Xie, O. M. Parkhi, A. Zisserman, VGGFace2: A dataset for recognising face across pose and age, International Conference on Automatic Face and Gesture Recognition, 2018.
F. Schroff, D. Kalenichenko, J. Philbin, FaceNet: A Unified Embedding for Face Recognition and Clustering, CVPR, 2015.
G. Koch, R. Zemel, R. Salakhutdinov, Siamese Neural Networks for One-shot Image Recognition, ICML deep learning workshop. Vol. 2. 2015. | [
{
"code": null,
"e": 439,
"s": 172,
"text": "In this blog post, I am going to give a walk-through of some implementation details of the face recognition model. I have also designed a browser-based UI for adding a new person to the database. Explaining the web-development part is out of the scope for this blog."
},
{
"code": null,
"e": 615,
"s": 439,
"text": "This post assumes an understanding of the Siamese Network model and Triplet Loss function. If you prefer to run the model first, then you can clone it from my repository here."
},
{
"code": null,
"e": 656,
"s": 615,
"text": "This blog post is structured as follows:"
},
{
"code": null,
"e": 675,
"s": 656,
"text": "Model Architecture"
},
{
"code": null,
"e": 683,
"s": 675,
"text": "Dataset"
},
{
"code": null,
"e": 702,
"s": 683,
"text": "Triplet Generation"
},
{
"code": null,
"e": 724,
"s": 702,
"text": "Miscellaneous Details"
},
{
"code": null,
"e": 735,
"s": 724,
"text": "Conclusion"
},
{
"code": null,
"e": 1256,
"s": 735,
"text": "We all know that training a Convolution Neural Network(CNN) from scratch takes a lot of data and also compute power. So we instead use transfer learning, where a model trained on similar data is fine-tuned as per our requirement. The Visual Geometry Group (VGG) at Oxford has built three models — VGG-16, ResNet-50, and SeNet-50 trained for face recognition as well as for face classification. I have used the VGG-16 model as it is a smaller model and the prediction in real-time can work on my local system without GPU."
},
{
"code": null,
"e": 1411,
"s": 1256,
"text": "Note: To avoid confusion between the VGG-16 Deep Learning model and Oxford’s Visual Geometry Group (VGG), I will be calling the later as the Oxford group."
},
{
"code": null,
"e": 1903,
"s": 1411,
"text": "This implementation has the entire model in Keras with TensorFlow v1.14 as backend. I had planned to build the same in TensorFlow v2.3, so I created a virtualenv in my local system and extracted the model weights. These extracted weights were stored in vgg_face_weights.h5 and later loaded them on an untrained VGG-16 (in TensorFlow v2.3) network shown in this paper. If you wish to use ResNet-50 or SeNet-50 then you can use Refik Can Malli’s repository to obtain the model and the weights."
},
{
"code": null,
"e": 2352,
"s": 1903,
"text": "The VGG-16 model was trained on the dataset shown in this paper, where they had trained the classification model on 2622 different faces. The second to last layer has 4096 Dense Units, to which we append a 128 unit Dense layer, without the bias term, and remove the classification/softmax layer containing 2622 units. All the layers before the 128 Dense layer are frozen (trainable = False) and only the newly added dense layer needs to be trained."
},
{
"code": null,
"e": 2575,
"s": 2352,
"text": "Now for training this network, we use a Triplet Loss function. The triplet loss function takes three, 128-D features generated from the above network. Let these three be known as an anchor, a positive, and a negative where"
},
{
"code": null,
"e": 2638,
"s": 2575,
"text": "Anchor: An image of a person that will be used for comparison."
},
{
"code": null,
"e": 2699,
"s": 2638,
"text": "Positive: An image of the same person as that of the anchor."
},
{
"code": null,
"e": 2757,
"s": 2699,
"text": "Negative: An image of a different person than the anchor."
},
{
"code": null,
"e": 3161,
"s": 2757,
"text": "Triplet loss tries to reduce the distance between the anchor and the positive pair and increase the distance between the anchor and the negative pair. There is also another parameter alpha = 0.2 which adds a margin thus making the training harder and giving better convergence. The parameters — 128D dense unit and the loss function parameter alpha are selected based on the analysis show in this paper."
},
{
"code": null,
"e": 3312,
"s": 3161,
"text": "Let’s sum up until now!! The VGG-16 Network gives us 128D features for anchor, positive, and negative images, which are then fed to the Loss function."
},
{
"code": null,
"e": 3792,
"s": 3312,
"text": "Now for training, one option is to call the same model three times on each of the anchor, positive and negative image, and then give the value to the loss function. However, running them one after another would be a bad idea. So I have instead wrap them in a Siamese Network class that extends the tf.keras.Model and leave the parallelization to the TensorFlow. Also, there is one more thing added to the model, L2 Regularization is applied to the output of the 128D Dense layer."
},
{
"code": null,
"e": 3924,
"s": 3792,
"text": "I have added a function get_features to the SiameseNetwork class, which is just an optimization that will be useful during testing."
},
{
"code": null,
"e": 4001,
"s": 3924,
"text": "Great, we have built a model!! Now let’s check out the dataset for training."
},
{
"code": null,
"e": 4389,
"s": 4001,
"text": "The VGGFace dataset consisting of 2622 distinct celebrity images, is used for training the VGG-16 model used above. Later, the Oxford group also released the VGGFace2 consisting of 8631 celebrity images for training, and 500 of them in the testing, each of them are distinct. Since the training set is 39GB, I downloaded only the test set, which is 2BG, and trained the last dense layer."
},
{
"code": null,
"e": 4618,
"s": 4389,
"text": "While using a test set for training may sound counter-intuitive, but this is the test set concerning the model trained by them. As for me, I have used it as a training set and tested my model on my family members and my friends."
},
{
"code": null,
"e": 5126,
"s": 4618,
"text": "The pre-processing generally depends on the underlying model. So, for training and testing, the input images have to go through the same pre-processing that is defined by the VGG-16 model implemented by Oxford Group. Images input to the model first run through a face detector described in this paper and then sent to the preprocess_input function given here. In my implementation, I have used the frontal face detector provided by the dlib library and then sent the images to the preprocess_input function."
},
{
"code": null,
"e": 5342,
"s": 5126,
"text": "Note: The preprocess_input function defined by the here is different than the one used by VGG-16 trained on ImageNet. Hence the code for pre-processing, in my repository, is taken from pip installed VGGFace library."
},
{
"code": null,
"e": 5641,
"s": 5342,
"text": "Now, I will show the directory structure of the datasets as it becomes a way to optimize memory during training. Let’s first check out the downloaded dataset directory structure. In the directory structure below, each directory(n000001, n000009, etc.) is allotted to a celebrity for all its images."
},
{
"code": null,
"e": 5900,
"s": 5641,
"text": ".└── vggface2_test └── test ├── n000001 │ ├── 0001_01.jpg │ ├── 0002_01.jpg │ ├── 0003_01.jpg ... ├── n000009 │ ├── 0001_01.jpg │ ├── 0002_01.jpg │ ├── 0003_01.jpg ...(so on and so forth)"
},
{
"code": null,
"e": 6156,
"s": 5900,
"text": "As mentioned above, we used the dlib’s frontal face detector to detect images containing faces and store them in a different folder called dataset. Below is the directory tree of the face detected images. This notebook has the implementation for the same."
},
{
"code": null,
"e": 6427,
"s": 6156,
"text": ".└── dataset └── list.txt └── images ├── n000001 │ ├── 0001_01.jpg │ ├── 0002_01.jpg │ ├── 0003_01.jpg ... ├── n000009 │ ├── 0001_01.jpg │ ├── 0002_01.jpg │ ├── 0003_01.jpg ...(so on and so forth)"
},
{
"code": null,
"e": 6823,
"s": 6427,
"text": "The directory structure of the vggface_test and dataset is almost similar. But, the dataset directory may contain fewer images as some of the faces may not have been detected by the dlib’s detector. Also, there is a file list.txt in the dataset directory, which contains the data as follows directory-name/image-name for each image. This list.txt is used for memory optimization during training."
},
{
"code": null,
"e": 7362,
"s": 6823,
"text": "For training, a model requires three images — the anchor, the positive, and the negative image. The first idea on top of my mind is to generate all the possible pairs of triplets. This may seem to have given a lot of data, but the research literature suggests that it’s inefficient. So I have used a random number generator for selecting the anchor, the positive, and the negative pairs of images. I have used a Data Generator which yields data during the training loop. If you are not familiar with Data Generator, do refer to this blog."
},
{
"code": null,
"e": 7456,
"s": 7362,
"text": "Fun Fact: It took me more time to write the DataGenerator class than the model took to train."
},
{
"code": null,
"e": 7588,
"s": 7456,
"text": "__getitem__ is the most important function. However, to understand the same, let’s check the constructor and other methods as well."
},
{
"code": null,
"e": 8005,
"s": 7588,
"text": "__init__: The constructor takes the path to the dataset directory defined in the previous subsection. The constructor uses the list.txt to make a dictionary. This dictionary has the directory name as its key and a list of images in that directory as its value. It is here, and in the shuffling step, that the list.txt becomes an easy way for us to have a dataset overview, thus avoiding to load images for shuffling."
},
{
"code": null,
"e": 8446,
"s": 8005,
"text": "__getitem__: We get the names of the people from the above dictionary keys. For 1st batch, the first 32 (batch size) people images are used as anchors, and a different image, of the same person, is used as positives. A negative image, from any other directory, is selected for training. For all of the triplets, the anchors, the positive, and the negative images are chosen randomly. The next 32 people become the anchor for the next batch."
},
{
"code": null,
"e": 8511,
"s": 8446,
"text": "curate_dataset: Creates the dictionary explained in the __init__"
},
{
"code": null,
"e": 8679,
"s": 8511,
"text": "on_epoch_end: On each epoch end, the order of people is shuffled, so that in the next epoch, the first 32 images are different than the one seen in the previous epoch."
},
{
"code": null,
"e": 8785,
"s": 8679,
"text": "get_image: The get image function uses the preprocess_input after resizing the image to (224 x 224) size."
},
{
"code": null,
"e": 8861,
"s": 8785,
"text": "__len__: This will return the number of batches that will define one epoch."
},
{
"code": null,
"e": 8870,
"s": 8861,
"text": "Done !!!"
},
{
"code": null,
"e": 9077,
"s": 8870,
"text": "I have used a custom training loop with tqdm (you still get Keras to feel) and trained the model for 50 epochs. On colab, the training time for each epoch is 24 seconds, so yes, the training is pretty fast."
},
{
"code": null,
"e": 9564,
"s": 9077,
"text": "For testing, you can save images of your family, friends, and your own in a directory and also store the 128D features generated from the dense layer for each person. You can use the get_features() function, which is defined in the SiameseNetwork class here. Also, to save you some time, I have made a notebook Real-time-prediction.ipynb, which loads the model checkpoints and also provides instruction for collecting images for testing on the fly and predicting them on a webcam-video."
},
{
"code": null,
"e": 9753,
"s": 9564,
"text": "In the DataGenerator, all the images are not loaded in the memory, instead, their indexes for manipulation. If you have your GPU, then the details in this sub-section may be less relevant."
},
{
"code": null,
"e": 10226,
"s": 9753,
"text": "I initially thought that reading and writing operations from colab to drive shall be fast, but it turns out they became slower than my local system which even does not have a GPU. To solve this issue, compressed the dataset to dataset.7z and uploaded it to my drive. Then copied the zip file from my Google drive to colab’s space given per session, extracted there, and then used for training. Using colab’s space significantly increased the speed of the training process."
},
{
"code": null,
"e": 10397,
"s": 10226,
"text": "However, my tensorboard summaries, and model checkpoints, were stored to the drive, as they are accessed once every epoch and do not significantly reduce the performance."
},
{
"code": null,
"e": 10692,
"s": 10397,
"text": "I wanted to learn some web technologies like HTML, CSS, and Javascript. The best way to learn that was by making a small project. Hence, I have tried to develop a UI based tool for collecting data for testing as well as for prediction. Steps for running the same are explained in my repository."
},
{
"code": null,
"e": 11183,
"s": 10692,
"text": "In this blog, we have covered key details about fine-tuning an existing network and building a Siamese Network on them. The results of the current model are much better than expected, but we could also improve them by manually creating good triplets. One could also download the entire training dataset for training the model. Literature suggests that manually selecting a set of hard triplets will significantly decrease the training time and increase the rate of convergence of the model."
},
{
"code": null,
"e": 11343,
"s": 11183,
"text": "You can refer to my repository for trying the Browser-based Tool as well as checking out the notebooks for training. The tool can also detect multiple people!!"
},
{
"code": null,
"e": 11447,
"s": 11343,
"text": "O. M. Parkhi, A. Vedaldi, A. Zisserman, Deep Face Recognition, British Machine Vision Conference, 2015."
},
{
"code": null,
"e": 11636,
"s": 11447,
"text": "Q. Cao, L. Shen, W. Xie, O. M. Parkhi, A. Zisserman, VGGFace2: A dataset for recognising face across pose and age, International Conference on Automatic Face and Gesture Recognition, 2018."
},
{
"code": null,
"e": 11755,
"s": 11636,
"text": "F. Schroff, D. Kalenichenko, J. Philbin, FaceNet: A Unified Embedding for Face Recognition and Clustering, CVPR, 2015."
}
] |
Create AI for Your Own Board Game From Scratch — Preparation — Part 1 | by Haryo Akbarianto Wibowo | Towards Data Science | Hello everyone! This is my second article in medium about Artificial Intelligence (AI). I want to share to everyone about how the progress of my little project that I do on my free time. It is a board game that I come up with. EvoPawness (Temporary Name) is inspired from a chess game. It is a simple game. However, my aim in this series of articles is not primary to tell step on how to develop, designing a game effectively. Instead, it will be focused on how to create an environment for the input of AI algorithm. I won’t use game engine such as Unity or Unreal Engine. But, I hope that my code can help you design your board game with powerful AI whether you use Game Engine or not.
NOTE: This part don’t use deep learning yet, but it will cover fundamental basic AI on how to create AI environment that is used for adversarial search. This part will be focused on designing the game’s class. If you only want to see Artificial Intelligence in action, skip this part.
I’m sorry that I can’t cover the Deep Learning part yet. I’m afraid It will make my article very long and not interesting to read. I want to share my knowledge step by step. So I’ll write it on the later part.
This article is targeted for the one who is interested in AI and designing a game. If you are not one of them, of course you can still see this article (who tells you that you cant 😆). I hope that my writing skill will increase by publishing this article and the content benefits you 😄.
Who doesn’t love gaming? It is a activity that someone do to release boredom. Game is fun and can train our brain to think how to solve a problem, especially board games. Board game is a game of strategy played by moving pieces on the board. There are several board games such as checkers, chess, and monopoly that need two players or more to play. It requires a good strategy to beat your opponent. It takes time to formulate a good strategy on beating your opponent.
Nowadays, board game is played on the computer. It usually has an AI agent to let player practice the game. The AI has a strategy that will search the best move. Of course, the smarter the AI it is, the more enjoyment we feel on beating the AI. So, how about we make a powerful AI on our game that learn the good strategy itself. It will make the AI powerful enough to make the human enjoy the game or make him/her frustrated 😆. It has a nice feeling if your AI creation on your own game idea is enjoyed by people.
This article will be focused on how I create my own original board game idea the EvoPawness (Temporary Name). I haven’t checked whether my game is already exists or not. I think it hasn’t. The code will be focused on designing the basic class for the game ready to be an input of AI algorithm. Because I like Python, I will write it in Python language. Of course you can write it in your preferred game engine. If you want to implement it, you should understand on the flow on how to create the game described in this article. The environment is based on Peter Norvig’s Artificial Intelligence book.
Let’s go, let’s create the game!
This article will be written in the following order:
TechnologyGame’s Description and RuleTerm DefinitionOur pipeline or stepsDefine our gameImplementationConclusionAfterwords
Technology
Game’s Description and Rule
Term Definition
Our pipeline or steps
Define our game
Implementation
Conclusion
Afterwords
In the project of this article, we will be using these:
Python 3.6.5PyCharm IDE or preferred text editor such as Atom or Sublime (Optional).
Python 3.6.5
PyCharm IDE or preferred text editor such as Atom or Sublime (Optional).
No other library is needed at the moment. Later, in the upcoming article, we will use TensorFlow (or maybe PyTorch) to develop AI agent.
EvoPawness (Temporary Name) is a board game that I come up with. It’s a turn based game that is played by two players. The board has 9 x 9 tiles. Each players has 6 pawns on his/her side with different color (Black and White). Every players has 5 soldier pawns chess and 1 king. The objective of this game is to destroy the opponent’s king or all of enemy’s pawns.
Every pawn has attributes called HP (Health Point), ATK (Attack Point) and step. The HP indicates their ability to function or alive. ATK is an attributes to reduce the enemy by the set amount of ATK point. Step point indicates how many step can a pawn move based on their unique movement. There is also a pawn status which tell whether the pawn has been activated or not. If it’s not activated, it cannot move, attack, or evolve.
The soldier pawn can evolve into higher rank pawn. Soldier pawn can evolve into knight, rook, and bishop. Knight and Bishop can evolve into Queen. They will have different abilities. Here are the ability of each pawns:
Movement : Soldier can only move forward. The number of steps depend on step point. Can bypass opponent’s pawn.
HP, ATK, STEP : Default 3, 1, 1
Attack target and range : Same like the movement It can only attack forward depend on step point. The pawn won’t move from the original position.
Evolve : Can evolve into Knight, Rook, and Bishop
Note : Can move, evolve, and attack if the pawn has been activated
Movement : L shaped in every direction (like in chess version). The number of steps is fixed to 1 (ignore step points). Can bypass opponent’s pawn
HP, ATK, STEP : Point attributes (if HP, it will be current HP not the max HP) before evolving into knight is added with these points (0,4,0)
Attack target and range : Same like the movement. The pawn won’t move from the original position.
Evolve : Cannot evolve
Movement : can move forward, backward, left, right (like in chess). The number of steps is based on the step points. Can bypass opponent’s pawn
HP, ATK, STEP : Point attributes (if HP, it will be current HP not the max HP) before evolving into knight is added with these points (2,2,0)
Attack target and range : Same like the movement. The pawn won’t move from the original position.
Evolve : Evolve into Queen
Movement : Diagonal move in every direction (like in chess). The number of steps is based on the step points. Can bypass opponent’s pawn
HP, ATK, STEP : Point attributes (if HP, it will be current HP not the max HP) before evolving into knight is added with these points (2,1,1)
Attack target and range : Same like the movement. The pawn won’t move from the original position.
Evolve : Evolve into Queen
Movement : Diagonal move in every direction and can move forward, backward, left and right (like in chess). The number of steps is based on the step points. Can bypass opponent’s pawn
HP, ATK, STEP : Point attributes before (if HP, it will be current HP not the max HP) evolving into knight is added with these points (2,2,0)
Attack range : Same like the movement. The pawn won’t move from the original position.
Evolve : Cannot move
Movement : Cannot move
HP, ATK, STEP : Default (15,4,1)
Attack range and target: Attack like Queen with one range. The pawn won’t move from the original position.
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
Every players has a special power which requires “mana” to do it. “mana” is generated each turn by one (max 10). In the first turn, they will have 5 manas. It will be generated each turn by one. Here are the special power:
Activate a soldier pawn : Need 3 manas
Evolve a soldier pawn : Need 5 manas
Evolve a rook and bishop : Need 10 manas
And last, there is two ‘runes’ that spawn each one randomly. It will spawn randomly near each player’s zone. If the rune is approached by a pawn. The pawn can gain a bonus on one of their attributes (random). The bonuses are:
Increase HP by 2
Increase Step by 1
Increase ATK by 2
The rune can spawn on a pawn’s location. If it spawns on the pawn’s location, it will gain the bonus immediately. This rule will make the game non-deterministic. If we use algorithm that needs the game to be deterministic game, we will change this rule.
Each players can only choose one action every turn. They must choose to move the pawn or activate special power. If there are no action that can be done. The player must skip the turn.
Black Player will always move first. So in the first turn, it’s Black Player’s turn followed by White Player’s turn. They will take turn alternatively.
These rules can change depending on the AI algorithm that we use on the next part. I will tell you later if we need to change a particular part. I haven’t tested the game balance yet. So, don’t expect that the game will be balance. There might be a strategy that is overpowered (OP). We won’t discuss about the balance of the game. But if you think that this game is really unbalance, just tell me. I will change the game’s rule according to your statement.
That’s all of the rule of EvoPawness (Temporary Name). If you are wondering about the name, The “(Temporary Name)” is also the part of the name. I haven’t decided on the name of the game so it will be the temporary name.
Specifies how the game is set up at the start.
Return a set of legal moves in a state
A transition model, which will define the result of an action given a state.
Check the terminal status of the game. Return true if the game has ended, false otherwise
Defines the final numeric value for a game when it’s in the terminal state for a player. The numeric value formula is defined by us.
Defines an estimate of the expected utility numeric value from a given state for a player. This function is called when the game hasn’t ended.
Here’s our steps:
We have stated the description and rule of the game. We still need to define the game’s state, initial state, players, possible actions, result functions, terminal test, utility function, and evaluation function. Then we need to define our game’s elements or objects. Then we design the class diagram and implement it. Oh, I’ve skipped the action function. We will define it after initial state.
In this article, we will skip the utility function and evaluation function. We will define them in the next article.
In this section, we will define all the elements of the game that we must define. As written above, It’s based on Peter Norvig’s book. So let’s follow it:
We should define how we will represent the game’s state. Before we do that, we should decide what information should we save in the state. In this game, there are:
Format : Game’s object (attributes)
Turn CounterPlayers (mana, color)Pawns (hp, atk, position, active status, color player, step, dead)Kings (hp, atk, position, color player, step, dead)Runes (bonuses, position)
Turn Counter
Players (mana, color)
Pawns (hp, atk, position, active status, color player, step, dead)
Kings (hp, atk, position, color player, step, dead)
Runes (bonuses, position)
Okay, I think that’s all. Let’s think on how to represent them.
We will need a 2D list or array of pawns to keep the coordinate’s pawn and king’s position information of the game. It can make us easier to check the position of pawn. So we will write the position of our Pawns and Kings into a 2D list or array of pawns and kings.
We also need a list of players, pawns, runes and kings to keep track on each objects. It’s exhausting to loop our 2D array only to check the position of each objects.
Finally there is a turn counter. It will help us to decide which turn it is now. If the counter is divisible by 2, it’s white player turn, black player otherwise.
There might be a better representation than this. But I think this will be enough to represent our game.
Here is our initial state based on how we represent our state:
Where the List of pawns is the same with our 2D array board of pawns. All of the pawn status is inactive (status boolean is false)
There are two players, white player and black player. The player’s turn is decided by:If turn is even number, it’s white player turn. But if turn is odd number, it’s black player turn.
There are the action that can be done with each actors:
Players
If a player has 5 manas , he/she can evolve a soldier pawn into higher pawn (except queen and knight).
If a player has 3 manas, he/she can activate a soldier pawn.
If a player has 10 manas, he/she can evolve a rook or bishop pawn into queen.
Pawns
If possible, the pawns can move into the direction based on the type of pawns.
If the enemy pawns is in the range of attack, the pawns can attack the enemy’s pawn.
Kings
If the enemy pawns is in the range of attack, the ally’s king can attack the enemy’s pawn.
Pass
If there are no actions available, pass the turn.
All of the possible action will be appended into a list that will be returned by the function.
There are the results of our action
There are 3 actors that we must see:
Players
Player can evolve pawn by the cost of manas. It will change the pawn into higher type pawn. It will add the attributes
Player can activate pawn with the cost of manas. It will change status of pawn to active.
Pawns
Pawns can move based on the type. It will change the pawn’s position in our board array. If the pawn hit a rune, it will increase its attribute randomly (only one).
Pawns can attack the opponents pawn by reducing the HP based on the ATK point of the attacker.
Kings
Pawns can attack the opponents pawn by reducing the HP based on the ATK point of the attacker
Pass
Pass the turn.
After doing one of the above action, the turn is increased by one. If the turn is divisible by 5, it will spawn 2 random runes.
It checks whether the game end or not.
We will check each king’s dead attribute. If it’s true, then the function will return true. If not, we will check each player’s pawns.
If a player doesn’t have alive pawn, the function will return true, false otherwise.
We won’t formulate our evaluation or utility function here. It’s not needed in the current article.
Before we code, we need to design our class to make our code become more structured. We will need to design the relationship. We will do it in Model View Controller (MVC) Design Pattern.
All type of pawns will inherit Pawn abstract class. The state will have Rune, Player, and Pawn class. These are our model. The element that we’ve defined is in the game controller.
That’s it, the state will contains Runes, Players, and Pawns. Game Controller will be a bridge between View and State. The controller will generate all of our defined elements above. The State is our model that will be processed by GameController class.
The source code will be uploaded into my GitHub repository. We won’t discuss all of the code here. We will discuss on how to code based on our defined elements.
Here are the example on how I code the state:
It has all of the attributes that we have defined above.
Here’s the example how to define the initial state
Here’s the code to decide whose player is taking the turn.
class State: def get_player_turn(self): return self.turn % 2class GameController: def player(self, state): return state.get_player_turn()
Here’s the code to decide the possible action. I will show you the example on how to generate possible action.
It will return the player’s possible action. There are also the code of pawn’s possible action. But, I won’t show it here because it’s very long. The possible action will be returned via dict format where it contains pawn’s information and the player’s information. It will contain all the information about the action.
Here’s an example of using the possible action. It’s one of the player possible action (remember, player has two possible actions, promote and activate) :
'p1a4’: {‘action’: ‘activate’, ‘pawn_atk’: 1, ‘pawn_hp’: 3, ‘pawn_index’: 4, ‘pawn_step’: 1, ‘pawn_x’: 8, ‘pawn_y’: 1, ‘player_index’: 1}}
where ‘p1a4’ is an unique key to give identification to an unique action.
The controller will call that function.
class GameController:def get_possible_action(self,state): all_possible_action = self.combine_action(self.state.get_possible_action() + self.state._get_possible_action_pawn() + self.state._get_possible_action_king()) if len(all_possible_action.keys()) == 0: return [{'action': {'skip' : {'action': 'skip'}}}] return all_possible_action
Here’s the example of the result function
It will receive action input and the current state. For example, we want to activate a pawn of index 1, the function will receive this input:
{‘action’: ‘activate’, ‘pawn_atk’: 1, ‘pawn_hp’: 3, ‘pawn_index’: 4, ‘pawn_step’: 1, ‘pawn_x’: 8, ‘pawn_y’: 1, ‘player_index’: 1}
It will activate a pawn and return the new state. Be careful, we must be sure to copy our state first to avoid object reference (using deepcopy library).
The function will response to the method called by our controller.
Here’s the example how to check if the game has ended or not
The function will check the dead status of pawn and the king. It doesn’t tell us who the winner is. It will only check the terminal status of the game.
I haven’t created the GUI version yet. Currently, We can only play in the terminal or command prompt. It’s not comfortable to play in the terminal. Here’s the screenshot of how I play the game:
The state, possible actions will be the input of our view.
The code of our view will be placed in the GitHub repository.
We have created a new game from scratch. We’ve defined some of the elements ready to be an input for AI algorithm. We have defined the representation of the state, initial state, players function, result function, and terminal functions and write it with Python Programming Language.
I haven’t tested if the code works perfectly though. So, If anyone find bug, you can send notes here.
Thank you for reading my second article about Artificial Intelligence. I need some constructive feedback to make me better on writing and Artificial Intelligence. Go easy on me please 😆!
I just want to share my knowledge to the reader. It’s good to share knowledge as it can be helpful to someone in needs. I’m in the process of learning this field and want to share what I’ve learnt. It’s nice if someone tell me if there’s something wrong with this article.
The GitHub repository will be created tomorrow. I need to document the function first.
EDIT: Here’s the GitHub link
I hope that the GUI will be finished in the next article. It’s really uncomfortable to play in the terminal. If anyone want to contribute to create the GUI, I appreciate it 😃.
Forgive me for my inefficient code, I’ve tried to make the code readable, high cohesion and low coupling as possible. So any feedback is welcomed to fix the mess of my code.
If you want another article from me like this one, please clap this article 👏 👏p. It will boost my spirit to write my next article. I promise to make a better article about AI .
In the next article I will share a traditional algorithm about adversarial search. After that, we will move into creating the agent with Deep Neural Network.
See you on the next article!
Part 1 : Create AI for Your Own Board Game From Scratch — Preparation — Part 1
Part 2 : Create AI for Your Own Board Game From Scratch — Minimax — Part 2
Part 3 : Create AI for your Own Board Game From Scratch — AlphaZero-Part 3
www.merriam-webster.com
www.visual-paradigm.com
Russell, Stuart J., and Peter Norvig. Artificial Intelligence: a Modern Approach. Prentice-Hall, 2010. | [
{
"code": null,
"e": 860,
"s": 172,
"text": "Hello everyone! This is my second article in medium about Artificial Intelligence (AI). I want to share to everyone about how the progress of my little project that I do on my free time. It is a board game that I come up with. EvoPawness (Temporary Name) is inspired from a chess game. It is a simple game. However, my aim in this series of articles is not primary to tell step on how to develop, designing a game effectively. Instead, it will be focused on how to create an environment for the input of AI algorithm. I won’t use game engine such as Unity or Unreal Engine. But, I hope that my code can help you design your board game with powerful AI whether you use Game Engine or not."
},
{
"code": null,
"e": 1145,
"s": 860,
"text": "NOTE: This part don’t use deep learning yet, but it will cover fundamental basic AI on how to create AI environment that is used for adversarial search. This part will be focused on designing the game’s class. If you only want to see Artificial Intelligence in action, skip this part."
},
{
"code": null,
"e": 1355,
"s": 1145,
"text": "I’m sorry that I can’t cover the Deep Learning part yet. I’m afraid It will make my article very long and not interesting to read. I want to share my knowledge step by step. So I’ll write it on the later part."
},
{
"code": null,
"e": 1642,
"s": 1355,
"text": "This article is targeted for the one who is interested in AI and designing a game. If you are not one of them, of course you can still see this article (who tells you that you cant 😆). I hope that my writing skill will increase by publishing this article and the content benefits you 😄."
},
{
"code": null,
"e": 2111,
"s": 1642,
"text": "Who doesn’t love gaming? It is a activity that someone do to release boredom. Game is fun and can train our brain to think how to solve a problem, especially board games. Board game is a game of strategy played by moving pieces on the board. There are several board games such as checkers, chess, and monopoly that need two players or more to play. It requires a good strategy to beat your opponent. It takes time to formulate a good strategy on beating your opponent."
},
{
"code": null,
"e": 2626,
"s": 2111,
"text": "Nowadays, board game is played on the computer. It usually has an AI agent to let player practice the game. The AI has a strategy that will search the best move. Of course, the smarter the AI it is, the more enjoyment we feel on beating the AI. So, how about we make a powerful AI on our game that learn the good strategy itself. It will make the AI powerful enough to make the human enjoy the game or make him/her frustrated 😆. It has a nice feeling if your AI creation on your own game idea is enjoyed by people."
},
{
"code": null,
"e": 3226,
"s": 2626,
"text": "This article will be focused on how I create my own original board game idea the EvoPawness (Temporary Name). I haven’t checked whether my game is already exists or not. I think it hasn’t. The code will be focused on designing the basic class for the game ready to be an input of AI algorithm. Because I like Python, I will write it in Python language. Of course you can write it in your preferred game engine. If you want to implement it, you should understand on the flow on how to create the game described in this article. The environment is based on Peter Norvig’s Artificial Intelligence book."
},
{
"code": null,
"e": 3259,
"s": 3226,
"text": "Let’s go, let’s create the game!"
},
{
"code": null,
"e": 3312,
"s": 3259,
"text": "This article will be written in the following order:"
},
{
"code": null,
"e": 3435,
"s": 3312,
"text": "TechnologyGame’s Description and RuleTerm DefinitionOur pipeline or stepsDefine our gameImplementationConclusionAfterwords"
},
{
"code": null,
"e": 3446,
"s": 3435,
"text": "Technology"
},
{
"code": null,
"e": 3474,
"s": 3446,
"text": "Game’s Description and Rule"
},
{
"code": null,
"e": 3490,
"s": 3474,
"text": "Term Definition"
},
{
"code": null,
"e": 3512,
"s": 3490,
"text": "Our pipeline or steps"
},
{
"code": null,
"e": 3528,
"s": 3512,
"text": "Define our game"
},
{
"code": null,
"e": 3543,
"s": 3528,
"text": "Implementation"
},
{
"code": null,
"e": 3554,
"s": 3543,
"text": "Conclusion"
},
{
"code": null,
"e": 3565,
"s": 3554,
"text": "Afterwords"
},
{
"code": null,
"e": 3621,
"s": 3565,
"text": "In the project of this article, we will be using these:"
},
{
"code": null,
"e": 3706,
"s": 3621,
"text": "Python 3.6.5PyCharm IDE or preferred text editor such as Atom or Sublime (Optional)."
},
{
"code": null,
"e": 3719,
"s": 3706,
"text": "Python 3.6.5"
},
{
"code": null,
"e": 3792,
"s": 3719,
"text": "PyCharm IDE or preferred text editor such as Atom or Sublime (Optional)."
},
{
"code": null,
"e": 3929,
"s": 3792,
"text": "No other library is needed at the moment. Later, in the upcoming article, we will use TensorFlow (or maybe PyTorch) to develop AI agent."
},
{
"code": null,
"e": 4294,
"s": 3929,
"text": "EvoPawness (Temporary Name) is a board game that I come up with. It’s a turn based game that is played by two players. The board has 9 x 9 tiles. Each players has 6 pawns on his/her side with different color (Black and White). Every players has 5 soldier pawns chess and 1 king. The objective of this game is to destroy the opponent’s king or all of enemy’s pawns."
},
{
"code": null,
"e": 4725,
"s": 4294,
"text": "Every pawn has attributes called HP (Health Point), ATK (Attack Point) and step. The HP indicates their ability to function or alive. ATK is an attributes to reduce the enemy by the set amount of ATK point. Step point indicates how many step can a pawn move based on their unique movement. There is also a pawn status which tell whether the pawn has been activated or not. If it’s not activated, it cannot move, attack, or evolve."
},
{
"code": null,
"e": 4944,
"s": 4725,
"text": "The soldier pawn can evolve into higher rank pawn. Soldier pawn can evolve into knight, rook, and bishop. Knight and Bishop can evolve into Queen. They will have different abilities. Here are the ability of each pawns:"
},
{
"code": null,
"e": 5056,
"s": 4944,
"text": "Movement : Soldier can only move forward. The number of steps depend on step point. Can bypass opponent’s pawn."
},
{
"code": null,
"e": 5088,
"s": 5056,
"text": "HP, ATK, STEP : Default 3, 1, 1"
},
{
"code": null,
"e": 5234,
"s": 5088,
"text": "Attack target and range : Same like the movement It can only attack forward depend on step point. The pawn won’t move from the original position."
},
{
"code": null,
"e": 5284,
"s": 5234,
"text": "Evolve : Can evolve into Knight, Rook, and Bishop"
},
{
"code": null,
"e": 5351,
"s": 5284,
"text": "Note : Can move, evolve, and attack if the pawn has been activated"
},
{
"code": null,
"e": 5498,
"s": 5351,
"text": "Movement : L shaped in every direction (like in chess version). The number of steps is fixed to 1 (ignore step points). Can bypass opponent’s pawn"
},
{
"code": null,
"e": 5640,
"s": 5498,
"text": "HP, ATK, STEP : Point attributes (if HP, it will be current HP not the max HP) before evolving into knight is added with these points (0,4,0)"
},
{
"code": null,
"e": 5738,
"s": 5640,
"text": "Attack target and range : Same like the movement. The pawn won’t move from the original position."
},
{
"code": null,
"e": 5761,
"s": 5738,
"text": "Evolve : Cannot evolve"
},
{
"code": null,
"e": 5905,
"s": 5761,
"text": "Movement : can move forward, backward, left, right (like in chess). The number of steps is based on the step points. Can bypass opponent’s pawn"
},
{
"code": null,
"e": 6047,
"s": 5905,
"text": "HP, ATK, STEP : Point attributes (if HP, it will be current HP not the max HP) before evolving into knight is added with these points (2,2,0)"
},
{
"code": null,
"e": 6145,
"s": 6047,
"text": "Attack target and range : Same like the movement. The pawn won’t move from the original position."
},
{
"code": null,
"e": 6172,
"s": 6145,
"text": "Evolve : Evolve into Queen"
},
{
"code": null,
"e": 6309,
"s": 6172,
"text": "Movement : Diagonal move in every direction (like in chess). The number of steps is based on the step points. Can bypass opponent’s pawn"
},
{
"code": null,
"e": 6451,
"s": 6309,
"text": "HP, ATK, STEP : Point attributes (if HP, it will be current HP not the max HP) before evolving into knight is added with these points (2,1,1)"
},
{
"code": null,
"e": 6549,
"s": 6451,
"text": "Attack target and range : Same like the movement. The pawn won’t move from the original position."
},
{
"code": null,
"e": 6576,
"s": 6549,
"text": "Evolve : Evolve into Queen"
},
{
"code": null,
"e": 6760,
"s": 6576,
"text": "Movement : Diagonal move in every direction and can move forward, backward, left and right (like in chess). The number of steps is based on the step points. Can bypass opponent’s pawn"
},
{
"code": null,
"e": 6902,
"s": 6760,
"text": "HP, ATK, STEP : Point attributes before (if HP, it will be current HP not the max HP) evolving into knight is added with these points (2,2,0)"
},
{
"code": null,
"e": 6989,
"s": 6902,
"text": "Attack range : Same like the movement. The pawn won’t move from the original position."
},
{
"code": null,
"e": 7010,
"s": 6989,
"text": "Evolve : Cannot move"
},
{
"code": null,
"e": 7033,
"s": 7010,
"text": "Movement : Cannot move"
},
{
"code": null,
"e": 7066,
"s": 7033,
"text": "HP, ATK, STEP : Default (15,4,1)"
},
{
"code": null,
"e": 7173,
"s": 7066,
"text": "Attack range and target: Attack like Queen with one range. The pawn won’t move from the original position."
},
{
"code": null,
"e": 7233,
"s": 7173,
"text": "— — — — — — — — — — — — — — — — — — — — — — — — — — — — — —"
},
{
"code": null,
"e": 7456,
"s": 7233,
"text": "Every players has a special power which requires “mana” to do it. “mana” is generated each turn by one (max 10). In the first turn, they will have 5 manas. It will be generated each turn by one. Here are the special power:"
},
{
"code": null,
"e": 7495,
"s": 7456,
"text": "Activate a soldier pawn : Need 3 manas"
},
{
"code": null,
"e": 7532,
"s": 7495,
"text": "Evolve a soldier pawn : Need 5 manas"
},
{
"code": null,
"e": 7573,
"s": 7532,
"text": "Evolve a rook and bishop : Need 10 manas"
},
{
"code": null,
"e": 7799,
"s": 7573,
"text": "And last, there is two ‘runes’ that spawn each one randomly. It will spawn randomly near each player’s zone. If the rune is approached by a pawn. The pawn can gain a bonus on one of their attributes (random). The bonuses are:"
},
{
"code": null,
"e": 7816,
"s": 7799,
"text": "Increase HP by 2"
},
{
"code": null,
"e": 7835,
"s": 7816,
"text": "Increase Step by 1"
},
{
"code": null,
"e": 7853,
"s": 7835,
"text": "Increase ATK by 2"
},
{
"code": null,
"e": 8107,
"s": 7853,
"text": "The rune can spawn on a pawn’s location. If it spawns on the pawn’s location, it will gain the bonus immediately. This rule will make the game non-deterministic. If we use algorithm that needs the game to be deterministic game, we will change this rule."
},
{
"code": null,
"e": 8292,
"s": 8107,
"text": "Each players can only choose one action every turn. They must choose to move the pawn or activate special power. If there are no action that can be done. The player must skip the turn."
},
{
"code": null,
"e": 8444,
"s": 8292,
"text": "Black Player will always move first. So in the first turn, it’s Black Player’s turn followed by White Player’s turn. They will take turn alternatively."
},
{
"code": null,
"e": 8902,
"s": 8444,
"text": "These rules can change depending on the AI algorithm that we use on the next part. I will tell you later if we need to change a particular part. I haven’t tested the game balance yet. So, don’t expect that the game will be balance. There might be a strategy that is overpowered (OP). We won’t discuss about the balance of the game. But if you think that this game is really unbalance, just tell me. I will change the game’s rule according to your statement."
},
{
"code": null,
"e": 9123,
"s": 8902,
"text": "That’s all of the rule of EvoPawness (Temporary Name). If you are wondering about the name, The “(Temporary Name)” is also the part of the name. I haven’t decided on the name of the game so it will be the temporary name."
},
{
"code": null,
"e": 9170,
"s": 9123,
"text": "Specifies how the game is set up at the start."
},
{
"code": null,
"e": 9209,
"s": 9170,
"text": "Return a set of legal moves in a state"
},
{
"code": null,
"e": 9286,
"s": 9209,
"text": "A transition model, which will define the result of an action given a state."
},
{
"code": null,
"e": 9376,
"s": 9286,
"text": "Check the terminal status of the game. Return true if the game has ended, false otherwise"
},
{
"code": null,
"e": 9509,
"s": 9376,
"text": "Defines the final numeric value for a game when it’s in the terminal state for a player. The numeric value formula is defined by us."
},
{
"code": null,
"e": 9652,
"s": 9509,
"text": "Defines an estimate of the expected utility numeric value from a given state for a player. This function is called when the game hasn’t ended."
},
{
"code": null,
"e": 9670,
"s": 9652,
"text": "Here’s our steps:"
},
{
"code": null,
"e": 10066,
"s": 9670,
"text": "We have stated the description and rule of the game. We still need to define the game’s state, initial state, players, possible actions, result functions, terminal test, utility function, and evaluation function. Then we need to define our game’s elements or objects. Then we design the class diagram and implement it. Oh, I’ve skipped the action function. We will define it after initial state."
},
{
"code": null,
"e": 10183,
"s": 10066,
"text": "In this article, we will skip the utility function and evaluation function. We will define them in the next article."
},
{
"code": null,
"e": 10338,
"s": 10183,
"text": "In this section, we will define all the elements of the game that we must define. As written above, It’s based on Peter Norvig’s book. So let’s follow it:"
},
{
"code": null,
"e": 10502,
"s": 10338,
"text": "We should define how we will represent the game’s state. Before we do that, we should decide what information should we save in the state. In this game, there are:"
},
{
"code": null,
"e": 10538,
"s": 10502,
"text": "Format : Game’s object (attributes)"
},
{
"code": null,
"e": 10714,
"s": 10538,
"text": "Turn CounterPlayers (mana, color)Pawns (hp, atk, position, active status, color player, step, dead)Kings (hp, atk, position, color player, step, dead)Runes (bonuses, position)"
},
{
"code": null,
"e": 10727,
"s": 10714,
"text": "Turn Counter"
},
{
"code": null,
"e": 10749,
"s": 10727,
"text": "Players (mana, color)"
},
{
"code": null,
"e": 10816,
"s": 10749,
"text": "Pawns (hp, atk, position, active status, color player, step, dead)"
},
{
"code": null,
"e": 10868,
"s": 10816,
"text": "Kings (hp, atk, position, color player, step, dead)"
},
{
"code": null,
"e": 10894,
"s": 10868,
"text": "Runes (bonuses, position)"
},
{
"code": null,
"e": 10958,
"s": 10894,
"text": "Okay, I think that’s all. Let’s think on how to represent them."
},
{
"code": null,
"e": 11224,
"s": 10958,
"text": "We will need a 2D list or array of pawns to keep the coordinate’s pawn and king’s position information of the game. It can make us easier to check the position of pawn. So we will write the position of our Pawns and Kings into a 2D list or array of pawns and kings."
},
{
"code": null,
"e": 11391,
"s": 11224,
"text": "We also need a list of players, pawns, runes and kings to keep track on each objects. It’s exhausting to loop our 2D array only to check the position of each objects."
},
{
"code": null,
"e": 11554,
"s": 11391,
"text": "Finally there is a turn counter. It will help us to decide which turn it is now. If the counter is divisible by 2, it’s white player turn, black player otherwise."
},
{
"code": null,
"e": 11659,
"s": 11554,
"text": "There might be a better representation than this. But I think this will be enough to represent our game."
},
{
"code": null,
"e": 11722,
"s": 11659,
"text": "Here is our initial state based on how we represent our state:"
},
{
"code": null,
"e": 11853,
"s": 11722,
"text": "Where the List of pawns is the same with our 2D array board of pawns. All of the pawn status is inactive (status boolean is false)"
},
{
"code": null,
"e": 12038,
"s": 11853,
"text": "There are two players, white player and black player. The player’s turn is decided by:If turn is even number, it’s white player turn. But if turn is odd number, it’s black player turn."
},
{
"code": null,
"e": 12094,
"s": 12038,
"text": "There are the action that can be done with each actors:"
},
{
"code": null,
"e": 12102,
"s": 12094,
"text": "Players"
},
{
"code": null,
"e": 12205,
"s": 12102,
"text": "If a player has 5 manas , he/she can evolve a soldier pawn into higher pawn (except queen and knight)."
},
{
"code": null,
"e": 12266,
"s": 12205,
"text": "If a player has 3 manas, he/she can activate a soldier pawn."
},
{
"code": null,
"e": 12344,
"s": 12266,
"text": "If a player has 10 manas, he/she can evolve a rook or bishop pawn into queen."
},
{
"code": null,
"e": 12350,
"s": 12344,
"text": "Pawns"
},
{
"code": null,
"e": 12429,
"s": 12350,
"text": "If possible, the pawns can move into the direction based on the type of pawns."
},
{
"code": null,
"e": 12514,
"s": 12429,
"text": "If the enemy pawns is in the range of attack, the pawns can attack the enemy’s pawn."
},
{
"code": null,
"e": 12520,
"s": 12514,
"text": "Kings"
},
{
"code": null,
"e": 12611,
"s": 12520,
"text": "If the enemy pawns is in the range of attack, the ally’s king can attack the enemy’s pawn."
},
{
"code": null,
"e": 12616,
"s": 12611,
"text": "Pass"
},
{
"code": null,
"e": 12666,
"s": 12616,
"text": "If there are no actions available, pass the turn."
},
{
"code": null,
"e": 12761,
"s": 12666,
"text": "All of the possible action will be appended into a list that will be returned by the function."
},
{
"code": null,
"e": 12797,
"s": 12761,
"text": "There are the results of our action"
},
{
"code": null,
"e": 12834,
"s": 12797,
"text": "There are 3 actors that we must see:"
},
{
"code": null,
"e": 12842,
"s": 12834,
"text": "Players"
},
{
"code": null,
"e": 12961,
"s": 12842,
"text": "Player can evolve pawn by the cost of manas. It will change the pawn into higher type pawn. It will add the attributes"
},
{
"code": null,
"e": 13051,
"s": 12961,
"text": "Player can activate pawn with the cost of manas. It will change status of pawn to active."
},
{
"code": null,
"e": 13057,
"s": 13051,
"text": "Pawns"
},
{
"code": null,
"e": 13222,
"s": 13057,
"text": "Pawns can move based on the type. It will change the pawn’s position in our board array. If the pawn hit a rune, it will increase its attribute randomly (only one)."
},
{
"code": null,
"e": 13317,
"s": 13222,
"text": "Pawns can attack the opponents pawn by reducing the HP based on the ATK point of the attacker."
},
{
"code": null,
"e": 13323,
"s": 13317,
"text": "Kings"
},
{
"code": null,
"e": 13417,
"s": 13323,
"text": "Pawns can attack the opponents pawn by reducing the HP based on the ATK point of the attacker"
},
{
"code": null,
"e": 13422,
"s": 13417,
"text": "Pass"
},
{
"code": null,
"e": 13437,
"s": 13422,
"text": "Pass the turn."
},
{
"code": null,
"e": 13565,
"s": 13437,
"text": "After doing one of the above action, the turn is increased by one. If the turn is divisible by 5, it will spawn 2 random runes."
},
{
"code": null,
"e": 13604,
"s": 13565,
"text": "It checks whether the game end or not."
},
{
"code": null,
"e": 13739,
"s": 13604,
"text": "We will check each king’s dead attribute. If it’s true, then the function will return true. If not, we will check each player’s pawns."
},
{
"code": null,
"e": 13824,
"s": 13739,
"text": "If a player doesn’t have alive pawn, the function will return true, false otherwise."
},
{
"code": null,
"e": 13924,
"s": 13824,
"text": "We won’t formulate our evaluation or utility function here. It’s not needed in the current article."
},
{
"code": null,
"e": 14111,
"s": 13924,
"text": "Before we code, we need to design our class to make our code become more structured. We will need to design the relationship. We will do it in Model View Controller (MVC) Design Pattern."
},
{
"code": null,
"e": 14292,
"s": 14111,
"text": "All type of pawns will inherit Pawn abstract class. The state will have Rune, Player, and Pawn class. These are our model. The element that we’ve defined is in the game controller."
},
{
"code": null,
"e": 14546,
"s": 14292,
"text": "That’s it, the state will contains Runes, Players, and Pawns. Game Controller will be a bridge between View and State. The controller will generate all of our defined elements above. The State is our model that will be processed by GameController class."
},
{
"code": null,
"e": 14707,
"s": 14546,
"text": "The source code will be uploaded into my GitHub repository. We won’t discuss all of the code here. We will discuss on how to code based on our defined elements."
},
{
"code": null,
"e": 14753,
"s": 14707,
"text": "Here are the example on how I code the state:"
},
{
"code": null,
"e": 14810,
"s": 14753,
"text": "It has all of the attributes that we have defined above."
},
{
"code": null,
"e": 14861,
"s": 14810,
"text": "Here’s the example how to define the initial state"
},
{
"code": null,
"e": 14920,
"s": 14861,
"text": "Here’s the code to decide whose player is taking the turn."
},
{
"code": null,
"e": 15065,
"s": 14920,
"text": "class State: def get_player_turn(self): return self.turn % 2class GameController: def player(self, state): return state.get_player_turn()"
},
{
"code": null,
"e": 15176,
"s": 15065,
"text": "Here’s the code to decide the possible action. I will show you the example on how to generate possible action."
},
{
"code": null,
"e": 15496,
"s": 15176,
"text": "It will return the player’s possible action. There are also the code of pawn’s possible action. But, I won’t show it here because it’s very long. The possible action will be returned via dict format where it contains pawn’s information and the player’s information. It will contain all the information about the action."
},
{
"code": null,
"e": 15651,
"s": 15496,
"text": "Here’s an example of using the possible action. It’s one of the player possible action (remember, player has two possible actions, promote and activate) :"
},
{
"code": null,
"e": 15790,
"s": 15651,
"text": "'p1a4’: {‘action’: ‘activate’, ‘pawn_atk’: 1, ‘pawn_hp’: 3, ‘pawn_index’: 4, ‘pawn_step’: 1, ‘pawn_x’: 8, ‘pawn_y’: 1, ‘player_index’: 1}}"
},
{
"code": null,
"e": 15864,
"s": 15790,
"text": "where ‘p1a4’ is an unique key to give identification to an unique action."
},
{
"code": null,
"e": 15904,
"s": 15864,
"text": "The controller will call that function."
},
{
"code": null,
"e": 16271,
"s": 15904,
"text": "class GameController:def get_possible_action(self,state): all_possible_action = self.combine_action(self.state.get_possible_action() + self.state._get_possible_action_pawn() + self.state._get_possible_action_king()) if len(all_possible_action.keys()) == 0: return [{'action': {'skip' : {'action': 'skip'}}}] return all_possible_action"
},
{
"code": null,
"e": 16313,
"s": 16271,
"text": "Here’s the example of the result function"
},
{
"code": null,
"e": 16455,
"s": 16313,
"text": "It will receive action input and the current state. For example, we want to activate a pawn of index 1, the function will receive this input:"
},
{
"code": null,
"e": 16585,
"s": 16455,
"text": "{‘action’: ‘activate’, ‘pawn_atk’: 1, ‘pawn_hp’: 3, ‘pawn_index’: 4, ‘pawn_step’: 1, ‘pawn_x’: 8, ‘pawn_y’: 1, ‘player_index’: 1}"
},
{
"code": null,
"e": 16739,
"s": 16585,
"text": "It will activate a pawn and return the new state. Be careful, we must be sure to copy our state first to avoid object reference (using deepcopy library)."
},
{
"code": null,
"e": 16806,
"s": 16739,
"text": "The function will response to the method called by our controller."
},
{
"code": null,
"e": 16867,
"s": 16806,
"text": "Here’s the example how to check if the game has ended or not"
},
{
"code": null,
"e": 17019,
"s": 16867,
"text": "The function will check the dead status of pawn and the king. It doesn’t tell us who the winner is. It will only check the terminal status of the game."
},
{
"code": null,
"e": 17213,
"s": 17019,
"text": "I haven’t created the GUI version yet. Currently, We can only play in the terminal or command prompt. It’s not comfortable to play in the terminal. Here’s the screenshot of how I play the game:"
},
{
"code": null,
"e": 17272,
"s": 17213,
"text": "The state, possible actions will be the input of our view."
},
{
"code": null,
"e": 17334,
"s": 17272,
"text": "The code of our view will be placed in the GitHub repository."
},
{
"code": null,
"e": 17618,
"s": 17334,
"text": "We have created a new game from scratch. We’ve defined some of the elements ready to be an input for AI algorithm. We have defined the representation of the state, initial state, players function, result function, and terminal functions and write it with Python Programming Language."
},
{
"code": null,
"e": 17720,
"s": 17618,
"text": "I haven’t tested if the code works perfectly though. So, If anyone find bug, you can send notes here."
},
{
"code": null,
"e": 17907,
"s": 17720,
"text": "Thank you for reading my second article about Artificial Intelligence. I need some constructive feedback to make me better on writing and Artificial Intelligence. Go easy on me please 😆!"
},
{
"code": null,
"e": 18180,
"s": 17907,
"text": "I just want to share my knowledge to the reader. It’s good to share knowledge as it can be helpful to someone in needs. I’m in the process of learning this field and want to share what I’ve learnt. It’s nice if someone tell me if there’s something wrong with this article."
},
{
"code": null,
"e": 18267,
"s": 18180,
"text": "The GitHub repository will be created tomorrow. I need to document the function first."
},
{
"code": null,
"e": 18296,
"s": 18267,
"text": "EDIT: Here’s the GitHub link"
},
{
"code": null,
"e": 18472,
"s": 18296,
"text": "I hope that the GUI will be finished in the next article. It’s really uncomfortable to play in the terminal. If anyone want to contribute to create the GUI, I appreciate it 😃."
},
{
"code": null,
"e": 18646,
"s": 18472,
"text": "Forgive me for my inefficient code, I’ve tried to make the code readable, high cohesion and low coupling as possible. So any feedback is welcomed to fix the mess of my code."
},
{
"code": null,
"e": 18824,
"s": 18646,
"text": "If you want another article from me like this one, please clap this article 👏 👏p. It will boost my spirit to write my next article. I promise to make a better article about AI ."
},
{
"code": null,
"e": 18982,
"s": 18824,
"text": "In the next article I will share a traditional algorithm about adversarial search. After that, we will move into creating the agent with Deep Neural Network."
},
{
"code": null,
"e": 19011,
"s": 18982,
"text": "See you on the next article!"
},
{
"code": null,
"e": 19090,
"s": 19011,
"text": "Part 1 : Create AI for Your Own Board Game From Scratch — Preparation — Part 1"
},
{
"code": null,
"e": 19165,
"s": 19090,
"text": "Part 2 : Create AI for Your Own Board Game From Scratch — Minimax — Part 2"
},
{
"code": null,
"e": 19240,
"s": 19165,
"text": "Part 3 : Create AI for your Own Board Game From Scratch — AlphaZero-Part 3"
},
{
"code": null,
"e": 19264,
"s": 19240,
"text": "www.merriam-webster.com"
},
{
"code": null,
"e": 19288,
"s": 19264,
"text": "www.visual-paradigm.com"
}
] |
How to write a jQuery selector for the label of a checkbox? | To write a jQuery selector for the label of a checkbox, use the for attribute of label element.
You can try to run the following code to learn how to write a jQuery selector for the label of a checkbox:
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("label[for='mysubjects1']").css("background-color", "yellow");
$("label[for='mysubjects2']").css("background-color", "gray");
});
</script>
</head>
<body>
<form>
<input type="checkbox" name="filter" id="sub1"/>
<label for="mysubjects1">Subjects</label><br>
<input type="checkbox" name="filter2" id="sub2"/>
<label for="mysubjects2">New Subjects</label>
</form>
</body>
</html> | [
{
"code": null,
"e": 1158,
"s": 1062,
"text": "To write a jQuery selector for the label of a checkbox, use the for attribute of label element."
},
{
"code": null,
"e": 1265,
"s": 1158,
"text": "You can try to run the following code to learn how to write a jQuery selector for the label of a checkbox:"
},
{
"code": null,
"e": 1275,
"s": 1265,
"text": "Live Demo"
},
{
"code": null,
"e": 1829,
"s": 1275,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n<script>\n$(document).ready(function(){\n\n $(\"label[for='mysubjects1']\").css(\"background-color\", \"yellow\");\n $(\"label[for='mysubjects2']\").css(\"background-color\", \"gray\");\n\n});\n</script>\n</head>\n<body>\n<form>\n <input type=\"checkbox\" name=\"filter\" id=\"sub1\"/>\n <label for=\"mysubjects1\">Subjects</label><br>\n <input type=\"checkbox\" name=\"filter2\" id=\"sub2\"/>\n <label for=\"mysubjects2\">New Subjects</label>\n</form>\n\n</body>\n</html>"
}
] |
DATE_ADD() Function in MySQL - GeeksforGeeks | 25 Nov, 2020
DATE_ADD() function in MySQL is used to add a specified time or date interval to a specified date and then return the date.
Syntax:
DATE_ADD(date, INTERVAL value addunit)
Parameter: This function accepts two parameters which are illustrated below:
date –Specified date to be modified.
value addunit –Here the value is the date or time interval to add. This value can be both positive and negative. And here the addunit is the type of interval to add such as SECOND, MINUTE, HOUR, DAY, YEAR, MONTH, etc.
Returns :
It returns the new date after the addition of a specified time or date.
Example 1:
Getting a new date of “2020-11-22” after the addition of 3 years to the specified date “2017-11-22”.
SELECT DATE_ADD("2017-11-22", INTERVAL 3 YEAR);
Output:
2020-11-22
Example 2:
Getting a new date of “2020-11-22” after the addition of 2 months to the specified date “2020-9-22”.
SELECT DATE_ADD("2020-9-22", INTERVAL 2 MONTH);
Output:
2020-11-22
Example 3:
Getting a new date of “2020-11-22” after the addition of 10 days to the specified date “2020-11-12”.
SELECT DATE_ADD("2020-11-12", INTERVAL 10 DAY);
Output:
2020-11-22
Example 4:
Getting a new date of “2020-11-22 09:12:10” after the addition of 3 hours to the specified date “2020-11-22 06:12:10”.
SELECT DATE_ADD("2020-11-22 06:12:10", INTERVAL 3 HOUR);
Output:
2020-11-22 09:12:10
Example 5:
Getting a new date of “2020-11-22 09:09:10” after the addition of 3 minutes to the specified date “2020-11-22 09:06:10”.
SELECT DATE_ADD("2020-11-22 09:06:10", INTERVAL 3 MINUTE);
Output:
2020-11-22 09:09:10
Example 6:
Getting a new date of “2020-11-22 09:09:10” after the addition of 5 seconds to the specified date “2020-11-22 09:09:5”.
SELECT DATE_ADD("2020-11-22 09:09:5", INTERVAL 5 SECOND);
Output:
2020-11-22 09:09:10
mysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
SQL Interview Questions
Difference between DELETE, DROP and TRUNCATE
MySQL | Group_CONCAT() Function
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL - ORDER BY
SQL using Python
MySQL | Regular expressions (Regexp) | [
{
"code": null,
"e": 23824,
"s": 23796,
"text": "\n25 Nov, 2020"
},
{
"code": null,
"e": 23948,
"s": 23824,
"text": "DATE_ADD() function in MySQL is used to add a specified time or date interval to a specified date and then return the date."
},
{
"code": null,
"e": 23956,
"s": 23948,
"text": "Syntax:"
},
{
"code": null,
"e": 23997,
"s": 23956,
"text": "DATE_ADD(date, INTERVAL value addunit)\n\n"
},
{
"code": null,
"e": 24074,
"s": 23997,
"text": "Parameter: This function accepts two parameters which are illustrated below:"
},
{
"code": null,
"e": 24111,
"s": 24074,
"text": "date –Specified date to be modified."
},
{
"code": null,
"e": 24329,
"s": 24111,
"text": "value addunit –Here the value is the date or time interval to add. This value can be both positive and negative. And here the addunit is the type of interval to add such as SECOND, MINUTE, HOUR, DAY, YEAR, MONTH, etc."
},
{
"code": null,
"e": 24339,
"s": 24329,
"text": "Returns :"
},
{
"code": null,
"e": 24411,
"s": 24339,
"text": "It returns the new date after the addition of a specified time or date."
},
{
"code": null,
"e": 24422,
"s": 24411,
"text": "Example 1:"
},
{
"code": null,
"e": 24523,
"s": 24422,
"text": "Getting a new date of “2020-11-22” after the addition of 3 years to the specified date “2017-11-22”."
},
{
"code": null,
"e": 24573,
"s": 24523,
"text": "SELECT DATE_ADD(\"2017-11-22\", INTERVAL 3 YEAR);\n\n"
},
{
"code": null,
"e": 24581,
"s": 24573,
"text": "Output:"
},
{
"code": null,
"e": 24594,
"s": 24581,
"text": "2020-11-22\n\n"
},
{
"code": null,
"e": 24605,
"s": 24594,
"text": "Example 2:"
},
{
"code": null,
"e": 24706,
"s": 24605,
"text": "Getting a new date of “2020-11-22” after the addition of 2 months to the specified date “2020-9-22”."
},
{
"code": null,
"e": 24756,
"s": 24706,
"text": "SELECT DATE_ADD(\"2020-9-22\", INTERVAL 2 MONTH);\n\n"
},
{
"code": null,
"e": 24764,
"s": 24756,
"text": "Output:"
},
{
"code": null,
"e": 24777,
"s": 24764,
"text": "2020-11-22\n\n"
},
{
"code": null,
"e": 24788,
"s": 24777,
"text": "Example 3:"
},
{
"code": null,
"e": 24889,
"s": 24788,
"text": "Getting a new date of “2020-11-22” after the addition of 10 days to the specified date “2020-11-12”."
},
{
"code": null,
"e": 24939,
"s": 24889,
"text": "SELECT DATE_ADD(\"2020-11-12\", INTERVAL 10 DAY);\n\n"
},
{
"code": null,
"e": 24947,
"s": 24939,
"text": "Output:"
},
{
"code": null,
"e": 24960,
"s": 24947,
"text": "2020-11-22\n\n"
},
{
"code": null,
"e": 24971,
"s": 24960,
"text": "Example 4:"
},
{
"code": null,
"e": 25090,
"s": 24971,
"text": "Getting a new date of “2020-11-22 09:12:10” after the addition of 3 hours to the specified date “2020-11-22 06:12:10”."
},
{
"code": null,
"e": 25149,
"s": 25090,
"text": "SELECT DATE_ADD(\"2020-11-22 06:12:10\", INTERVAL 3 HOUR);\n\n"
},
{
"code": null,
"e": 25157,
"s": 25149,
"text": "Output:"
},
{
"code": null,
"e": 25179,
"s": 25157,
"text": "2020-11-22 09:12:10\n\n"
},
{
"code": null,
"e": 25190,
"s": 25179,
"text": "Example 5:"
},
{
"code": null,
"e": 25311,
"s": 25190,
"text": "Getting a new date of “2020-11-22 09:09:10” after the addition of 3 minutes to the specified date “2020-11-22 09:06:10”."
},
{
"code": null,
"e": 25372,
"s": 25311,
"text": "SELECT DATE_ADD(\"2020-11-22 09:06:10\", INTERVAL 3 MINUTE);\n\n"
},
{
"code": null,
"e": 25380,
"s": 25372,
"text": "Output:"
},
{
"code": null,
"e": 25402,
"s": 25380,
"text": "2020-11-22 09:09:10\n\n"
},
{
"code": null,
"e": 25413,
"s": 25402,
"text": "Example 6:"
},
{
"code": null,
"e": 25533,
"s": 25413,
"text": "Getting a new date of “2020-11-22 09:09:10” after the addition of 5 seconds to the specified date “2020-11-22 09:09:5”."
},
{
"code": null,
"e": 25593,
"s": 25533,
"text": "SELECT DATE_ADD(\"2020-11-22 09:09:5\", INTERVAL 5 SECOND);\n\n"
},
{
"code": null,
"e": 25601,
"s": 25593,
"text": "Output:"
},
{
"code": null,
"e": 25623,
"s": 25601,
"text": "2020-11-22 09:09:10\n\n"
},
{
"code": null,
"e": 25629,
"s": 25623,
"text": "mysql"
},
{
"code": null,
"e": 25633,
"s": 25629,
"text": "SQL"
},
{
"code": null,
"e": 25637,
"s": 25633,
"text": "SQL"
},
{
"code": null,
"e": 25735,
"s": 25637,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25746,
"s": 25735,
"text": "CTE in SQL"
},
{
"code": null,
"e": 25812,
"s": 25746,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 25836,
"s": 25812,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 25881,
"s": 25836,
"text": "Difference between DELETE, DROP and TRUNCATE"
},
{
"code": null,
"e": 25913,
"s": 25881,
"text": "MySQL | Group_CONCAT() Function"
},
{
"code": null,
"e": 25945,
"s": 25913,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 26023,
"s": 25945,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 26038,
"s": 26023,
"text": "SQL - ORDER BY"
},
{
"code": null,
"e": 26055,
"s": 26038,
"text": "SQL using Python"
}
] |
Pinging an IP address in Java | Set 1 | 29 Jun, 2017
PING stands for Packet InterNet Groper in computer networking field. It’s a computer network administration software used to test the reachability of a host on an Internet Protocol (IP) network. It measures the round-trip time for messages sent from the originating host to a destination computer that are echoed back to the source.
Ping operates by sending Internet Control Message Protocol (ICMP/ICMP6 ) Echo Request packets to the target host and waiting for an ICMP Echo Reply. The program reports errors, packet loss, and a statistical summary of the results.
Internet Control Message Protocol (ICMP) : The Internet Control Message Protocol (ICMP) supports protocol in the Internet Protocol suite. It is used by network devices like routers, to send error messages and operational information indicating whether a request to service is available or not or that a host or router could not be reached.ICMP differs from transport protocols such as TCP and UDP in that it is not typically used to exchange data between systems.ICMP is not supported in Java and ping in Java as it relies on ICMPWe can’t simply ping in Java as it relies on ICMP, which is sadly not supported in Java
This Java Program pings an IP address in Java using InetAddress class. It is successful in case of Local Host but for other hosts this program shows that the host is unreachable.
// Java Program to Ping an IP addressimport java.io.*;import java.net.*; class NewClass{ // Sends ping request to a provided IP address public static void sendPingRequest(String ipAddress) throws UnknownHostException, IOException { InetAddress geek = InetAddress.getByName(ipAddress); System.out.println("Sending Ping Request to " + ipAddress); if (geek.isReachable(5000)) System.out.println("Host is reachable"); else System.out.println("Sorry ! We can't reach to this host"); } // Driver code public static void main(String[] args) throws UnknownHostException, IOException { String ipAddress = "127.0.0.1"; sendPingRequest(ipAddress); ipAddress = "133.192.31.42"; sendPingRequest(ipAddress); ipAddress = "145.154.42.58"; sendPingRequest(ipAddress); }}
Output :
Sending Ping Request to 127.0.0.1
Host is reachable
Sending Ping Request to 133.192.31.42
Sorry! We can't reach to this host
Sending Ping Request to 145.154.42.58
Sorry! We can't reach to this host
Next : Pinging an IP address in Java | Set 2 (By creating sub-process)
Definition Source :https://en.wikipedia.org/wiki/Internet_Control_Message_Protocolhttps://en.wikipedia.org/wiki/Ping_(networking_utility)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.
Java-Networking
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n29 Jun, 2017"
},
{
"code": null,
"e": 385,
"s": 52,
"text": "PING stands for Packet InterNet Groper in computer networking field. It’s a computer network administration software used to test the reachability of a host on an Internet Protocol (IP) network. It measures the round-trip time for messages sent from the originating host to a destination computer that are echoed back to the source."
},
{
"code": null,
"e": 617,
"s": 385,
"text": "Ping operates by sending Internet Control Message Protocol (ICMP/ICMP6 ) Echo Request packets to the target host and waiting for an ICMP Echo Reply. The program reports errors, packet loss, and a statistical summary of the results."
},
{
"code": null,
"e": 1235,
"s": 617,
"text": "Internet Control Message Protocol (ICMP) : The Internet Control Message Protocol (ICMP) supports protocol in the Internet Protocol suite. It is used by network devices like routers, to send error messages and operational information indicating whether a request to service is available or not or that a host or router could not be reached.ICMP differs from transport protocols such as TCP and UDP in that it is not typically used to exchange data between systems.ICMP is not supported in Java and ping in Java as it relies on ICMPWe can’t simply ping in Java as it relies on ICMP, which is sadly not supported in Java"
},
{
"code": null,
"e": 1414,
"s": 1235,
"text": "This Java Program pings an IP address in Java using InetAddress class. It is successful in case of Local Host but for other hosts this program shows that the host is unreachable."
},
{
"code": "// Java Program to Ping an IP addressimport java.io.*;import java.net.*; class NewClass{ // Sends ping request to a provided IP address public static void sendPingRequest(String ipAddress) throws UnknownHostException, IOException { InetAddress geek = InetAddress.getByName(ipAddress); System.out.println(\"Sending Ping Request to \" + ipAddress); if (geek.isReachable(5000)) System.out.println(\"Host is reachable\"); else System.out.println(\"Sorry ! We can't reach to this host\"); } // Driver code public static void main(String[] args) throws UnknownHostException, IOException { String ipAddress = \"127.0.0.1\"; sendPingRequest(ipAddress); ipAddress = \"133.192.31.42\"; sendPingRequest(ipAddress); ipAddress = \"145.154.42.58\"; sendPingRequest(ipAddress); }}",
"e": 2245,
"s": 1414,
"text": null
},
{
"code": null,
"e": 2254,
"s": 2245,
"text": "Output :"
},
{
"code": null,
"e": 2456,
"s": 2254,
"text": "Sending Ping Request to 127.0.0.1\nHost is reachable\nSending Ping Request to 133.192.31.42\nSorry! We can't reach to this host\nSending Ping Request to 145.154.42.58\nSorry! We can't reach to this host\n"
},
{
"code": null,
"e": 2527,
"s": 2456,
"text": "Next : Pinging an IP address in Java | Set 2 (By creating sub-process)"
},
{
"code": null,
"e": 2968,
"s": 2527,
"text": "Definition Source :https://en.wikipedia.org/wiki/Internet_Control_Message_Protocolhttps://en.wikipedia.org/wiki/Ping_(networking_utility)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": 3093,
"s": 2968,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 3109,
"s": 3093,
"text": "Java-Networking"
},
{
"code": null,
"e": 3114,
"s": 3109,
"text": "Java"
},
{
"code": null,
"e": 3119,
"s": 3114,
"text": "Java"
}
] |
Python Number cos() Method | Python number method cos() returns the cosine of x radians.
Following is the syntax for cos() method −
cos(x)
Note − This function is not accessible directly, so we need to import math module and then we need to call this function using math static object.
x − This must be a numeric value.
x − This must be a numeric value.
This method returns a numeric value between -1 and 1, which represents the cosine of the angle.
The following example shows the usage of cos() method.
#!/usr/bin/python
import math
print "cos(3) : ", math.cos(3)
print "cos(-3) : ", math.cos(-3)
print "cos(0) : ", math.cos(0)
print "cos(math.pi) : ", math.cos(math.pi)
print "cos(2*math.pi) : ", math.cos(2*math.pi)
When we run above program, it produces following result −
cos(3) : -0.9899924966
cos(-3) : -0.9899924966
cos(0) : 1.0
cos(math.pi) : -1.0
cos(2*math.pi) : 1.0 | [
{
"code": null,
"e": 2439,
"s": 2378,
"text": "Python number method cos() returns the cosine of x radians."
},
{
"code": null,
"e": 2482,
"s": 2439,
"text": "Following is the syntax for cos() method −"
},
{
"code": null,
"e": 2490,
"s": 2482,
"text": "cos(x)\n"
},
{
"code": null,
"e": 2637,
"s": 2490,
"text": "Note − This function is not accessible directly, so we need to import math module and then we need to call this function using math static object."
},
{
"code": null,
"e": 2671,
"s": 2637,
"text": "x − This must be a numeric value."
},
{
"code": null,
"e": 2705,
"s": 2671,
"text": "x − This must be a numeric value."
},
{
"code": null,
"e": 2801,
"s": 2705,
"text": "This method returns a numeric value between -1 and 1, which represents the cosine of the angle."
},
{
"code": null,
"e": 2856,
"s": 2801,
"text": "The following example shows the usage of cos() method."
},
{
"code": null,
"e": 3077,
"s": 2856,
"text": "#!/usr/bin/python\nimport math\n\nprint \"cos(3) : \", math.cos(3)\nprint \"cos(-3) : \", math.cos(-3)\nprint \"cos(0) : \", math.cos(0)\nprint \"cos(math.pi) : \", math.cos(math.pi)\nprint \"cos(2*math.pi) : \", math.cos(2*math.pi)"
},
{
"code": null,
"e": 3135,
"s": 3077,
"text": "When we run above program, it produces following result −"
}
] |
Remove every k-th node of the linked list | 11 Jun, 2022
Given a singly linked list, Your task is to remove every K-th node of the linked list. Assume that K is always less than or equal to length of Linked List.Examples :
Input : 1->2->3->4->5->6->7->8
k = 3
Output : 1->2->4->5->7->8
As 3 is the k-th node after its deletion list
would be 1->2->4->5->6->7->8
And now 4 is the starting node then from it, 6
would be the k-th node. So no other kth node
could be there.So, final list is:
1->2->4->5->7->8.
Input: 1->2->3->4->5->6
k = 1
Output: Empty list
All nodes need to be deleted
The idea is to traverse the list from the beginning and keep track of nodes visited after the last deletion. Whenever count becomes k, delete the current node and reset the count as 0.
(1) Traverse list and do following
(a) Count node before deletion.
(b) If (count == k) that means current
node is to be deleted.
(i) Delete current node i.e. do
// assign address of next node of
// current node to the previous node
// of the current node.
prev->next = ptr->next i.e.
(ii) Reset count as 0, i.e., do count = 0.
(c) Update prev node if count != 0 and if
count is 0 that means that node is a
starting point.
(d) Update ptr and continue until all
k-th node gets deleted.
Below is the implementation.
C++
Java
Python3
C#
Javascript
// C++ program to delete every k-th Node of// a singly linked list.#include<bits/stdc++.h>using namespace std; /* Linked list Node */struct Node{ int data; struct Node* next;}; // To remove complete list (Needed for// case when k is 1)void freeList(Node *node){ while (node != NULL) { Node *next = node->next; delete (node); node = next; }} // Deletes every k-th node and returns head// of modified list.Node *deleteKthNode(struct Node *head, int k){ // If linked list is empty if (head == NULL) return NULL; if (k == 1) { freeList(head); return NULL; } // Initialize ptr and prev before starting // traversal. struct Node *ptr = head, *prev = NULL; // Traverse list and delete every k-th node int count = 0; while (ptr != NULL) { // increment Node count count++; // check if count is equal to k // if yes, then delete current Node if (k == count) { // put the next of current Node in // the next of previous Node delete(prev->next); prev->next = ptr->next; // set count = 0 to reach further // k-th Node count = 0; } // update prev if count is not 0 if (count != 0) prev = ptr; ptr = prev->next; } return head;} /* Function to print linked list */void displayList(struct Node *head){ struct Node *temp = head; while (temp != NULL) { cout<<temp->data<<" "; temp = temp->next; }} // Utility function to create a new node.struct Node *newNode(int x){ Node *temp = new Node; temp->data = x; temp->next = NULL; return temp;} /* Driver program to test count function*/int main(){ /* Start with the empty list */ struct Node* head = newNode(1); head->next = newNode(2); head->next->next = newNode(3); head->next->next->next = newNode(4); head->next->next->next->next = newNode(5); head->next->next->next->next->next = newNode(6); head->next->next->next->next->next->next = newNode(7); head->next->next->next->next->next->next->next = newNode(8); int k = 3; head = deleteKthNode(head, k); displayList(head); return 0;}
// Java program to delete every k-th Node// of a singly linked list.class GFG{ /* Linked list Node */static class Node{ int data; Node next;} // To remove complete list (Needed for// case when k is 1)static Node freeList(Node node){ while (node != null) { Node next = node.next; node = next; } return node;} // Deletes every k-th node and// returns head of modified list.static Node deleteKthNode(Node head, int k){ // If linked list is empty if (head == null) return null; if (k == 1) { head = freeList(head); return null; } // Initialize ptr and prev before // starting traversal. Node ptr = head, prev = null; // Traverse list and delete // every k-th node int count = 0; while (ptr != null) { // increment Node count count++; // check if count is equal to k // if yes, then delete current Node if (k == count) { // put the next of current Node in // the next of previous Node prev.next = ptr.next; // set count = 0 to reach further // k-th Node count = 0; } // update prev if count is not 0 if (count != 0) prev = ptr; ptr = prev.next; } return head;} /* Function to print linked list */static void displayList(Node head){ Node temp = head; while (temp != null) { System.out.print(temp.data + " "); temp = temp.next; }} // Utility function to create a new node.static Node newNode(int x){ Node temp = new Node(); temp.data = x; temp.next = null; return temp;} // Driver Codepublic static void main(String args[]){ /* Start with the empty list */ Node head = newNode(1); head.next = newNode(2); head.next.next = newNode(3); head.next.next.next = newNode(4); head.next.next.next.next = newNode(5); head.next.next.next.next.next = newNode(6); head.next.next.next.next.next.next = newNode(7); head.next.next.next.next.next.next.next = newNode(8); int k = 3; head = deleteKthNode(head, k); displayList(head);}} // This code is contributed by Arnab Kundu
# Python3 program to delete every k-th Node# of a singly linked list.import math # Linked list Nodeclass Node: def __init__(self, data): self.data = data self.next = None # To remove complete list (Needed for# case when k is 1)def freeList(node): while (node != None): next = node.next node = next return node # Deletes every k-th node and# returns head of modified list.def deleteKthNode(head, k): # If linked list is empty if (head == None): return None if (k == 1): freeList(head) return None # Initialize ptr and prev before # starting traversal. ptr = head prev = None # Traverse list and delete every k-th node count = 0 while (ptr != None): # increment Node count count = count + 1 # check if count is equal to k # if yes, then delete current Node if (k == count): # put the next of current Node in # the next of previous Node # delete(prev.next) prev.next = ptr.next # set count = 0 to reach further # k-th Node count = 0 # update prev if count is not 0 if (count != 0): prev = ptr ptr = prev.next return head # Function to print linked listdef displayList(head): temp = head while (temp != None): print(temp.data, end = ' ') temp = temp.next # Utility function to create a new node.def newNode( x): temp = Node(x) temp.data = x temp.next = None return temp # Driver Codeif __name__=='__main__': # Start with the empty list head = newNode(1) head.next = newNode(2) head.next.next = newNode(3) head.next.next.next = newNode(4) head.next.next.next.next = newNode(5) head.next.next.next.next.next = newNode(6) head.next.next.next.next.next.next = newNode(7) head.next.next.next.next.next.next.next = newNode(8) k = 3 head = deleteKthNode(head, k) displayList(head) # This code is contributed by Srathore
// C# program to delete every k-th Node// of a singly linked list.using System; class GFG{ /* Linked list Node */public class Node{ public int data; public Node next;} // To remove complete list (Needed for// case when k is 1)static Node freeList(Node node){ while (node != null) { Node next = node.next; node = next; } return node;} // Deletes every k-th node and// returns head of modified list.static Node deleteKthNode(Node head, int k){ // If linked list is empty if (head == null) return null; if (k == 1) { head = freeList(head); return null; } // Initialize ptr and prev before // starting traversal. Node ptr = head, prev = null; // Traverse list and delete // every k-th node int count = 0; while (ptr != null) { // increment Node count count++; // check if count is equal to k // if yes, then delete current Node if (k == count) { // put the next of current Node in // the next of previous Node prev.next = ptr.next; // set count = 0 to reach further // k-th Node count = 0; } // update prev if count is not 0 if (count != 0) prev = ptr; ptr = prev.next; } return head;} /* Function to print linked list */static void displayList(Node head){ Node temp = head; while (temp != null) { Console.Write(temp.data + " "); temp = temp.next; }} // Utility function to create a new node.static Node newNode(int x){ Node temp = new Node(); temp.data = x; temp.next = null; return temp;} // Driver Codepublic static void Main(String []args){ /* Start with the empty list */ Node head = newNode(1); head.next = newNode(2); head.next.next = newNode(3); head.next.next.next = newNode(4); head.next.next.next.next = newNode(5); head.next.next.next.next.next = newNode(6); head.next.next.next.next.next.next = newNode(7); head.next.next.next.next.next.next.next = newNode(8); int k = 3; head = deleteKthNode(head, k); displayList(head);}} // This code is contributed by PrinciRaj1992
<script> // Javascript program to delete every k-th Node// of a singly linked list./* Linked list Node */class Node { constructor() { this.data = 0; this.next = null; }} // To remove complete list (Needed for // case when k is 1) function freeList( node) { while (node != null) { next = node.next; node = next; } return node; } // Deletes every k-th node and // returns head of modified list. function deleteKthNode( head , k) { // If linked list is empty if (head == null) return null; if (k == 1) { head = freeList(head); return null; } // Initialize ptr and prev before // starting traversal. var ptr = head, prev = null; // Traverse list and delete // every k-th node var count = 0; while (ptr != null) { // increment Node count count++; // check if count is equal to k // if yes, then delete current Node if (k == count) { // put the next of current Node in // the next of previous Node prev.next = ptr.next; // set count = 0 to reach further // k-th Node count = 0; } // update prev if count is not 0 if (count != 0) prev = ptr; ptr = prev.next; } return head; } /* Function to print linked list */ function displayList( head) { temp = head; while (temp != null) { document.write(temp.data + " "); temp = temp.next; } } // Utility function to create a new node. function newNode(x) { temp = new Node(); temp.data = x; temp.next = null; return temp; } // Driver Code /* Start with the empty list */ head = newNode(1); head.next = newNode(2); head.next.next = newNode(3); head.next.next.next = newNode(4); head.next.next.next.next = newNode(5); head.next.next.next.next.next = newNode(6); head.next.next.next.next.next.next = newNode(7); head.next.next.next.next.next.next.next = newNode(8); var k = 3; head = deleteKthNode(head, k); displayList(head); // This code contributed by umadevi9616 </script>
Output:
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
default, selected
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
1 2 4 5 7 8
Time Complexity : O(n) Auxiliary Space : O(1)
Remove every k-th node of the linked list | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersRemove every k-th node of the linked list | 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 / 5:53•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=o-_r86WD3Qo" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Sahil Chhabra. 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.
andrew1234
sapnasingh4991
princiraj1992
Akanksha_Rai
umadevi9616
Kirti_Mangal
polymatir3j
Amazon
Microsoft
Linked List
Amazon
Microsoft
Linked List
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stack Data Structure (Introduction and Program)
LinkedList in Java
Introduction to Data Structures
What is Data Structure: Types, Classifications and Applications
Implementing a Linked List in Java using Class
Add two numbers represented by linked lists | Set 1
Detect and Remove Loop in a Linked List
Queue - Linked List Implementation
Function to check if a singly linked list is palindrome
Implement a stack using singly linked list | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n11 Jun, 2022"
},
{
"code": null,
"e": 220,
"s": 52,
"text": "Given a singly linked list, Your task is to remove every K-th node of the linked list. Assume that K is always less than or equal to length of Linked List.Examples : "
},
{
"code": null,
"e": 604,
"s": 220,
"text": "Input : 1->2->3->4->5->6->7->8 \n k = 3\nOutput : 1->2->4->5->7->8\nAs 3 is the k-th node after its deletion list \nwould be 1->2->4->5->6->7->8\nAnd now 4 is the starting node then from it, 6 \nwould be the k-th node. So no other kth node \ncould be there.So, final list is:\n1->2->4->5->7->8.\n\nInput: 1->2->3->4->5->6 \n k = 1\nOutput: Empty list \nAll nodes need to be deleted"
},
{
"code": null,
"e": 792,
"s": 606,
"text": "The idea is to traverse the list from the beginning and keep track of nodes visited after the last deletion. Whenever count becomes k, delete the current node and reset the count as 0. "
},
{
"code": null,
"e": 1377,
"s": 792,
"text": "(1) Traverse list and do following\n (a) Count node before deletion.\n (b) If (count == k) that means current \n node is to be deleted.\n (i) Delete current node i.e. do\n\n // assign address of next node of \n // current node to the previous node\n // of the current node.\n prev->next = ptr->next i.e.\n\n (ii) Reset count as 0, i.e., do count = 0.\n (c) Update prev node if count != 0 and if\n count is 0 that means that node is a\n starting point.\n (d) Update ptr and continue until all \n k-th node gets deleted."
},
{
"code": null,
"e": 1408,
"s": 1377,
"text": "Below is the implementation. "
},
{
"code": null,
"e": 1412,
"s": 1408,
"text": "C++"
},
{
"code": null,
"e": 1417,
"s": 1412,
"text": "Java"
},
{
"code": null,
"e": 1425,
"s": 1417,
"text": "Python3"
},
{
"code": null,
"e": 1428,
"s": 1425,
"text": "C#"
},
{
"code": null,
"e": 1439,
"s": 1428,
"text": "Javascript"
},
{
"code": "// C++ program to delete every k-th Node of// a singly linked list.#include<bits/stdc++.h>using namespace std; /* Linked list Node */struct Node{ int data; struct Node* next;}; // To remove complete list (Needed for// case when k is 1)void freeList(Node *node){ while (node != NULL) { Node *next = node->next; delete (node); node = next; }} // Deletes every k-th node and returns head// of modified list.Node *deleteKthNode(struct Node *head, int k){ // If linked list is empty if (head == NULL) return NULL; if (k == 1) { freeList(head); return NULL; } // Initialize ptr and prev before starting // traversal. struct Node *ptr = head, *prev = NULL; // Traverse list and delete every k-th node int count = 0; while (ptr != NULL) { // increment Node count count++; // check if count is equal to k // if yes, then delete current Node if (k == count) { // put the next of current Node in // the next of previous Node delete(prev->next); prev->next = ptr->next; // set count = 0 to reach further // k-th Node count = 0; } // update prev if count is not 0 if (count != 0) prev = ptr; ptr = prev->next; } return head;} /* Function to print linked list */void displayList(struct Node *head){ struct Node *temp = head; while (temp != NULL) { cout<<temp->data<<\" \"; temp = temp->next; }} // Utility function to create a new node.struct Node *newNode(int x){ Node *temp = new Node; temp->data = x; temp->next = NULL; return temp;} /* Driver program to test count function*/int main(){ /* Start with the empty list */ struct Node* head = newNode(1); head->next = newNode(2); head->next->next = newNode(3); head->next->next->next = newNode(4); head->next->next->next->next = newNode(5); head->next->next->next->next->next = newNode(6); head->next->next->next->next->next->next = newNode(7); head->next->next->next->next->next->next->next = newNode(8); int k = 3; head = deleteKthNode(head, k); displayList(head); return 0;}",
"e": 3773,
"s": 1439,
"text": null
},
{
"code": "// Java program to delete every k-th Node// of a singly linked list.class GFG{ /* Linked list Node */static class Node{ int data; Node next;} // To remove complete list (Needed for// case when k is 1)static Node freeList(Node node){ while (node != null) { Node next = node.next; node = next; } return node;} // Deletes every k-th node and// returns head of modified list.static Node deleteKthNode(Node head, int k){ // If linked list is empty if (head == null) return null; if (k == 1) { head = freeList(head); return null; } // Initialize ptr and prev before // starting traversal. Node ptr = head, prev = null; // Traverse list and delete // every k-th node int count = 0; while (ptr != null) { // increment Node count count++; // check if count is equal to k // if yes, then delete current Node if (k == count) { // put the next of current Node in // the next of previous Node prev.next = ptr.next; // set count = 0 to reach further // k-th Node count = 0; } // update prev if count is not 0 if (count != 0) prev = ptr; ptr = prev.next; } return head;} /* Function to print linked list */static void displayList(Node head){ Node temp = head; while (temp != null) { System.out.print(temp.data + \" \"); temp = temp.next; }} // Utility function to create a new node.static Node newNode(int x){ Node temp = new Node(); temp.data = x; temp.next = null; return temp;} // Driver Codepublic static void main(String args[]){ /* Start with the empty list */ Node head = newNode(1); head.next = newNode(2); head.next.next = newNode(3); head.next.next.next = newNode(4); head.next.next.next.next = newNode(5); head.next.next.next.next.next = newNode(6); head.next.next.next.next.next.next = newNode(7); head.next.next.next.next.next.next.next = newNode(8); int k = 3; head = deleteKthNode(head, k); displayList(head);}} // This code is contributed by Arnab Kundu",
"e": 6032,
"s": 3773,
"text": null
},
{
"code": "# Python3 program to delete every k-th Node# of a singly linked list.import math # Linked list Nodeclass Node: def __init__(self, data): self.data = data self.next = None # To remove complete list (Needed for# case when k is 1)def freeList(node): while (node != None): next = node.next node = next return node # Deletes every k-th node and# returns head of modified list.def deleteKthNode(head, k): # If linked list is empty if (head == None): return None if (k == 1): freeList(head) return None # Initialize ptr and prev before # starting traversal. ptr = head prev = None # Traverse list and delete every k-th node count = 0 while (ptr != None): # increment Node count count = count + 1 # check if count is equal to k # if yes, then delete current Node if (k == count): # put the next of current Node in # the next of previous Node # delete(prev.next) prev.next = ptr.next # set count = 0 to reach further # k-th Node count = 0 # update prev if count is not 0 if (count != 0): prev = ptr ptr = prev.next return head # Function to print linked listdef displayList(head): temp = head while (temp != None): print(temp.data, end = ' ') temp = temp.next # Utility function to create a new node.def newNode( x): temp = Node(x) temp.data = x temp.next = None return temp # Driver Codeif __name__=='__main__': # Start with the empty list head = newNode(1) head.next = newNode(2) head.next.next = newNode(3) head.next.next.next = newNode(4) head.next.next.next.next = newNode(5) head.next.next.next.next.next = newNode(6) head.next.next.next.next.next.next = newNode(7) head.next.next.next.next.next.next.next = newNode(8) k = 3 head = deleteKthNode(head, k) displayList(head) # This code is contributed by Srathore",
"e": 8106,
"s": 6032,
"text": null
},
{
"code": "// C# program to delete every k-th Node// of a singly linked list.using System; class GFG{ /* Linked list Node */public class Node{ public int data; public Node next;} // To remove complete list (Needed for// case when k is 1)static Node freeList(Node node){ while (node != null) { Node next = node.next; node = next; } return node;} // Deletes every k-th node and// returns head of modified list.static Node deleteKthNode(Node head, int k){ // If linked list is empty if (head == null) return null; if (k == 1) { head = freeList(head); return null; } // Initialize ptr and prev before // starting traversal. Node ptr = head, prev = null; // Traverse list and delete // every k-th node int count = 0; while (ptr != null) { // increment Node count count++; // check if count is equal to k // if yes, then delete current Node if (k == count) { // put the next of current Node in // the next of previous Node prev.next = ptr.next; // set count = 0 to reach further // k-th Node count = 0; } // update prev if count is not 0 if (count != 0) prev = ptr; ptr = prev.next; } return head;} /* Function to print linked list */static void displayList(Node head){ Node temp = head; while (temp != null) { Console.Write(temp.data + \" \"); temp = temp.next; }} // Utility function to create a new node.static Node newNode(int x){ Node temp = new Node(); temp.data = x; temp.next = null; return temp;} // Driver Codepublic static void Main(String []args){ /* Start with the empty list */ Node head = newNode(1); head.next = newNode(2); head.next.next = newNode(3); head.next.next.next = newNode(4); head.next.next.next.next = newNode(5); head.next.next.next.next.next = newNode(6); head.next.next.next.next.next.next = newNode(7); head.next.next.next.next.next.next.next = newNode(8); int k = 3; head = deleteKthNode(head, k); displayList(head);}} // This code is contributed by PrinciRaj1992",
"e": 10316,
"s": 8106,
"text": null
},
{
"code": "<script> // Javascript program to delete every k-th Node// of a singly linked list./* Linked list Node */class Node { constructor() { this.data = 0; this.next = null; }} // To remove complete list (Needed for // case when k is 1) function freeList( node) { while (node != null) { next = node.next; node = next; } return node; } // Deletes every k-th node and // returns head of modified list. function deleteKthNode( head , k) { // If linked list is empty if (head == null) return null; if (k == 1) { head = freeList(head); return null; } // Initialize ptr and prev before // starting traversal. var ptr = head, prev = null; // Traverse list and delete // every k-th node var count = 0; while (ptr != null) { // increment Node count count++; // check if count is equal to k // if yes, then delete current Node if (k == count) { // put the next of current Node in // the next of previous Node prev.next = ptr.next; // set count = 0 to reach further // k-th Node count = 0; } // update prev if count is not 0 if (count != 0) prev = ptr; ptr = prev.next; } return head; } /* Function to print linked list */ function displayList( head) { temp = head; while (temp != null) { document.write(temp.data + \" \"); temp = temp.next; } } // Utility function to create a new node. function newNode(x) { temp = new Node(); temp.data = x; temp.next = null; return temp; } // Driver Code /* Start with the empty list */ head = newNode(1); head.next = newNode(2); head.next.next = newNode(3); head.next.next.next = newNode(4); head.next.next.next.next = newNode(5); head.next.next.next.next.next = newNode(6); head.next.next.next.next.next.next = newNode(7); head.next.next.next.next.next.next.next = newNode(8); var k = 3; head = deleteKthNode(head, k); displayList(head); // This code contributed by umadevi9616 </script>",
"e": 12738,
"s": 10316,
"text": null
},
{
"code": null,
"e": 12748,
"s": 12738,
"text": "Output: "
},
{
"code": null,
"e": 12757,
"s": 12748,
"text": "Chapters"
},
{
"code": null,
"e": 12784,
"s": 12757,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 12834,
"s": 12784,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 12857,
"s": 12834,
"text": "captions off, selected"
},
{
"code": null,
"e": 12865,
"s": 12857,
"text": "English"
},
{
"code": null,
"e": 12883,
"s": 12865,
"text": "default, selected"
},
{
"code": null,
"e": 12907,
"s": 12883,
"text": "This is a modal window."
},
{
"code": null,
"e": 12976,
"s": 12907,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 12998,
"s": 12976,
"text": "End of dialog window."
},
{
"code": null,
"e": 13010,
"s": 12998,
"text": "1 2 4 5 7 8"
},
{
"code": null,
"e": 13058,
"s": 13010,
"text": "Time Complexity : O(n) Auxiliary Space : O(1) "
},
{
"code": null,
"e": 13958,
"s": 13058,
"text": "Remove every k-th node of the linked list | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersRemove every k-th node of the linked list | 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 / 5:53•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=o-_r86WD3Qo\" 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": 14380,
"s": 13958,
"text": "This article is contributed by Sahil Chhabra. 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": 14391,
"s": 14380,
"text": "andrew1234"
},
{
"code": null,
"e": 14406,
"s": 14391,
"text": "sapnasingh4991"
},
{
"code": null,
"e": 14420,
"s": 14406,
"text": "princiraj1992"
},
{
"code": null,
"e": 14433,
"s": 14420,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 14445,
"s": 14433,
"text": "umadevi9616"
},
{
"code": null,
"e": 14458,
"s": 14445,
"text": "Kirti_Mangal"
},
{
"code": null,
"e": 14470,
"s": 14458,
"text": "polymatir3j"
},
{
"code": null,
"e": 14477,
"s": 14470,
"text": "Amazon"
},
{
"code": null,
"e": 14487,
"s": 14477,
"text": "Microsoft"
},
{
"code": null,
"e": 14499,
"s": 14487,
"text": "Linked List"
},
{
"code": null,
"e": 14506,
"s": 14499,
"text": "Amazon"
},
{
"code": null,
"e": 14516,
"s": 14506,
"text": "Microsoft"
},
{
"code": null,
"e": 14528,
"s": 14516,
"text": "Linked List"
},
{
"code": null,
"e": 14626,
"s": 14528,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 14674,
"s": 14626,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 14693,
"s": 14674,
"text": "LinkedList in Java"
},
{
"code": null,
"e": 14725,
"s": 14693,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 14789,
"s": 14725,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 14836,
"s": 14789,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 14888,
"s": 14836,
"text": "Add two numbers represented by linked lists | Set 1"
},
{
"code": null,
"e": 14928,
"s": 14888,
"text": "Detect and Remove Loop in a Linked List"
},
{
"code": null,
"e": 14963,
"s": 14928,
"text": "Queue - Linked List Implementation"
},
{
"code": null,
"e": 15019,
"s": 14963,
"text": "Function to check if a singly linked list is palindrome"
}
] |
Python program to calculate BMI(Body Mass Index) of your Body | We have to enter our height and weight. Our task is to calculate BMI using formula.
Step 1: input height and weight of your body.
Step 2: then applying the formula for calculation BMI.
Step 3: display BMI.
height = float(input("Enter your height(m): "))
weight = float(input("Enter your weight(kg): "))
print("Your BMI is: ", round(weight / (height * height), 2))
Enter your height (m): 5.8
Input your weight (kg): 64
Your body mass index is: 1.9 | [
{
"code": null,
"e": 1271,
"s": 1187,
"text": "We have to enter our height and weight. Our task is to calculate BMI using formula."
},
{
"code": null,
"e": 1394,
"s": 1271,
"text": "Step 1: input height and weight of your body.\nStep 2: then applying the formula for calculation BMI.\nStep 3: display BMI.\n"
},
{
"code": null,
"e": 1552,
"s": 1394,
"text": "height = float(input(\"Enter your height(m): \"))\nweight = float(input(\"Enter your weight(kg): \"))\nprint(\"Your BMI is: \", round(weight / (height * height), 2))"
},
{
"code": null,
"e": 1637,
"s": 1552,
"text": "Enter your height (m): 5.8\nInput your weight (kg): 64\nYour body mass index is: 1.9\n"
}
] |
Web Driver Methods in Selenium Python | 19 May, 2020
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies. Selenium WebDriver offers various useful methods to control the session, or in other words, browser. For example, adding a cookie, pressing back button, navigating among tabs, etc.
This article revolves around Various WebDriver Methods and functions one can use to manipulate DOM and various other actions one can do with Selenium WebDriver in Python.
To create object of WebDriver, import WebDriver class from docs and create a object based on different Web Browser and Capabilities. After this one can use this object to perform all the operations of Webdriver. For example, to create object of Firefox, one can use –
# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox()
Arguments –Webdriver accepts various arguments to manipulate various features –
desired_capabilities – A dictionary of capabilities to request whenstarting the browser session. Required parameter.
browser_profile – A selenium.webdriver.firefox.firefox_profile.FirefoxProfile object.Only used if Firefox is requested. Optional.
proxy – A selenium.webdriver.common.proxy.Proxy object. The browser session willbe started with given proxy settings, if possible. Optional.
keep_alive – Whether to configure remote_connection.RemoteConnection to useHTTP keep-alive. Defaults to False.
file_detector – Pass custom file detector object during instantiation. If None,then default LocalFileDetector() will be used.
options – instance of a driver options.Options class
After one has created an object of Webdriver, open a webpage, and perform various other methods using below syntax and examples. one can perform various actions such as opening a new tab closing a tab, closing a window, adding a cookie, executing javascript, etc.
Let’s try to implement WebDriver methods using https://www.geeksforgeeks.org/ and play around with using javascript through selenium python.Program –
# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # write scriptscript = "alert('Alert via selenium')" # generate a alert via javascriptdriver.execute_async_script(script)
Output –Browser generates alert as verified below –
One can perform a huge number of operations using Webdriver methods such as getting cookie, taking screenshot, etc. Here is a list of important methods used in webdriver.
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python OOPs Concepts
How to iterate through Excel rows in Python?
Python Classes and Objects
Introduction To PYTHON
Decorators in Python
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Rotate axis tick labels in Seaborn and Matplotlib
Queue in Python
Defaultdict in Python | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n19 May, 2020"
},
{
"code": null,
"e": 792,
"s": 53,
"text": "Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies. Selenium WebDriver offers various useful methods to control the session, or in other words, browser. For example, adding a cookie, pressing back button, navigating among tabs, etc."
},
{
"code": null,
"e": 963,
"s": 792,
"text": "This article revolves around Various WebDriver Methods and functions one can use to manipulate DOM and various other actions one can do with Selenium WebDriver in Python."
},
{
"code": null,
"e": 1231,
"s": 963,
"text": "To create object of WebDriver, import WebDriver class from docs and create a object based on different Web Browser and Capabilities. After this one can use this object to perform all the operations of Webdriver. For example, to create object of Firefox, one can use –"
},
{
"code": "# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() ",
"e": 1338,
"s": 1231,
"text": null
},
{
"code": null,
"e": 1418,
"s": 1338,
"text": "Arguments –Webdriver accepts various arguments to manipulate various features –"
},
{
"code": null,
"e": 1535,
"s": 1418,
"text": "desired_capabilities – A dictionary of capabilities to request whenstarting the browser session. Required parameter."
},
{
"code": null,
"e": 1665,
"s": 1535,
"text": "browser_profile – A selenium.webdriver.firefox.firefox_profile.FirefoxProfile object.Only used if Firefox is requested. Optional."
},
{
"code": null,
"e": 1806,
"s": 1665,
"text": "proxy – A selenium.webdriver.common.proxy.Proxy object. The browser session willbe started with given proxy settings, if possible. Optional."
},
{
"code": null,
"e": 1917,
"s": 1806,
"text": "keep_alive – Whether to configure remote_connection.RemoteConnection to useHTTP keep-alive. Defaults to False."
},
{
"code": null,
"e": 2043,
"s": 1917,
"text": "file_detector – Pass custom file detector object during instantiation. If None,then default LocalFileDetector() will be used."
},
{
"code": null,
"e": 2096,
"s": 2043,
"text": "options – instance of a driver options.Options class"
},
{
"code": null,
"e": 2360,
"s": 2096,
"text": "After one has created an object of Webdriver, open a webpage, and perform various other methods using below syntax and examples. one can perform various actions such as opening a new tab closing a tab, closing a window, adding a cookie, executing javascript, etc."
},
{
"code": null,
"e": 2510,
"s": 2360,
"text": "Let’s try to implement WebDriver methods using https://www.geeksforgeeks.org/ and play around with using javascript through selenium python.Program –"
},
{
"code": "# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # write scriptscript = \"alert('Alert via selenium')\" # generate a alert via javascriptdriver.execute_async_script(script)",
"e": 2807,
"s": 2510,
"text": null
},
{
"code": null,
"e": 2859,
"s": 2807,
"text": "Output –Browser generates alert as verified below –"
},
{
"code": null,
"e": 3030,
"s": 2859,
"text": "One can perform a huge number of operations using Webdriver methods such as getting cookie, taking screenshot, etc. Here is a list of important methods used in webdriver."
},
{
"code": null,
"e": 3046,
"s": 3030,
"text": "Python-selenium"
},
{
"code": null,
"e": 3055,
"s": 3046,
"text": "selenium"
},
{
"code": null,
"e": 3062,
"s": 3055,
"text": "Python"
},
{
"code": null,
"e": 3160,
"s": 3062,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3181,
"s": 3160,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3226,
"s": 3181,
"text": "How to iterate through Excel rows in Python?"
},
{
"code": null,
"e": 3253,
"s": 3226,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3276,
"s": 3253,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 3297,
"s": 3276,
"text": "Decorators in Python"
},
{
"code": null,
"e": 3329,
"s": 3297,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3385,
"s": 3329,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 3435,
"s": 3385,
"text": "Rotate axis tick labels in Seaborn and Matplotlib"
},
{
"code": null,
"e": 3451,
"s": 3435,
"text": "Queue in Python"
}
] |
Rune in Golang | 11 Apr, 2022
In the past, we only had one character set, and that was known as ASCII (American Standard Code for Information Interchange). There, we used 7 bits to represent 128 characters, including upper and lowercase English letters, digits, and a variety of punctuations and device-control characters. Due to this character limitation, the majority of the population is not able to use their custom writing systems. To solve this problem, Unicode was invented. Unicode is a superset of ASCII that contains all the characters present in today’s world writing system. It includes accents, diacritical marks, control codes like tab and carriage return, and assigns each character a standard number called “Unicode Code Point”, or in Go language, a “Rune”. The Rune type is an alias of int32. Important Points:
Always remember, a string is a sequence of bytes and not of a Rune. A string may contain Unicode text encoded in UTF-8. But, the Go source code encodes as UTF-8, therefore, no need to encode the string in UTF-8.
UTF-8 encodes all the Unicode in the range of 1 to 4 bytes, where 1 byte is used for ASCII and the rest for the Rune.
ASCII contains a total of 256 elements and out of which, 128 are characters and 0-127 are identified as code points. Here, code point refers to the element which represents a single value.
Example:
♄
It is a Rune with hexadecimal value ♄.
It represents a Rune constant, where an integer value recognizes a Unicode code point. In Go language, a Rune Literal is expressed as one or more characters enclosed in single quotes like ‘g’, ‘\t’, etc. In between single quotes, you are allowed to place any character except a newline and an unescaped single quote. Here, these single-quoted characters themselves represent the Unicode value of the given character and multi-character sequences with a backslash (at the beginning of the multi-character sequence) encode values in a different format. In Rune Literals, all the sequences that start with a backslash are illegal, only the following single-character escapes represent special values when you use them with a backslash:
Example 1:
C
// Simple Go program to illustrate// how to create a runepackage main import ( "fmt" "reflect") func main() { // Creating a rune rune1 := 'B' rune2 := 'g' rune3 := '\a' // Displaying rune and its type fmt.Printf("Rune 1: %c; Unicode: %U; Type: %s", rune1, rune1, reflect.TypeOf(rune1)) fmt.Printf("\nRune 2: %c; Unicode: %U; Type: %s", rune2, rune2, reflect.TypeOf(rune2)) fmt.Printf("\nRune 3: Unicode: %U; Type: %s", rune3, reflect.TypeOf(rune3)) }
Output:
Rune 1: B; Unicode: U+0042; Type: int32
Rune 2: g; Unicode: U+0067; Type: int32
Rune 3: Unicode: U+0007; Type: int32
Example 2: Output:
Character: ♛, Unicode:U+265B, Position:0
Character: ♠, Unicode:U+2660, Position:1
Character: ♧, Unicode:U+2667, Position:2
Character: ♡, Unicode:U+2661, Position:3
Character: ♬, Unicode:U+266C, Position:4
kaustubhgupta1828
Golang
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Go
Golang Maps
Interfaces in Golang
Slices 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 compare times in Golang?
Inheritance in GoLang
How to Assign Default Value for Struct Field in Golang? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Apr, 2022"
},
{
"code": null,
"e": 826,
"s": 28,
"text": "In the past, we only had one character set, and that was known as ASCII (American Standard Code for Information Interchange). There, we used 7 bits to represent 128 characters, including upper and lowercase English letters, digits, and a variety of punctuations and device-control characters. Due to this character limitation, the majority of the population is not able to use their custom writing systems. To solve this problem, Unicode was invented. Unicode is a superset of ASCII that contains all the characters present in today’s world writing system. It includes accents, diacritical marks, control codes like tab and carriage return, and assigns each character a standard number called “Unicode Code Point”, or in Go language, a “Rune”. The Rune type is an alias of int32. Important Points:"
},
{
"code": null,
"e": 1038,
"s": 826,
"text": "Always remember, a string is a sequence of bytes and not of a Rune. A string may contain Unicode text encoded in UTF-8. But, the Go source code encodes as UTF-8, therefore, no need to encode the string in UTF-8."
},
{
"code": null,
"e": 1156,
"s": 1038,
"text": "UTF-8 encodes all the Unicode in the range of 1 to 4 bytes, where 1 byte is used for ASCII and the rest for the Rune."
},
{
"code": null,
"e": 1345,
"s": 1156,
"text": "ASCII contains a total of 256 elements and out of which, 128 are characters and 0-127 are identified as code points. Here, code point refers to the element which represents a single value."
},
{
"code": null,
"e": 1354,
"s": 1345,
"text": "Example:"
},
{
"code": null,
"e": 1357,
"s": 1354,
"text": " ♄"
},
{
"code": null,
"e": 1396,
"s": 1357,
"text": "It is a Rune with hexadecimal value ♄."
},
{
"code": null,
"e": 2130,
"s": 1396,
"text": "It represents a Rune constant, where an integer value recognizes a Unicode code point. In Go language, a Rune Literal is expressed as one or more characters enclosed in single quotes like ‘g’, ‘\\t’, etc. In between single quotes, you are allowed to place any character except a newline and an unescaped single quote. Here, these single-quoted characters themselves represent the Unicode value of the given character and multi-character sequences with a backslash (at the beginning of the multi-character sequence) encode values in a different format. In Rune Literals, all the sequences that start with a backslash are illegal, only the following single-character escapes represent special values when you use them with a backslash: "
},
{
"code": null,
"e": 2142,
"s": 2130,
"text": "Example 1: "
},
{
"code": null,
"e": 2144,
"s": 2142,
"text": "C"
},
{
"code": "// Simple Go program to illustrate// how to create a runepackage main import ( \"fmt\" \"reflect\") func main() { // Creating a rune rune1 := 'B' rune2 := 'g' rune3 := '\\a' // Displaying rune and its type fmt.Printf(\"Rune 1: %c; Unicode: %U; Type: %s\", rune1, rune1, reflect.TypeOf(rune1)) fmt.Printf(\"\\nRune 2: %c; Unicode: %U; Type: %s\", rune2, rune2, reflect.TypeOf(rune2)) fmt.Printf(\"\\nRune 3: Unicode: %U; Type: %s\", rune3, reflect.TypeOf(rune3)) }",
"e": 2727,
"s": 2144,
"text": null
},
{
"code": null,
"e": 2735,
"s": 2727,
"text": "Output:"
},
{
"code": null,
"e": 2852,
"s": 2735,
"text": "Rune 1: B; Unicode: U+0042; Type: int32\nRune 2: g; Unicode: U+0067; Type: int32\nRune 3: Unicode: U+0007; Type: int32"
},
{
"code": null,
"e": 2872,
"s": 2852,
"text": "Example 2: Output:"
},
{
"code": null,
"e": 3082,
"s": 2872,
"text": "Character: ♛, Unicode:U+265B, Position:0 \nCharacter: ♠, Unicode:U+2660, Position:1 \nCharacter: ♧, Unicode:U+2667, Position:2 \nCharacter: ♡, Unicode:U+2661, Position:3 \nCharacter: ♬, Unicode:U+266C, Position:4 "
},
{
"code": null,
"e": 3100,
"s": 3082,
"text": "kaustubhgupta1828"
},
{
"code": null,
"e": 3107,
"s": 3100,
"text": "Golang"
},
{
"code": null,
"e": 3119,
"s": 3107,
"text": "Go Language"
},
{
"code": null,
"e": 3217,
"s": 3119,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3230,
"s": 3217,
"text": "Arrays in Go"
},
{
"code": null,
"e": 3242,
"s": 3230,
"text": "Golang Maps"
},
{
"code": null,
"e": 3263,
"s": 3242,
"text": "Interfaces in Golang"
},
{
"code": null,
"e": 3280,
"s": 3263,
"text": "Slices in Golang"
},
{
"code": null,
"e": 3334,
"s": 3280,
"text": "Different Ways to Find the Type of Variable in Golang"
},
{
"code": null,
"e": 3363,
"s": 3334,
"text": "How to Parse JSON in Golang?"
},
{
"code": null,
"e": 3395,
"s": 3363,
"text": "How to Trim a String in Golang?"
},
{
"code": null,
"e": 3427,
"s": 3395,
"text": "How to compare times in Golang?"
},
{
"code": null,
"e": 3449,
"s": 3427,
"text": "Inheritance in GoLang"
}
] |
Implementation of lower_bound and upper_bound on Set of Pairs in C++ | 22 Jul, 2020
Prerequisite: set lower_bound() function in C++ STL, set upper_bound() function in C++ STL
lower_bound() returns an iterator pointing to the first element in the range [first, last) which has a value greater than or equals to the given value “val”. But in set of Pairs lower_bound() for pair(x, y) will return an iterator pointing to the position of pair whose the first value is greater than or equals x.If first values are same, then it will return an iterator pointing to the position of pair whose the second value is greater than or equals y.If the above-mentioned criteria are not met, then it returns an iterator which points to end of the set (next to the last pair in set).
Syntax: There are two ways to use lower_bound():
setName.lower_bound({a, b})
lower_bound(setName.begin(), setName.end(), pair(a, b))
upper_bound() returns an iterator pointing to the first element in the range [first, last) which has a value greater than the given value “val”. But in set of Pairs upper_bound() for pair(x, y) will return an iterator pointing to the position of pair whose the first value is greater than x.If first values are same, then it will return an iterator pointing to the position of pair whose the second value is greater than y.If the above-mentioned criteria are not met, then it returns an iterator which points to end of the set (next to the last pair in set).
Syntax: There are two ways to use upper_bound() with Set:
setName.upper_bound({a, b})
upper_bound(setName.begin(), setName.end(), pair(a, b))
Below is the program to demonstrate lower_bound() and upper_bound() in set of pairs:
// C++ program to demonstrate lower_bound()// and upper_bound() in set of Pairs #include <bits/stdc++.h>using namespace std; // Function to implement lower_bound()void findLowerBound( set<pair<int, int> >& arr, pair<int, int>& p){ // Given iterator points to the // lower_bound() of given pair auto low = lower_bound(arr.begin(), arr.end(), p); cout << "lower_bound() for {1, 2}" << " is: {" << (*low).first << ", " << (*low).second << "}" << endl;} // Function to implement upper_bound()void findUpperBound( set<pair<int, int> >& arr, pair<int, int>& p){ // Given iterator points to the // lower_bound() of given pair auto up = upper_bound(arr.begin(), arr.end(), p); cout << "upper_bound() for {1, 2}" << " is: {" << (*up).first << ", " << (*up).second << "}" << endl;} // Driver Codeint main(){ // Given sorted vector of Pairs set<pair<int, int> > s; // Insert pairs in set s.insert(make_pair(1, 2)); s.insert(make_pair(2, 4)); s.insert(make_pair(3, 7)); s.insert(make_pair(8, 9)); // Given pair { 1, 2 } pair<int, int> p = { 1, 2 }; // Function Call to find lower_bound // of pair p in arr findLowerBound(s, p); // Function Call to find upper_bound // of pair p in arr findUpperBound(s, p); return 0;}
lower_bound() for {1, 2} is: {1, 2}
upper_bound() for {1, 2} is: {2, 4}
lakshaysood
cpp-pair
cpp-set
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bitwise Operators in C/C++
vector erase() and clear() in C++
Inheritance in C++
Priority Queue in C++ Standard Template Library (STL)
The C++ Standard Template Library (STL)
Substring in C++
Object Oriented Programming in C++
C++ Classes and Objects
Sorting a vector in C++
2D Vector In C++ With User Defined Size | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n22 Jul, 2020"
},
{
"code": null,
"e": 144,
"s": 53,
"text": "Prerequisite: set lower_bound() function in C++ STL, set upper_bound() function in C++ STL"
},
{
"code": null,
"e": 736,
"s": 144,
"text": "lower_bound() returns an iterator pointing to the first element in the range [first, last) which has a value greater than or equals to the given value “val”. But in set of Pairs lower_bound() for pair(x, y) will return an iterator pointing to the position of pair whose the first value is greater than or equals x.If first values are same, then it will return an iterator pointing to the position of pair whose the second value is greater than or equals y.If the above-mentioned criteria are not met, then it returns an iterator which points to end of the set (next to the last pair in set)."
},
{
"code": null,
"e": 785,
"s": 736,
"text": "Syntax: There are two ways to use lower_bound():"
},
{
"code": null,
"e": 813,
"s": 785,
"text": "setName.lower_bound({a, b})"
},
{
"code": null,
"e": 869,
"s": 813,
"text": "lower_bound(setName.begin(), setName.end(), pair(a, b))"
},
{
"code": null,
"e": 1428,
"s": 869,
"text": "upper_bound() returns an iterator pointing to the first element in the range [first, last) which has a value greater than the given value “val”. But in set of Pairs upper_bound() for pair(x, y) will return an iterator pointing to the position of pair whose the first value is greater than x.If first values are same, then it will return an iterator pointing to the position of pair whose the second value is greater than y.If the above-mentioned criteria are not met, then it returns an iterator which points to end of the set (next to the last pair in set)."
},
{
"code": null,
"e": 1486,
"s": 1428,
"text": "Syntax: There are two ways to use upper_bound() with Set:"
},
{
"code": null,
"e": 1514,
"s": 1486,
"text": "setName.upper_bound({a, b})"
},
{
"code": null,
"e": 1570,
"s": 1514,
"text": "upper_bound(setName.begin(), setName.end(), pair(a, b))"
},
{
"code": null,
"e": 1655,
"s": 1570,
"text": "Below is the program to demonstrate lower_bound() and upper_bound() in set of pairs:"
},
{
"code": "// C++ program to demonstrate lower_bound()// and upper_bound() in set of Pairs #include <bits/stdc++.h>using namespace std; // Function to implement lower_bound()void findLowerBound( set<pair<int, int> >& arr, pair<int, int>& p){ // Given iterator points to the // lower_bound() of given pair auto low = lower_bound(arr.begin(), arr.end(), p); cout << \"lower_bound() for {1, 2}\" << \" is: {\" << (*low).first << \", \" << (*low).second << \"}\" << endl;} // Function to implement upper_bound()void findUpperBound( set<pair<int, int> >& arr, pair<int, int>& p){ // Given iterator points to the // lower_bound() of given pair auto up = upper_bound(arr.begin(), arr.end(), p); cout << \"upper_bound() for {1, 2}\" << \" is: {\" << (*up).first << \", \" << (*up).second << \"}\" << endl;} // Driver Codeint main(){ // Given sorted vector of Pairs set<pair<int, int> > s; // Insert pairs in set s.insert(make_pair(1, 2)); s.insert(make_pair(2, 4)); s.insert(make_pair(3, 7)); s.insert(make_pair(8, 9)); // Given pair { 1, 2 } pair<int, int> p = { 1, 2 }; // Function Call to find lower_bound // of pair p in arr findLowerBound(s, p); // Function Call to find upper_bound // of pair p in arr findUpperBound(s, p); return 0;}",
"e": 3052,
"s": 1655,
"text": null
},
{
"code": null,
"e": 3125,
"s": 3052,
"text": "lower_bound() for {1, 2} is: {1, 2}\nupper_bound() for {1, 2} is: {2, 4}\n"
},
{
"code": null,
"e": 3137,
"s": 3125,
"text": "lakshaysood"
},
{
"code": null,
"e": 3146,
"s": 3137,
"text": "cpp-pair"
},
{
"code": null,
"e": 3154,
"s": 3146,
"text": "cpp-set"
},
{
"code": null,
"e": 3158,
"s": 3154,
"text": "C++"
},
{
"code": null,
"e": 3162,
"s": 3158,
"text": "CPP"
},
{
"code": null,
"e": 3260,
"s": 3162,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3287,
"s": 3260,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 3321,
"s": 3287,
"text": "vector erase() and clear() in C++"
},
{
"code": null,
"e": 3340,
"s": 3321,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 3394,
"s": 3340,
"text": "Priority Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 3434,
"s": 3394,
"text": "The C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 3451,
"s": 3434,
"text": "Substring in C++"
},
{
"code": null,
"e": 3486,
"s": 3451,
"text": "Object Oriented Programming in C++"
},
{
"code": null,
"e": 3510,
"s": 3486,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 3534,
"s": 3510,
"text": "Sorting a vector in C++"
}
] |
ES6 | Operators | 07 Mar, 2022
An expression is a special kind of statement that evaluates to a value. Every expression consists of
Operands: Represents the data.
Operator: which performs certain operations on operands.
Consider the following expression – 2 / 3, in the expression, 2 and 3 are operands and the symbol /is the operator.JavaScript supports the following types of operators:
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Type Operators
Miscellaneous Operators
Arithmetic Operators: As we know these are the basic mathematical operators available in JavaScript ES6.
Example:
javascript
<script> var num1 = 10.5 var num2 = 2.5 document.write("Sum : " + (num1 + num2) + "<br>"); document.write("Difference : " + (num1 - num2) + "<br>") document.write("Product : " + num1 * num2 + "<br>") document.write("Quotient : " + num1 / num2 + "<br>") document.write("Remainder : " + num1 % num2 + "<br>") // pre-increment document.write("Value of num1 after pre-increment : " + (++num1) + "<br>") // post-increment document.write("Value of num1 after post-increment : " + (num1++) + "<br>") // pre-decrement document.write("Value of num2 after pre-decrement : " + (--num2) + "<br>") // post-decrement document.write("Value of num2 after post-decrement : " + (num2--) + "<br>")</script>
Output:
Sum : 13
Difference : 8
Product : 26.25
Quotient : 4.2
Remainder : 0.5
Value of num1 after pre-increment : 11.5
Value of num1 after post-increment : 11.5
Value of num2 after pre-decrement : 1.5
Value of num2 after post-decrement : 1.5
Relational Operators: An operator that compares two values. Relational operators are sometimes called comparison operators.
Example:
javascript
<script> document.write("11>12 : " + (11 > 12) + "<br>"); document.write("11<12 : " + (11 < 12) + "<br>") document.write("12>=11 : " + (12 >= 11) + "<br>") document.write("12<=12 : " + (12 <= 12) + "<br>") document.write("11==11 : " + (11 == 11) + "<br>") document.write("11!=11 : " + (11 != 11) + "<br>")</script>
Output:
11>12 : false
11=11 : true
12<=12 : true
11==11 : true
11!=11 : false
Logical Operators: Logical operators are used to combine two or more relational statements.
Example:
javascript
<script> // Returns true as every statement is true. document.write("13>12 && 12>11 && 9==9 : " + (13 > 12 && 12 > 11 && 9 == 9) + "<br>"); // Returns false as 11>12 is false. document.write("11>12 && 12>11 && 9==9 : " + (11 > 12 && 12 > 11 && 9 == 9) + "<br>") // As one true statement is enough to return. document.write("11>12 || 12>11 || 9==9 : " + (11 > 12 || 12 > 11 || 9 == 9) + "<br>") // Returns false as 11>12 is not true. document.write("11>12 && (12>11 || 9==9) : " + (11 > 12 && (12 > 11 || 9 == 9)) + "<br>")</script>
Output:
13>12 && 12>11 && 9==9 : true
11>12 && 12>11 && 9==9 : false
11>12 || 12>11 || 9==9 : true
11>12 && (12>11 || 9==9) : false
Bitwise Operators: A bitwise operator is an operator used to perform bitwise operations on bit patterns or binary numerals that involve the manipulation of individual bits.
Example:
javascript
<script> document.write("2&3 : " + (2 & 3) + "<br>"); document.write("2|3 : " + (2 | 3) + "<br>"); document.write("2^3 : " + (2 ^ 3) + "<br>"); document.write("~4 : " + (~4) + "<br>"); document.write("2<<3 : " + (2 << 3) + "<br>"); document.write("2>>3 : " + (2 >> 3) + "<br>");</script>
Output:
2&3 : 2
2|3 : 3
2^3 : 1
~4 : -5
2<>3 : 0
Assignment Operators: An assignment operator is the operator used to assign a new value to the variable, property, event or indexer element.
Example:
javascript
<script> var a = 12; var b = 10; a = b; document.write("a = b : " + a + "<br>"); a += b; document.write("a += b : " + a + "<br>") a -= b; document.write("a -= b : " + a + "<br>") a *= b; document.write("a *= b : " + a + "<br>") a /= b; document.write("a /= b : " + a + "<br>")</script>
Output:
a = b : 10
a += b : 20
a -= b : 10
a *= b : 100
a /= b : 10
Type Operators: It is a unary operator. This operator returns the data type of the operand. Syntax:
typeof(operand)
Example:
javascript
<script> var a = 12; var b = "Geeks"; var b = "Geeks"; var c = true; var d = String; document.write("a is " + typeof(a) + "<br>"); document.write("b is " + typeof(b) + "<br>") document.write("c is : " + typeof(c) + "<br>") document.write("d is : " + typeof(d) + "<br>")</script>
Output:
a is number
b is string
c is : boolean
d is : function
Miscellaneous Operators:These are the operators that, does different operators when used at different types of occasions.
Example:
javascript
<script> var a = "GeeksforGeeks=>"; var b = "A Computer science portal."; var c = true; var d = 9; // Concatenation document.write("a+b : " + a + b + "<br>"); // Ternary Operator var c = 2 > 3 ? "yes is 2>3" : "No, It is not." document.write("2>3 :" + c + "<br>") // Negation d = -d; document.write("d = -d : " + d + "<br>")</script>
Output:
a+b : GeeksforGeeks=>A Computer science portal.
2>3 :No, It is not.
d = -d : -9
sumitgumber28
ES6
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Mar, 2022"
},
{
"code": null,
"e": 131,
"s": 28,
"text": "An expression is a special kind of statement that evaluates to a value. Every expression consists of "
},
{
"code": null,
"e": 162,
"s": 131,
"text": "Operands: Represents the data."
},
{
"code": null,
"e": 219,
"s": 162,
"text": "Operator: which performs certain operations on operands."
},
{
"code": null,
"e": 390,
"s": 219,
"text": "Consider the following expression – 2 / 3, in the expression, 2 and 3 are operands and the symbol /is the operator.JavaScript supports the following types of operators: "
},
{
"code": null,
"e": 411,
"s": 390,
"text": "Arithmetic Operators"
},
{
"code": null,
"e": 432,
"s": 411,
"text": "Relational Operators"
},
{
"code": null,
"e": 450,
"s": 432,
"text": "Logical Operators"
},
{
"code": null,
"e": 468,
"s": 450,
"text": "Bitwise Operators"
},
{
"code": null,
"e": 489,
"s": 468,
"text": "Assignment Operators"
},
{
"code": null,
"e": 504,
"s": 489,
"text": "Type Operators"
},
{
"code": null,
"e": 528,
"s": 504,
"text": "Miscellaneous Operators"
},
{
"code": null,
"e": 634,
"s": 528,
"text": "Arithmetic Operators: As we know these are the basic mathematical operators available in JavaScript ES6. "
},
{
"code": null,
"e": 645,
"s": 634,
"text": "Example: "
},
{
"code": null,
"e": 656,
"s": 645,
"text": "javascript"
},
{
"code": "<script> var num1 = 10.5 var num2 = 2.5 document.write(\"Sum : \" + (num1 + num2) + \"<br>\"); document.write(\"Difference : \" + (num1 - num2) + \"<br>\") document.write(\"Product : \" + num1 * num2 + \"<br>\") document.write(\"Quotient : \" + num1 / num2 + \"<br>\") document.write(\"Remainder : \" + num1 % num2 + \"<br>\") // pre-increment document.write(\"Value of num1 after pre-increment : \" + (++num1) + \"<br>\") // post-increment document.write(\"Value of num1 after post-increment : \" + (num1++) + \"<br>\") // pre-decrement document.write(\"Value of num2 after pre-decrement : \" + (--num2) + \"<br>\") // post-decrement document.write(\"Value of num2 after post-decrement : \" + (num2--) + \"<br>\")</script>",
"e": 1490,
"s": 656,
"text": null
},
{
"code": null,
"e": 1500,
"s": 1490,
"text": "Output: "
},
{
"code": null,
"e": 1735,
"s": 1500,
"text": "Sum : 13\nDifference : 8\nProduct : 26.25\nQuotient : 4.2\nRemainder : 0.5\nValue of num1 after pre-increment : 11.5\nValue of num1 after post-increment : 11.5\nValue of num2 after pre-decrement : 1.5\nValue of num2 after post-decrement : 1.5"
},
{
"code": null,
"e": 1860,
"s": 1735,
"text": "Relational Operators: An operator that compares two values. Relational operators are sometimes called comparison operators. "
},
{
"code": null,
"e": 1871,
"s": 1860,
"text": "Example: "
},
{
"code": null,
"e": 1882,
"s": 1871,
"text": "javascript"
},
{
"code": "<script> document.write(\"11>12 : \" + (11 > 12) + \"<br>\"); document.write(\"11<12 : \" + (11 < 12) + \"<br>\") document.write(\"12>=11 : \" + (12 >= 11) + \"<br>\") document.write(\"12<=12 : \" + (12 <= 12) + \"<br>\") document.write(\"11==11 : \" + (11 == 11) + \"<br>\") document.write(\"11!=11 : \" + (11 != 11) + \"<br>\")</script>",
"e": 2220,
"s": 1882,
"text": null
},
{
"code": null,
"e": 2230,
"s": 2220,
"text": "Output: "
},
{
"code": null,
"e": 2300,
"s": 2230,
"text": "11>12 : false\n11=11 : true\n12<=12 : true\n11==11 : true\n11!=11 : false"
},
{
"code": null,
"e": 2393,
"s": 2300,
"text": "Logical Operators: Logical operators are used to combine two or more relational statements. "
},
{
"code": null,
"e": 2404,
"s": 2393,
"text": "Example: "
},
{
"code": null,
"e": 2415,
"s": 2404,
"text": "javascript"
},
{
"code": "<script> // Returns true as every statement is true. document.write(\"13>12 && 12>11 && 9==9 : \" + (13 > 12 && 12 > 11 && 9 == 9) + \"<br>\"); // Returns false as 11>12 is false. document.write(\"11>12 && 12>11 && 9==9 : \" + (11 > 12 && 12 > 11 && 9 == 9) + \"<br>\") // As one true statement is enough to return. document.write(\"11>12 || 12>11 || 9==9 : \" + (11 > 12 || 12 > 11 || 9 == 9) + \"<br>\") // Returns false as 11>12 is not true. document.write(\"11>12 && (12>11 || 9==9) : \" + (11 > 12 && (12 > 11 || 9 == 9)) + \"<br>\")</script> ",
"e": 3043,
"s": 2415,
"text": null
},
{
"code": null,
"e": 3053,
"s": 3043,
"text": "Output: "
},
{
"code": null,
"e": 3177,
"s": 3053,
"text": "13>12 && 12>11 && 9==9 : true\n11>12 && 12>11 && 9==9 : false\n11>12 || 12>11 || 9==9 : true\n11>12 && (12>11 || 9==9) : false"
},
{
"code": null,
"e": 3351,
"s": 3177,
"text": "Bitwise Operators: A bitwise operator is an operator used to perform bitwise operations on bit patterns or binary numerals that involve the manipulation of individual bits. "
},
{
"code": null,
"e": 3364,
"s": 3353,
"text": "Example: "
},
{
"code": null,
"e": 3375,
"s": 3364,
"text": "javascript"
},
{
"code": "<script> document.write(\"2&3 : \" + (2 & 3) + \"<br>\"); document.write(\"2|3 : \" + (2 | 3) + \"<br>\"); document.write(\"2^3 : \" + (2 ^ 3) + \"<br>\"); document.write(\"~4 : \" + (~4) + \"<br>\"); document.write(\"2<<3 : \" + (2 << 3) + \"<br>\"); document.write(\"2>>3 : \" + (2 >> 3) + \"<br>\");</script>",
"e": 3681,
"s": 3375,
"text": null
},
{
"code": null,
"e": 3691,
"s": 3681,
"text": "Output: "
},
{
"code": null,
"e": 3732,
"s": 3691,
"text": "2&3 : 2\n2|3 : 3\n2^3 : 1\n~4 : -5\n2<>3 : 0"
},
{
"code": null,
"e": 3874,
"s": 3732,
"text": "Assignment Operators: An assignment operator is the operator used to assign a new value to the variable, property, event or indexer element. "
},
{
"code": null,
"e": 3885,
"s": 3874,
"text": "Example: "
},
{
"code": null,
"e": 3896,
"s": 3885,
"text": "javascript"
},
{
"code": "<script> var a = 12; var b = 10; a = b; document.write(\"a = b : \" + a + \"<br>\"); a += b; document.write(\"a += b : \" + a + \"<br>\") a -= b; document.write(\"a -= b : \" + a + \"<br>\") a *= b; document.write(\"a *= b : \" + a + \"<br>\") a /= b; document.write(\"a /= b : \" + a + \"<br>\")</script>",
"e": 4238,
"s": 3896,
"text": null
},
{
"code": null,
"e": 4248,
"s": 4238,
"text": "Output: "
},
{
"code": null,
"e": 4308,
"s": 4248,
"text": "a = b : 10\na += b : 20\na -= b : 10\na *= b : 100\na /= b : 10"
},
{
"code": null,
"e": 4410,
"s": 4308,
"text": "Type Operators: It is a unary operator. This operator returns the data type of the operand. Syntax: "
},
{
"code": null,
"e": 4426,
"s": 4410,
"text": "typeof(operand)"
},
{
"code": null,
"e": 4437,
"s": 4426,
"text": "Example: "
},
{
"code": null,
"e": 4448,
"s": 4437,
"text": "javascript"
},
{
"code": "<script> var a = 12; var b = \"Geeks\"; var b = \"Geeks\"; var c = true; var d = String; document.write(\"a is \" + typeof(a) + \"<br>\"); document.write(\"b is \" + typeof(b) + \"<br>\") document.write(\"c is : \" + typeof(c) + \"<br>\") document.write(\"d is : \" + typeof(d) + \"<br>\")</script>",
"e": 4756,
"s": 4448,
"text": null
},
{
"code": null,
"e": 4766,
"s": 4756,
"text": "Output: "
},
{
"code": null,
"e": 4821,
"s": 4766,
"text": "a is number\nb is string\nc is : boolean\nd is : function"
},
{
"code": null,
"e": 4944,
"s": 4821,
"text": "Miscellaneous Operators:These are the operators that, does different operators when used at different types of occasions. "
},
{
"code": null,
"e": 4955,
"s": 4944,
"text": "Example: "
},
{
"code": null,
"e": 4966,
"s": 4955,
"text": "javascript"
},
{
"code": "<script> var a = \"GeeksforGeeks=>\"; var b = \"A Computer science portal.\"; var c = true; var d = 9; // Concatenation document.write(\"a+b : \" + a + b + \"<br>\"); // Ternary Operator var c = 2 > 3 ? \"yes is 2>3\" : \"No, It is not.\" document.write(\"2>3 :\" + c + \"<br>\") // Negation d = -d; document.write(\"d = -d : \" + d + \"<br>\")</script>",
"e": 5339,
"s": 4966,
"text": null
},
{
"code": null,
"e": 5349,
"s": 5339,
"text": "Output: "
},
{
"code": null,
"e": 5429,
"s": 5349,
"text": "a+b : GeeksforGeeks=>A Computer science portal.\n2>3 :No, It is not.\nd = -d : -9"
},
{
"code": null,
"e": 5445,
"s": 5431,
"text": "sumitgumber28"
},
{
"code": null,
"e": 5449,
"s": 5445,
"text": "ES6"
},
{
"code": null,
"e": 5456,
"s": 5449,
"text": "Picked"
},
{
"code": null,
"e": 5467,
"s": 5456,
"text": "JavaScript"
},
{
"code": null,
"e": 5484,
"s": 5467,
"text": "Web Technologies"
}
] |
Thread joinable() function in C++ | 26 Oct, 2018
Thread::joinable is an in-built function in C++ std::thread. It is an observer function which means it observes a state and then returns the corresponding output and checks whether the thread object is joinable or not.
A thread object is said to be joinable if it identifies/represent an active thread of execution.
A thread is not joinable if:
It was default-constructed
If either of its member join or detach has been called
It has been moved elsewhere
Syntax:
std::thread::joinable()
Parameters: This function does not accepts any parameters.
Return Value: It is a boolean type function and returns true when the thread object isjoinable. It returns false if the thread object is not joinable.
The following program demonstrate the use of std::thread::joinable()
Note: On the online IDE this program will show error. To compile this, use the flag “-pthread” on g++ compilers compilation with the help of command “g++ –std=c++14 -pthread file.cpp”.
// C++ program to demonstrate the use of// std::thread::joinable() #include <chrono>#include <iostream>#include <thread> using namespace std; // function to put thread to sleepvoid threadFunc(){ std::this_thread::sleep_for( std::chrono::seconds(1));} int main(){ std::thread t1; // declaring the thread cout << "t1 joinable when default created? \n"; // checking if it is joinable if (t1.joinable()) cout << "YES\n"; else cout << "NO\n"; // calling the function threadFunc // to put thread to sleep t1 = std::thread(threadFunc); cout << "t1 joinable when put to sleep? \n"; // checking if t1 is joinable if (t1.joinable()) cout << "YES\n"; else cout << "NO\n"; // joining t1 t1.join(); // checking joinablity of t1 after calling join() cout << "t1 joinable after join is called? \n"; if (t1.joinable()) cout << "YES\n"; else cout << "NO\n"; return 0;}
Output:
t1 joinable when default created?
NO
t1 joinable when put to sleep?
YES
t1 joinable after join is called?
NO
Note: The third output will appear 1 sec later because the thread was put to sleep for 1 minute.
CPP-Library
cpp-multithreading
STL
C++
C++ Programs
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
std::string class in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
Header files in C/C++ and its uses
Sorting a Map by value in C++ STL
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
C++ program for hashing with chaining | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Oct, 2018"
},
{
"code": null,
"e": 247,
"s": 28,
"text": "Thread::joinable is an in-built function in C++ std::thread. It is an observer function which means it observes a state and then returns the corresponding output and checks whether the thread object is joinable or not."
},
{
"code": null,
"e": 344,
"s": 247,
"text": "A thread object is said to be joinable if it identifies/represent an active thread of execution."
},
{
"code": null,
"e": 373,
"s": 344,
"text": "A thread is not joinable if:"
},
{
"code": null,
"e": 400,
"s": 373,
"text": "It was default-constructed"
},
{
"code": null,
"e": 455,
"s": 400,
"text": "If either of its member join or detach has been called"
},
{
"code": null,
"e": 483,
"s": 455,
"text": "It has been moved elsewhere"
},
{
"code": null,
"e": 491,
"s": 483,
"text": "Syntax:"
},
{
"code": null,
"e": 516,
"s": 491,
"text": "std::thread::joinable()\n"
},
{
"code": null,
"e": 575,
"s": 516,
"text": "Parameters: This function does not accepts any parameters."
},
{
"code": null,
"e": 726,
"s": 575,
"text": "Return Value: It is a boolean type function and returns true when the thread object isjoinable. It returns false if the thread object is not joinable."
},
{
"code": null,
"e": 795,
"s": 726,
"text": "The following program demonstrate the use of std::thread::joinable()"
},
{
"code": null,
"e": 980,
"s": 795,
"text": "Note: On the online IDE this program will show error. To compile this, use the flag “-pthread” on g++ compilers compilation with the help of command “g++ –std=c++14 -pthread file.cpp”."
},
{
"code": "// C++ program to demonstrate the use of// std::thread::joinable() #include <chrono>#include <iostream>#include <thread> using namespace std; // function to put thread to sleepvoid threadFunc(){ std::this_thread::sleep_for( std::chrono::seconds(1));} int main(){ std::thread t1; // declaring the thread cout << \"t1 joinable when default created? \\n\"; // checking if it is joinable if (t1.joinable()) cout << \"YES\\n\"; else cout << \"NO\\n\"; // calling the function threadFunc // to put thread to sleep t1 = std::thread(threadFunc); cout << \"t1 joinable when put to sleep? \\n\"; // checking if t1 is joinable if (t1.joinable()) cout << \"YES\\n\"; else cout << \"NO\\n\"; // joining t1 t1.join(); // checking joinablity of t1 after calling join() cout << \"t1 joinable after join is called? \\n\"; if (t1.joinable()) cout << \"YES\\n\"; else cout << \"NO\\n\"; return 0;}",
"e": 1959,
"s": 980,
"text": null
},
{
"code": null,
"e": 1967,
"s": 1959,
"text": "Output:"
},
{
"code": null,
"e": 2080,
"s": 1967,
"text": "t1 joinable when default created? \nNO\nt1 joinable when put to sleep? \nYES\nt1 joinable after join is called? \nNO\n"
},
{
"code": null,
"e": 2177,
"s": 2080,
"text": "Note: The third output will appear 1 sec later because the thread was put to sleep for 1 minute."
},
{
"code": null,
"e": 2189,
"s": 2177,
"text": "CPP-Library"
},
{
"code": null,
"e": 2208,
"s": 2189,
"text": "cpp-multithreading"
},
{
"code": null,
"e": 2212,
"s": 2208,
"text": "STL"
},
{
"code": null,
"e": 2216,
"s": 2212,
"text": "C++"
},
{
"code": null,
"e": 2229,
"s": 2216,
"text": "C++ Programs"
},
{
"code": null,
"e": 2233,
"s": 2229,
"text": "STL"
},
{
"code": null,
"e": 2237,
"s": 2233,
"text": "CPP"
},
{
"code": null,
"e": 2335,
"s": 2237,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2359,
"s": 2335,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 2379,
"s": 2359,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 2404,
"s": 2379,
"text": "std::string class in C++"
},
{
"code": null,
"e": 2437,
"s": 2404,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 2481,
"s": 2437,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 2516,
"s": 2481,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 2550,
"s": 2516,
"text": "Sorting a Map by value in C++ STL"
},
{
"code": null,
"e": 2594,
"s": 2550,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 2653,
"s": 2594,
"text": "How to return multiple values from a function in C or C++?"
}
] |
Why is Scanner skipping nextLine() after use of other next functions? | 02 Sep, 2021
The nextLine() method of java.util.Scanner class advances this scanner past the current line and returns the input that was skipped. This function prints the rest of the current line, leaving out the line separator at the end. The next is set to after the line separator. Since this method continues to search through the input looking for a line separator, it may search all of the input searching for the line to skip if no line separators are present.
Syntax:
public String nextLine()
What is the Issue with nextLine() method?
Consider the following code example:
Java
// Java program to show the issue with// nextLine() method of Scanner Class import java.util.Scanner; public class ScannerDemo1 { public static void main(String[] args) { // Declare the object and initialize with // predefined standard input object Scanner sc = new Scanner(System.in); // Taking input String name = sc.nextLine(); char gender = sc.next().charAt(0); int age = sc.nextInt(); String fatherName = sc.nextLine(); String motherName = sc.nextLine(); // Print the values to check // if the input was correctly obtained. System.out.println("Name: " + name); System.out.println("Gender: " + gender); System.out.println("Age: " + age); System.out.println("Father's Name: " + fatherName); System.out.println("Mother's Name: " + motherName); }}
When this code is run against the input:
abc
m
1
xyz
pqr
Expected Output:
Name: abc
Gender: m
Age: 1
Father's Name: xyz
Mother's Name: pqr
Actual Output:
Name: abc
Gender: m
Age: 1
Father's Name:
Mother's Name: xyz
As you can see, the nextLine() method skips the input to be read and takes the name of Mother in the place of Father. Hence the expected output does not match with the actual output. This error is very common and causes a lot of problems.
Why does this issue occur? This issue occurs because, when nextInt() method of Scanner class is used to read the age of the person, it returns the value 1 to the variable age, as expected. But the cursor, after reading 1, remains just after it.
abc
m
1_ // Cursor is here
xyz
pqr
So when the Father’s name is read using nextLine() method of Scanner class, this method starts reading from the cursor’s current position. In this case, it will start reading just after 1. So the next line after 1 is just a new line, which is represented by ‘\n’ character. Hence the Father’s name is just ‘\n’.
How to solve this issue? This issue can be solved by either of the following two ways:
1. reading the complete line for the integer and converting it to an integer, or
Syntax:
// Read the complete line as String
// and convert it to integer
int var = Integer.parseInt(sc.nextLine());
Although this method is not applicable for input String after Byte character(Byte.parseByte(sc.nextLine()). Second method is applicable in that case.
2. by consuming the leftover new line using the nextLine() method.
Syntax:
// Read the integer
int var = sc.nextInt();
// Read the leftover new line
sc.nextLine();
Below example shows how to solve this issue with nextLine() method:
Java
// Java program to solve the issue with// nextLine() method of Scanner Class import java.util.Scanner;import java.io.*;import java.lang.*; class ScannerDemo1 { public static void main(String[] args) { // Declare the object and initialize with // predefined standard input object Scanner sc = new Scanner(System.in); // Taking input String name = sc.nextLine(); char gender = sc.next().charAt(0); // Consuming the leftover new line // using the nextLine() method sc.nextLine(); // reading the complete line for the integer // and converting it to an integer int age = Integer.parseInt(sc.nextLine()); String fatherName = sc.nextLine(); String motherName = sc.nextLine(); // Print the values to check // if the input was correctly obtained. System.out.println("Name: " + name); System.out.println("Gender: " + gender); System.out.println("Age: " + age); System.out.println("Father's Name: " + fatherName); System.out.println("Mother's Name: " + motherName); }}
When this code is run against the input:
abc
m
1
xyz
pqr
Expected Output:
Name: abc
Gender: m
Age: 1
Father's Name: xyz
Mother's Name: pqr
Actual Output:
Name: abc
Gender: m
Age: 1
Father's Name: xyz
Mother's Name: pqr
manishgnext
amanpreet9391
gulshankumarar231
Java-Scanner
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n02 Sep, 2021"
},
{
"code": null,
"e": 507,
"s": 52,
"text": "The nextLine() method of java.util.Scanner class advances this scanner past the current line and returns the input that was skipped. This function prints the rest of the current line, leaving out the line separator at the end. The next is set to after the line separator. Since this method continues to search through the input looking for a line separator, it may search all of the input searching for the line to skip if no line separators are present."
},
{
"code": null,
"e": 515,
"s": 507,
"text": "Syntax:"
},
{
"code": null,
"e": 540,
"s": 515,
"text": "public String nextLine()"
},
{
"code": null,
"e": 582,
"s": 540,
"text": "What is the Issue with nextLine() method?"
},
{
"code": null,
"e": 620,
"s": 582,
"text": "Consider the following code example: "
},
{
"code": null,
"e": 625,
"s": 620,
"text": "Java"
},
{
"code": "// Java program to show the issue with// nextLine() method of Scanner Class import java.util.Scanner; public class ScannerDemo1 { public static void main(String[] args) { // Declare the object and initialize with // predefined standard input object Scanner sc = new Scanner(System.in); // Taking input String name = sc.nextLine(); char gender = sc.next().charAt(0); int age = sc.nextInt(); String fatherName = sc.nextLine(); String motherName = sc.nextLine(); // Print the values to check // if the input was correctly obtained. System.out.println(\"Name: \" + name); System.out.println(\"Gender: \" + gender); System.out.println(\"Age: \" + age); System.out.println(\"Father's Name: \" + fatherName); System.out.println(\"Mother's Name: \" + motherName); }}",
"e": 1549,
"s": 625,
"text": null
},
{
"code": null,
"e": 1591,
"s": 1549,
"text": "When this code is run against the input: "
},
{
"code": null,
"e": 1607,
"s": 1591,
"text": "abc\nm\n1\nxyz\npqr"
},
{
"code": null,
"e": 1625,
"s": 1607,
"text": "Expected Output: "
},
{
"code": null,
"e": 1690,
"s": 1625,
"text": "Name: abc\nGender: m\nAge: 1\nFather's Name: xyz\nMother's Name: pqr"
},
{
"code": null,
"e": 1706,
"s": 1690,
"text": "Actual Output: "
},
{
"code": null,
"e": 1768,
"s": 1706,
"text": "Name: abc\nGender: m\nAge: 1\nFather's Name: \nMother's Name: xyz"
},
{
"code": null,
"e": 2007,
"s": 1768,
"text": "As you can see, the nextLine() method skips the input to be read and takes the name of Mother in the place of Father. Hence the expected output does not match with the actual output. This error is very common and causes a lot of problems."
},
{
"code": null,
"e": 2252,
"s": 2007,
"text": "Why does this issue occur? This issue occurs because, when nextInt() method of Scanner class is used to read the age of the person, it returns the value 1 to the variable age, as expected. But the cursor, after reading 1, remains just after it."
},
{
"code": null,
"e": 2287,
"s": 2252,
"text": "abc\nm\n1_ // Cursor is here\nxyz\npqr"
},
{
"code": null,
"e": 2599,
"s": 2287,
"text": "So when the Father’s name is read using nextLine() method of Scanner class, this method starts reading from the cursor’s current position. In this case, it will start reading just after 1. So the next line after 1 is just a new line, which is represented by ‘\\n’ character. Hence the Father’s name is just ‘\\n’."
},
{
"code": null,
"e": 2688,
"s": 2599,
"text": "How to solve this issue? This issue can be solved by either of the following two ways: "
},
{
"code": null,
"e": 2769,
"s": 2688,
"text": "1. reading the complete line for the integer and converting it to an integer, or"
},
{
"code": null,
"e": 2778,
"s": 2769,
"text": "Syntax: "
},
{
"code": null,
"e": 2886,
"s": 2778,
"text": "// Read the complete line as String\n// and convert it to integer\nint var = Integer.parseInt(sc.nextLine());"
},
{
"code": null,
"e": 3036,
"s": 2886,
"text": "Although this method is not applicable for input String after Byte character(Byte.parseByte(sc.nextLine()). Second method is applicable in that case."
},
{
"code": null,
"e": 3103,
"s": 3036,
"text": "2. by consuming the leftover new line using the nextLine() method."
},
{
"code": null,
"e": 3112,
"s": 3103,
"text": "Syntax: "
},
{
"code": null,
"e": 3202,
"s": 3112,
"text": "// Read the integer\nint var = sc.nextInt();\n\n// Read the leftover new line\nsc.nextLine();"
},
{
"code": null,
"e": 3271,
"s": 3202,
"text": "Below example shows how to solve this issue with nextLine() method: "
},
{
"code": null,
"e": 3276,
"s": 3271,
"text": "Java"
},
{
"code": "// Java program to solve the issue with// nextLine() method of Scanner Class import java.util.Scanner;import java.io.*;import java.lang.*; class ScannerDemo1 { public static void main(String[] args) { // Declare the object and initialize with // predefined standard input object Scanner sc = new Scanner(System.in); // Taking input String name = sc.nextLine(); char gender = sc.next().charAt(0); // Consuming the leftover new line // using the nextLine() method sc.nextLine(); // reading the complete line for the integer // and converting it to an integer int age = Integer.parseInt(sc.nextLine()); String fatherName = sc.nextLine(); String motherName = sc.nextLine(); // Print the values to check // if the input was correctly obtained. System.out.println(\"Name: \" + name); System.out.println(\"Gender: \" + gender); System.out.println(\"Age: \" + age); System.out.println(\"Father's Name: \" + fatherName); System.out.println(\"Mother's Name: \" + motherName); }}",
"e": 4448,
"s": 3276,
"text": null
},
{
"code": null,
"e": 4490,
"s": 4448,
"text": "When this code is run against the input: "
},
{
"code": null,
"e": 4506,
"s": 4490,
"text": "abc\nm\n1\nxyz\npqr"
},
{
"code": null,
"e": 4524,
"s": 4506,
"text": "Expected Output: "
},
{
"code": null,
"e": 4589,
"s": 4524,
"text": "Name: abc\nGender: m\nAge: 1\nFather's Name: xyz\nMother's Name: pqr"
},
{
"code": null,
"e": 4605,
"s": 4589,
"text": "Actual Output: "
},
{
"code": null,
"e": 4670,
"s": 4605,
"text": "Name: abc\nGender: m\nAge: 1\nFather's Name: xyz\nMother's Name: pqr"
},
{
"code": null,
"e": 4682,
"s": 4670,
"text": "manishgnext"
},
{
"code": null,
"e": 4696,
"s": 4682,
"text": "amanpreet9391"
},
{
"code": null,
"e": 4714,
"s": 4696,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 4727,
"s": 4714,
"text": "Java-Scanner"
},
{
"code": null,
"e": 4732,
"s": 4727,
"text": "Java"
},
{
"code": null,
"e": 4737,
"s": 4732,
"text": "Java"
}
] |
MathF.Round() Method in C# with Examples | Set – 1 | 04 Apr, 2019
In C#, MathF.Round() is a MathF class method which is used to round a value to the nearest integer or to the particular number of fractional digits. This method can be overloaded by changing the number and type of arguments passed. There are 4 methods in the overload list of the MathF.Round() method.
MathF.Round(Single) MethodMathF.Round(Single, Int32) MethodMathF.Round(Single, Int32, MidpointRounding) MethodMathF.Round(Single, MidpointRounding) Method
MathF.Round(Single) Method
MathF.Round(Single, Int32) Method
MathF.Round(Single, Int32, MidpointRounding) Method
MathF.Round(Single, MidpointRounding) Method
Here, we will discuss the first two methods.
This method rounds a single-precision floating-point value to the nearest integer value.
Syntax: public static float Round (float x);Here, x is a singlefloating-point number which is to be rounded. Type of this parameter is System.Single.
Return Type:It returns the integer nearest to x and return type is System.Single.
Note: In case if the fractional component of x is halfway between two integers, one of which is even and the other odd, then the even number is returned.
Example:
// C# program to demonstrate the// MathF.Round(Single) methodusing System; class Geeks { // Main method static void Main(string[] args) { // Case-1 // A float value whose fractional part is // less than the halfway between two // consecutive integers float dx1 = 12.434565f; // Output value will be 12 Console.WriteLine("Rounded value of " + dx1 + " is " + MathF.Round(dx1)); // Case-2 // A float value whose fractional part is // greater than the halfway between two // consecutive integers float dx2 = 12.634565f; // Output value will be 13 Console.WriteLine("Rounded value of " + dx2 + " is " + MathF.Round(dx2)); }}
Rounded value of 12.43456 is 12
Rounded value of 12.63457 is 13
This method rounds a single precision floating-point value to a specified number of fractional digits.
Syntax: public static float Round (float x, int digits);
Parameters:x: A single floating-point number which is to be rounded. Type of this parameter is System.Single.y: It is the number of fractional digits in the returned value. Type of this parameter is System.Int32.
Return Type: It returns the integer nearest to x which contains a number of fractional digits equal to y and return type is System.Single.
Exception: This method will give ArgumentOutOfRangeException if the value of y is less than 0 or greater than 15.
Example:
// C# program to demonstrate the// MathF.Round(Single, Int32) Methodusing System; class Geeks { // Main method static void Main(string[] args) { // float type float dx1 = 12.434565f; // using method Console.WriteLine("Rounded value of " + dx1 + " is " + MathF.Round(dx1, 4)); // float type float dx2 = 12.634565f; // using method Console.WriteLine("Rounded value of " + dx2 + " is " + MathF.Round(dx2, 2)); }}
Rounded value of 12.43456 is 12.4346
Rounded value of 12.63457 is 12.63
CSharp-MathF-Class
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 Apr, 2019"
},
{
"code": null,
"e": 330,
"s": 28,
"text": "In C#, MathF.Round() is a MathF class method which is used to round a value to the nearest integer or to the particular number of fractional digits. This method can be overloaded by changing the number and type of arguments passed. There are 4 methods in the overload list of the MathF.Round() method."
},
{
"code": null,
"e": 485,
"s": 330,
"text": "MathF.Round(Single) MethodMathF.Round(Single, Int32) MethodMathF.Round(Single, Int32, MidpointRounding) MethodMathF.Round(Single, MidpointRounding) Method"
},
{
"code": null,
"e": 512,
"s": 485,
"text": "MathF.Round(Single) Method"
},
{
"code": null,
"e": 546,
"s": 512,
"text": "MathF.Round(Single, Int32) Method"
},
{
"code": null,
"e": 598,
"s": 546,
"text": "MathF.Round(Single, Int32, MidpointRounding) Method"
},
{
"code": null,
"e": 643,
"s": 598,
"text": "MathF.Round(Single, MidpointRounding) Method"
},
{
"code": null,
"e": 688,
"s": 643,
"text": "Here, we will discuss the first two methods."
},
{
"code": null,
"e": 777,
"s": 688,
"text": "This method rounds a single-precision floating-point value to the nearest integer value."
},
{
"code": null,
"e": 927,
"s": 777,
"text": "Syntax: public static float Round (float x);Here, x is a singlefloating-point number which is to be rounded. Type of this parameter is System.Single."
},
{
"code": null,
"e": 1009,
"s": 927,
"text": "Return Type:It returns the integer nearest to x and return type is System.Single."
},
{
"code": null,
"e": 1163,
"s": 1009,
"text": "Note: In case if the fractional component of x is halfway between two integers, one of which is even and the other odd, then the even number is returned."
},
{
"code": null,
"e": 1172,
"s": 1163,
"text": "Example:"
},
{
"code": "// C# program to demonstrate the// MathF.Round(Single) methodusing System; class Geeks { // Main method static void Main(string[] args) { // Case-1 // A float value whose fractional part is // less than the halfway between two // consecutive integers float dx1 = 12.434565f; // Output value will be 12 Console.WriteLine(\"Rounded value of \" + dx1 + \" is \" + MathF.Round(dx1)); // Case-2 // A float value whose fractional part is // greater than the halfway between two // consecutive integers float dx2 = 12.634565f; // Output value will be 13 Console.WriteLine(\"Rounded value of \" + dx2 + \" is \" + MathF.Round(dx2)); }}",
"e": 1963,
"s": 1172,
"text": null
},
{
"code": null,
"e": 2028,
"s": 1963,
"text": "Rounded value of 12.43456 is 12\nRounded value of 12.63457 is 13\n"
},
{
"code": null,
"e": 2131,
"s": 2028,
"text": "This method rounds a single precision floating-point value to a specified number of fractional digits."
},
{
"code": null,
"e": 2188,
"s": 2131,
"text": "Syntax: public static float Round (float x, int digits);"
},
{
"code": null,
"e": 2401,
"s": 2188,
"text": "Parameters:x: A single floating-point number which is to be rounded. Type of this parameter is System.Single.y: It is the number of fractional digits in the returned value. Type of this parameter is System.Int32."
},
{
"code": null,
"e": 2540,
"s": 2401,
"text": "Return Type: It returns the integer nearest to x which contains a number of fractional digits equal to y and return type is System.Single."
},
{
"code": null,
"e": 2654,
"s": 2540,
"text": "Exception: This method will give ArgumentOutOfRangeException if the value of y is less than 0 or greater than 15."
},
{
"code": null,
"e": 2663,
"s": 2654,
"text": "Example:"
},
{
"code": "// C# program to demonstrate the// MathF.Round(Single, Int32) Methodusing System; class Geeks { // Main method static void Main(string[] args) { // float type float dx1 = 12.434565f; // using method Console.WriteLine(\"Rounded value of \" + dx1 + \" is \" + MathF.Round(dx1, 4)); // float type float dx2 = 12.634565f; // using method Console.WriteLine(\"Rounded value of \" + dx2 + \" is \" + MathF.Round(dx2, 2)); }}",
"e": 3195,
"s": 2663,
"text": null
},
{
"code": null,
"e": 3268,
"s": 3195,
"text": "Rounded value of 12.43456 is 12.4346\nRounded value of 12.63457 is 12.63\n"
},
{
"code": null,
"e": 3287,
"s": 3268,
"text": "CSharp-MathF-Class"
},
{
"code": null,
"e": 3301,
"s": 3287,
"text": "CSharp-method"
},
{
"code": null,
"e": 3304,
"s": 3301,
"text": "C#"
}
] |
Python | Pandas Series.is_unique | 28 Jan, 2019
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.is_unique attribute return a boolean value. It returns True if the data in the given Series object is unique else it return False.
Syntax:Series.is_unique
Parameter : None
Returns : boolean
Example #1: Use Series.is_unique attribute to check if the underlying data in the given Series object is unique or not.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Chicago']) # Creating the row axis labelssr.index = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5'] # Print the seriesprint(sr)
Output :
Now we will use Series.is_unique attribute to check if the underlying data in the given Series object is unique or it contains some duplicated value.
# check if underlying data is# is unique or notsr.is_unique
Output :
As we can see in the output, the Series.is_unique attribute has returned False indicating the underlying in the given series object is not unique. Example #2 : Use Series.is_unique attribute to check if the underlying data in the given Series object is unique or not.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['1/1/2018', '2/1/2018', '3/1/2018', '4/1/2018']) # Creating the row axis labelssr.index = ['Day 1', 'Day 2', 'Day 3', 'Day 4'] # Print the seriesprint(sr)
Output :
Now we will use Series.is_unique attribute to check if the underlying data in the given Series object is unique or it contains some duplicated value.
# check if underlying data is# is unique or notsr.is_unique
Output :As we can see in the output, the Series.is_unique attribute has returned True indicating the underlying in the given series object is unique.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jan, 2019"
},
{
"code": null,
"e": 242,
"s": 28,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier."
},
{
"code": null,
"e": 499,
"s": 242,
"text": "Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index."
},
{
"code": null,
"e": 644,
"s": 499,
"text": "Pandas Series.is_unique attribute return a boolean value. It returns True if the data in the given Series object is unique else it return False."
},
{
"code": null,
"e": 668,
"s": 644,
"text": "Syntax:Series.is_unique"
},
{
"code": null,
"e": 685,
"s": 668,
"text": "Parameter : None"
},
{
"code": null,
"e": 703,
"s": 685,
"text": "Returns : boolean"
},
{
"code": null,
"e": 823,
"s": 703,
"text": "Example #1: Use Series.is_unique attribute to check if the underlying data in the given Series object is unique or not."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Chicago']) # Creating the row axis labelssr.index = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5'] # Print the seriesprint(sr)",
"e": 1084,
"s": 823,
"text": null
},
{
"code": null,
"e": 1093,
"s": 1084,
"text": "Output :"
},
{
"code": null,
"e": 1243,
"s": 1093,
"text": "Now we will use Series.is_unique attribute to check if the underlying data in the given Series object is unique or it contains some duplicated value."
},
{
"code": "# check if underlying data is# is unique or notsr.is_unique",
"e": 1303,
"s": 1243,
"text": null
},
{
"code": null,
"e": 1312,
"s": 1303,
"text": "Output :"
},
{
"code": null,
"e": 1580,
"s": 1312,
"text": "As we can see in the output, the Series.is_unique attribute has returned False indicating the underlying in the given series object is not unique. Example #2 : Use Series.is_unique attribute to check if the underlying data in the given Series object is unique or not."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['1/1/2018', '2/1/2018', '3/1/2018', '4/1/2018']) # Creating the row axis labelssr.index = ['Day 1', 'Day 2', 'Day 3', 'Day 4'] # Print the seriesprint(sr)",
"e": 1819,
"s": 1580,
"text": null
},
{
"code": null,
"e": 1828,
"s": 1819,
"text": "Output :"
},
{
"code": null,
"e": 1978,
"s": 1828,
"text": "Now we will use Series.is_unique attribute to check if the underlying data in the given Series object is unique or it contains some duplicated value."
},
{
"code": "# check if underlying data is# is unique or notsr.is_unique",
"e": 2038,
"s": 1978,
"text": null
},
{
"code": null,
"e": 2188,
"s": 2038,
"text": "Output :As we can see in the output, the Series.is_unique attribute has returned True indicating the underlying in the given series object is unique."
},
{
"code": null,
"e": 2209,
"s": 2188,
"text": "Python pandas-series"
},
{
"code": null,
"e": 2238,
"s": 2209,
"text": "Python pandas-series-methods"
},
{
"code": null,
"e": 2252,
"s": 2238,
"text": "Python-pandas"
},
{
"code": null,
"e": 2259,
"s": 2252,
"text": "Python"
}
] |
Pearson Correlation Testing in R Programming | 23 Dec, 2021
Correlation is a statistical measure that indicates how strongly two variables are related. It involves the relationship between multiple variables as well. For instance, if one is interested to know whether there is a relationship between the heights of fathers and sons, a correlation coefficient can be calculated to answer this question. Generally, it lies between -1 and +1. It is a scaled version of covariance and provides the direction and strength of a relationship.
There are mainly two types of correlation:
Parametric Correlation – Pearson correlation(r): It measures a linear dependence between two variables (x and y) is known as a parametric correlation test because it depends on the distribution of the data.
Non-Parametric Correlation – Kendall(tau) and Spearman(rho): They are rank-based correlation coefficients, are known as non-parametric correlation.
Pearson Rank Correlation is a parametric correlation. The Pearson correlation coefficient is probably the most widely used measure for linear relationships between two normal distributed variables and thus often just called “correlation coefficient”. The formula for calculating the Pearson Rank Correlation is as follows:
where,
r: pearson correlation coefficient
x and y: two vectors of length n
mx and my: corresponds to the means of x and y, respectively.
Note:
r takes a value between -1 (negative correlation) and 1 (positive correlation).
r = 0 means no correlation.
Can not be applied to ordinal variables.
The sample size should be moderate (20-30) for good estimation.
Outliers can lead to misleading values means not robust with outliers.
R Language provides two methods to calculate the pearson correlation coefficient. By using the functions cor() or cor.test() it can be calculated. It can be noted that cor() computes the correlation coefficient whereas cor.test() computes the test for association or correlation between paired samples. It returns both the correlation coefficient and the significance level(or p-value) of the correlation.
Syntax: cor(x, y, method = “pearson”) cor.test(x, y, method = “pearson”)
Parameters:
x, y: numeric vectors with the same length
method: correlation method
R
# R program to illustrate# pearson Correlation Testing# Using cor() # Taking two numeric# Vectors with same lengthx = c(1, 2, 3, 4, 5, 6, 7)y = c(1, 3, 6, 2, 7, 4, 5) # Calculating# Correlation coefficient# Using cor() methodresult = cor(x, y, method = "pearson") # Print the resultcat("Pearson correlation coefficient is:", result)
Output:
Pearson correlation coefficient is: 0.5357143
R
# R program to illustrate# pearson Correlation Testing# Using cor.test() # Taking two numeric# Vectors with same lengthx = c(1, 2, 3, 4, 5, 6, 7)y = c(1, 3, 6, 2, 7, 4, 5) # Calculating# Correlation coefficient# Using cor.test() methodresult = cor.test(x, y, method = "pearson") # Print the resultprint(result)
Output:
Pearson's product-moment correlation
data: x and y
t = 1.4186, df = 5, p-value = 0.2152
alternative hypothesis: true correlation is not equal to 0
95 percent confidence interval:
-0.3643187 0.9183058
sample estimates:
cor
0.5357143
In the output above:
T is the value of the test statistic (T = 1.4186)
p-value is the significance level of the test statistic (p-value = 0.2152).
alternative hypothesis is a character string describing the alternative hypothesis (true correlation is not equal to 0).
sample estimates is the correlation coefficient. For Pearson correlation coefficient it’s named as cor (Cor.coeff = 0.5357).
Example 3:
Data: Download the CSV file here.
R
# R program to illustrate# Pearson Correlation Testing # Import data into RStudiodf = read.csv("Auto.csv") # Taking two column# Vectors with same lengthx = df$mpgy = df$weight # Calculating# Correlation coefficient# Using cor() methodresult = cor(x, y, method = "pearson") # Print the resultcat("Person correlation coefficient is:", result) # Using cor.test() methodres = cor.test(x, y, method = "pearson")print(res)
Output:
Person correlation coefficient is: -0.8782815
Pearson's product-moment correlation
data: x and y
t = -31.709, df = 298, p-value < 2.2e-16
alternative hypothesis: true correlation is not equal to 0
95 percent confidence interval:
-0.9018288 -0.8495329
sample estimates:
cor
-0.8782815
kumar_satyam
data-science
Machine Learning
R Language
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Dec, 2021"
},
{
"code": null,
"e": 505,
"s": 28,
"text": "Correlation is a statistical measure that indicates how strongly two variables are related. It involves the relationship between multiple variables as well. For instance, if one is interested to know whether there is a relationship between the heights of fathers and sons, a correlation coefficient can be calculated to answer this question. Generally, it lies between -1 and +1. It is a scaled version of covariance and provides the direction and strength of a relationship. "
},
{
"code": null,
"e": 549,
"s": 505,
"text": "There are mainly two types of correlation: "
},
{
"code": null,
"e": 756,
"s": 549,
"text": "Parametric Correlation – Pearson correlation(r): It measures a linear dependence between two variables (x and y) is known as a parametric correlation test because it depends on the distribution of the data."
},
{
"code": null,
"e": 904,
"s": 756,
"text": "Non-Parametric Correlation – Kendall(tau) and Spearman(rho): They are rank-based correlation coefficients, are known as non-parametric correlation."
},
{
"code": null,
"e": 1227,
"s": 904,
"text": "Pearson Rank Correlation is a parametric correlation. The Pearson correlation coefficient is probably the most widely used measure for linear relationships between two normal distributed variables and thus often just called “correlation coefficient”. The formula for calculating the Pearson Rank Correlation is as follows:"
},
{
"code": null,
"e": 1235,
"s": 1227,
"text": "where, "
},
{
"code": null,
"e": 1270,
"s": 1235,
"text": "r: pearson correlation coefficient"
},
{
"code": null,
"e": 1303,
"s": 1270,
"text": "x and y: two vectors of length n"
},
{
"code": null,
"e": 1365,
"s": 1303,
"text": "mx and my: corresponds to the means of x and y, respectively."
},
{
"code": null,
"e": 1371,
"s": 1365,
"text": "Note:"
},
{
"code": null,
"e": 1451,
"s": 1371,
"text": "r takes a value between -1 (negative correlation) and 1 (positive correlation)."
},
{
"code": null,
"e": 1479,
"s": 1451,
"text": "r = 0 means no correlation."
},
{
"code": null,
"e": 1520,
"s": 1479,
"text": "Can not be applied to ordinal variables."
},
{
"code": null,
"e": 1584,
"s": 1520,
"text": "The sample size should be moderate (20-30) for good estimation."
},
{
"code": null,
"e": 1655,
"s": 1584,
"text": "Outliers can lead to misleading values means not robust with outliers."
},
{
"code": null,
"e": 2061,
"s": 1655,
"text": "R Language provides two methods to calculate the pearson correlation coefficient. By using the functions cor() or cor.test() it can be calculated. It can be noted that cor() computes the correlation coefficient whereas cor.test() computes the test for association or correlation between paired samples. It returns both the correlation coefficient and the significance level(or p-value) of the correlation."
},
{
"code": null,
"e": 2134,
"s": 2061,
"text": "Syntax: cor(x, y, method = “pearson”) cor.test(x, y, method = “pearson”)"
},
{
"code": null,
"e": 2147,
"s": 2134,
"text": "Parameters: "
},
{
"code": null,
"e": 2190,
"s": 2147,
"text": "x, y: numeric vectors with the same length"
},
{
"code": null,
"e": 2217,
"s": 2190,
"text": "method: correlation method"
},
{
"code": null,
"e": 2219,
"s": 2217,
"text": "R"
},
{
"code": "# R program to illustrate# pearson Correlation Testing# Using cor() # Taking two numeric# Vectors with same lengthx = c(1, 2, 3, 4, 5, 6, 7)y = c(1, 3, 6, 2, 7, 4, 5) # Calculating# Correlation coefficient# Using cor() methodresult = cor(x, y, method = \"pearson\") # Print the resultcat(\"Pearson correlation coefficient is:\", result)",
"e": 2552,
"s": 2219,
"text": null
},
{
"code": null,
"e": 2561,
"s": 2552,
"text": "Output: "
},
{
"code": null,
"e": 2607,
"s": 2561,
"text": "Pearson correlation coefficient is: 0.5357143"
},
{
"code": null,
"e": 2609,
"s": 2607,
"text": "R"
},
{
"code": "# R program to illustrate# pearson Correlation Testing# Using cor.test() # Taking two numeric# Vectors with same lengthx = c(1, 2, 3, 4, 5, 6, 7)y = c(1, 3, 6, 2, 7, 4, 5) # Calculating# Correlation coefficient# Using cor.test() methodresult = cor.test(x, y, method = \"pearson\") # Print the resultprint(result)",
"e": 2920,
"s": 2609,
"text": null
},
{
"code": null,
"e": 2929,
"s": 2920,
"text": "Output: "
},
{
"code": null,
"e": 3173,
"s": 2929,
"text": "Pearson's product-moment correlation\n\ndata: x and y\nt = 1.4186, df = 5, p-value = 0.2152\nalternative hypothesis: true correlation is not equal to 0\n95 percent confidence interval:\n -0.3643187 0.9183058\nsample estimates:\n cor \n0.5357143 "
},
{
"code": null,
"e": 3194,
"s": 3173,
"text": "In the output above:"
},
{
"code": null,
"e": 3244,
"s": 3194,
"text": "T is the value of the test statistic (T = 1.4186)"
},
{
"code": null,
"e": 3320,
"s": 3244,
"text": "p-value is the significance level of the test statistic (p-value = 0.2152)."
},
{
"code": null,
"e": 3441,
"s": 3320,
"text": "alternative hypothesis is a character string describing the alternative hypothesis (true correlation is not equal to 0)."
},
{
"code": null,
"e": 3566,
"s": 3441,
"text": "sample estimates is the correlation coefficient. For Pearson correlation coefficient it’s named as cor (Cor.coeff = 0.5357)."
},
{
"code": null,
"e": 3577,
"s": 3566,
"text": "Example 3:"
},
{
"code": null,
"e": 3611,
"s": 3577,
"text": "Data: Download the CSV file here."
},
{
"code": null,
"e": 3613,
"s": 3611,
"text": "R"
},
{
"code": "# R program to illustrate# Pearson Correlation Testing # Import data into RStudiodf = read.csv(\"Auto.csv\") # Taking two column# Vectors with same lengthx = df$mpgy = df$weight # Calculating# Correlation coefficient# Using cor() methodresult = cor(x, y, method = \"pearson\") # Print the resultcat(\"Person correlation coefficient is:\", result) # Using cor.test() methodres = cor.test(x, y, method = \"pearson\")print(res)",
"e": 4030,
"s": 3613,
"text": null
},
{
"code": null,
"e": 4039,
"s": 4030,
"text": "Output: "
},
{
"code": null,
"e": 4339,
"s": 4039,
"text": "Person correlation coefficient is: -0.8782815\n Pearson's product-moment correlation\n\ndata: x and y\nt = -31.709, df = 298, p-value < 2.2e-16\nalternative hypothesis: true correlation is not equal to 0\n95 percent confidence interval:\n -0.9018288 -0.8495329\nsample estimates:\n cor \n-0.8782815 "
},
{
"code": null,
"e": 4352,
"s": 4339,
"text": "kumar_satyam"
},
{
"code": null,
"e": 4365,
"s": 4352,
"text": "data-science"
},
{
"code": null,
"e": 4382,
"s": 4365,
"text": "Machine Learning"
},
{
"code": null,
"e": 4393,
"s": 4382,
"text": "R Language"
},
{
"code": null,
"e": 4410,
"s": 4393,
"text": "Machine Learning"
}
] |
Getting the current date and time with timestamp in local and other timezones in Golang | 22 Jun, 2020
We can get the current date and time with a timestamp in local with the help of Location() function and other timezones in Golang with the help of LoadLocation() function. The LoadLocation() takes a string(city name) as parameter and returns the place..location() takes no parameter and return location .time.now() returns current date and time with a timestamp in local.
1. location(): It takes no parameter and returns local time.
2. func LoadLocation(name string) (*Location, error): It takes the place name as a parameter. Returns the location with the given name or return nil as an error.
3. time.Now() : It return current time.
Example 1:
package main import ( "fmt" "time") //main functionfunc main() { // with the help of time.Now() // store the local time t := time.Now() // print location and local time fmt.Println("Location : ", t.Location(), " Time : ", t)}
Output:
Location : Local Time : 2009-11-10 23:00:00 +0000 UTC m=+0.000000001
Example 2:
package main import ( "fmt" "time") // main functionfunc main() { // with the help of time.Now() // store the local time t := time.Now() // print location and local time location, err := time.LoadLocation("America/New_York") if err != nil { fmt.Println(err) } // America/New_York fmt.Println("Location : ", location, " Time : ", t.In(location)) }
Output:
Location : America/New_York Time : 2009-11-10 18:00:00 -0500 EST
GoLang-time
Picked
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Go
strings.Replace() Function in Golang With Examples
How to convert a string in lower case in Golang?
How to Sort Golang Map By Keys or Values?
Different Ways to Find the Type of Variable in Golang
Anonymous function in Go Language
Strings in Golang
Golang Maps
How to Trim a String in Golang?
Nested Structure in Golang | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Jun, 2020"
},
{
"code": null,
"e": 400,
"s": 28,
"text": "We can get the current date and time with a timestamp in local with the help of Location() function and other timezones in Golang with the help of LoadLocation() function. The LoadLocation() takes a string(city name) as parameter and returns the place..location() takes no parameter and return location .time.now() returns current date and time with a timestamp in local."
},
{
"code": null,
"e": 461,
"s": 400,
"text": "1. location(): It takes no parameter and returns local time."
},
{
"code": null,
"e": 623,
"s": 461,
"text": "2. func LoadLocation(name string) (*Location, error): It takes the place name as a parameter. Returns the location with the given name or return nil as an error."
},
{
"code": null,
"e": 663,
"s": 623,
"text": "3. time.Now() : It return current time."
},
{
"code": null,
"e": 674,
"s": 663,
"text": "Example 1:"
},
{
"code": "package main import ( \"fmt\" \"time\") //main functionfunc main() { // with the help of time.Now() // store the local time t := time.Now() // print location and local time fmt.Println(\"Location : \", t.Location(), \" Time : \", t)}",
"e": 931,
"s": 674,
"text": null
},
{
"code": null,
"e": 939,
"s": 931,
"text": "Output:"
},
{
"code": null,
"e": 1012,
"s": 939,
"text": "Location : Local Time : 2009-11-10 23:00:00 +0000 UTC m=+0.000000001\n"
},
{
"code": null,
"e": 1023,
"s": 1012,
"text": "Example 2:"
},
{
"code": "package main import ( \"fmt\" \"time\") // main functionfunc main() { // with the help of time.Now() // store the local time t := time.Now() // print location and local time location, err := time.LoadLocation(\"America/New_York\") if err != nil { fmt.Println(err) } // America/New_York fmt.Println(\"Location : \", location, \" Time : \", t.In(location)) }",
"e": 1427,
"s": 1023,
"text": null
},
{
"code": null,
"e": 1435,
"s": 1427,
"text": "Output:"
},
{
"code": null,
"e": 1504,
"s": 1435,
"text": "Location : America/New_York Time : 2009-11-10 18:00:00 -0500 EST\n"
},
{
"code": null,
"e": 1516,
"s": 1504,
"text": "GoLang-time"
},
{
"code": null,
"e": 1523,
"s": 1516,
"text": "Picked"
},
{
"code": null,
"e": 1535,
"s": 1523,
"text": "Go Language"
},
{
"code": null,
"e": 1633,
"s": 1535,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1646,
"s": 1633,
"text": "Arrays in Go"
},
{
"code": null,
"e": 1697,
"s": 1646,
"text": "strings.Replace() Function in Golang With Examples"
},
{
"code": null,
"e": 1746,
"s": 1697,
"text": "How to convert a string in lower case in Golang?"
},
{
"code": null,
"e": 1788,
"s": 1746,
"text": "How to Sort Golang Map By Keys or Values?"
},
{
"code": null,
"e": 1842,
"s": 1788,
"text": "Different Ways to Find the Type of Variable in Golang"
},
{
"code": null,
"e": 1876,
"s": 1842,
"text": "Anonymous function in Go Language"
},
{
"code": null,
"e": 1894,
"s": 1876,
"text": "Strings in Golang"
},
{
"code": null,
"e": 1906,
"s": 1894,
"text": "Golang Maps"
},
{
"code": null,
"e": 1938,
"s": 1906,
"text": "How to Trim a String in Golang?"
}
] |
Underscore.js _.isEmpty() Function | 20 Dec, 2021
_.isEmpty() function:
It is used to check whether a list, array, string, object etc is empty or not.
It first finds out the length of the passed argument and then decides.
If length is zero, then the output is true otherwise false.
Syntax:
_.isEmpty(object)
Parameters:It takes only one argument which is the object.Return value:It returns true if the argument passed is empty, i.e., does not have any elements in it. Otherwise it returns false.Examples:
Passing an empty element to the _.isEmpty() function:The _.isEmpty() function takes the element from the list one by one and starts counting the length of the array. Each time it encounters an element, it increments length by one. Then, when the array finishes, it checks if the array’s length is zero ( it returns true) or greater than zero (then, it returns false). Here, we have an empty array so the output will be true.
html
<!-- Write HTML code here --><html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"> </script></head> <body> <script type="text/javascript"> console.log(_.isEmpty([])); </script></body> </html>
Output:
Passing an array with 6 elements to the _.isEmpty() function:The procedure for the check function will be same as in the above example. Here, we have 6 elements in the array which implies that at the finish of the array, it’s length will be 6. so, the length is not equal to 0 and hence the answer will be false.
html
<!-- Write HTML code here --><html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"> </script></head> <body> <script type="text/javascript"> console.log(_.isEmpty([1, 2, 3, 4, 5, 6])); </script></body> </html>
Output:
Passing a list of characters to _.isEmpty() function:The _.isEmpty() function will work the same as in the examples above. It implies that it does not distinguish between whether the array has numbers, characters or is empty. It will work the same on all the array and find out their length. In this example we have an array of length 4. Hence, the output will be false.
html
<html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"> </script></head> <body> <script type="text/javascript"> console.log(_.isEmpty(['HTML', 'CSS', 'JS', 'AJAX'])); </script></body> </html>
Output:
Passing an element zero to the _.isEmpty() function:Do not get confused with the empty array and an array containing zero as an element. Since the elements is zero, so you must be thinking that the array is empty. But the array contains an element and since the _isEmpty() calculates the length, therefore the length of the below array will be one which is greater than zero. And hence the output will be false.
html
<!-- Write HTML code here --> <html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"> </script></head> <body> <script type="text/javascript"> console.log(_.isEmpty([0])); </script></body> </html>
Output:
NOTE: These commands will not work in Google console or in firefox as for these additional files need to be added which they didn’t have added.So, add the given links to your HTML file and then run them. The links are as follows:
html
<!-- Write HTML code here --><script type="text/javascript" src ="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>
An example is shown below:
shubham_singh
arorakashish0911
simmytarika5
JavaScript - Underscore.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
How to append HTML code to a div using JavaScript ?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Dec, 2021"
},
{
"code": null,
"e": 50,
"s": 28,
"text": "_.isEmpty() function:"
},
{
"code": null,
"e": 129,
"s": 50,
"text": "It is used to check whether a list, array, string, object etc is empty or not."
},
{
"code": null,
"e": 200,
"s": 129,
"text": "It first finds out the length of the passed argument and then decides."
},
{
"code": null,
"e": 260,
"s": 200,
"text": "If length is zero, then the output is true otherwise false."
},
{
"code": null,
"e": 269,
"s": 260,
"text": "Syntax: "
},
{
"code": null,
"e": 287,
"s": 269,
"text": "_.isEmpty(object)"
},
{
"code": null,
"e": 485,
"s": 287,
"text": "Parameters:It takes only one argument which is the object.Return value:It returns true if the argument passed is empty, i.e., does not have any elements in it. Otherwise it returns false.Examples: "
},
{
"code": null,
"e": 910,
"s": 485,
"text": "Passing an empty element to the _.isEmpty() function:The _.isEmpty() function takes the element from the list one by one and starts counting the length of the array. Each time it encounters an element, it increments length by one. Then, when the array finishes, it checks if the array’s length is zero ( it returns true) or greater than zero (then, it returns false). Here, we have an empty array so the output will be true."
},
{
"code": null,
"e": 915,
"s": 910,
"text": "html"
},
{
"code": "<!-- Write HTML code here --><html> <head> <script src = \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\"> </script></head> <body> <script type=\"text/javascript\"> console.log(_.isEmpty([])); </script></body> </html>",
"e": 1187,
"s": 915,
"text": null
},
{
"code": null,
"e": 1195,
"s": 1187,
"text": "Output:"
},
{
"code": null,
"e": 1508,
"s": 1195,
"text": "Passing an array with 6 elements to the _.isEmpty() function:The procedure for the check function will be same as in the above example. Here, we have 6 elements in the array which implies that at the finish of the array, it’s length will be 6. so, the length is not equal to 0 and hence the answer will be false."
},
{
"code": null,
"e": 1513,
"s": 1508,
"text": "html"
},
{
"code": "<!-- Write HTML code here --><html> <head> <script src = \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\"> </script></head> <body> <script type=\"text/javascript\"> console.log(_.isEmpty([1, 2, 3, 4, 5, 6])); </script></body> </html>",
"e": 1800,
"s": 1513,
"text": null
},
{
"code": null,
"e": 1808,
"s": 1800,
"text": "Output:"
},
{
"code": null,
"e": 2179,
"s": 1808,
"text": "Passing a list of characters to _.isEmpty() function:The _.isEmpty() function will work the same as in the examples above. It implies that it does not distinguish between whether the array has numbers, characters or is empty. It will work the same on all the array and find out their length. In this example we have an array of length 4. Hence, the output will be false."
},
{
"code": null,
"e": 2184,
"s": 2179,
"text": "html"
},
{
"code": "<html> <head> <script src = \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\"> </script></head> <body> <script type=\"text/javascript\"> console.log(_.isEmpty(['HTML', 'CSS', 'JS', 'AJAX'])); </script></body> </html>",
"e": 2454,
"s": 2184,
"text": null
},
{
"code": null,
"e": 2462,
"s": 2454,
"text": "Output:"
},
{
"code": null,
"e": 2874,
"s": 2462,
"text": "Passing an element zero to the _.isEmpty() function:Do not get confused with the empty array and an array containing zero as an element. Since the elements is zero, so you must be thinking that the array is empty. But the array contains an element and since the _isEmpty() calculates the length, therefore the length of the below array will be one which is greater than zero. And hence the output will be false."
},
{
"code": null,
"e": 2879,
"s": 2874,
"text": "html"
},
{
"code": "<!-- Write HTML code here --> <html> <head> <script src = \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\"> </script></head> <body> <script type=\"text/javascript\"> console.log(_.isEmpty([0])); </script></body> </html>",
"e": 3153,
"s": 2879,
"text": null
},
{
"code": null,
"e": 3161,
"s": 3153,
"text": "Output:"
},
{
"code": null,
"e": 3392,
"s": 3161,
"text": "NOTE: These commands will not work in Google console or in firefox as for these additional files need to be added which they didn’t have added.So, add the given links to your HTML file and then run them. The links are as follows: "
},
{
"code": null,
"e": 3397,
"s": 3392,
"text": "html"
},
{
"code": "<!-- Write HTML code here --><script type=\"text/javascript\" src =\"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\"></script>",
"e": 3551,
"s": 3397,
"text": null
},
{
"code": null,
"e": 3578,
"s": 3551,
"text": "An example is shown below:"
},
{
"code": null,
"e": 3592,
"s": 3578,
"text": "shubham_singh"
},
{
"code": null,
"e": 3609,
"s": 3592,
"text": "arorakashish0911"
},
{
"code": null,
"e": 3622,
"s": 3609,
"text": "simmytarika5"
},
{
"code": null,
"e": 3649,
"s": 3622,
"text": "JavaScript - Underscore.js"
},
{
"code": null,
"e": 3660,
"s": 3649,
"text": "JavaScript"
},
{
"code": null,
"e": 3677,
"s": 3660,
"text": "Web Technologies"
},
{
"code": null,
"e": 3775,
"s": 3677,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3836,
"s": 3775,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3908,
"s": 3836,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 3948,
"s": 3908,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 3989,
"s": 3948,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 4041,
"s": 3989,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 4074,
"s": 4041,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 4136,
"s": 4074,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 4197,
"s": 4136,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4247,
"s": 4197,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Python – Regex Lookbehind | 24 Feb, 2021
Regex Lookbehind is used as an assertion in Python regular expressions(re) to determine success or failure whether the pattern is behind i.e to the right of the parser’s current position. They don’t match anything. Hence, Regex Lookbehind and lookahead are termed as a zero-width assertion.
Syntax:
# Positive lookbehind
(?<=<lookbehind_regex>)
# Positive lookahead
(?=<lookahead_regex>)
In this post we will talk about regex lookbehind.
Example 1:
Python3
# importing regeximport re # Regex Lookbehind exampleexample = re.search(r'(?<=geeks)\w', 'geeksforgeeks') print(example.group())print("Pattern found from index", example.start(), example.end())
Output:
f
Pattern found from index 5 6
The regex lookbehind assertion (?<=geeks) specifies that what precedes before any word character(‘\w’) must be ‘geeks’ string. In this case, it’s the character ‘f’ before which ‘geeks’ string occurs.
Example 2:
Python3
# importing regeximport re # Regex Lookbehind exampleexample = re.search(r'(?<=geeks)\d', 'geeksforgeeks')print(example)
Output:
None
In the above example, the output is None because there is no decimal digit preceded by ‘geeks’ string.
Lookbehind portion is not part of the search string. They are important when you don’t want the output to return lookbehind portion present in search string but want to use it to match pattern which is preceded by a particular section. Below example will make this clear:
Example 3:
Python3
import re # Using lookbehindexample1 = re.search(r'(?<=[a-z])\d', "geeks12")print(example1.group()) # Without using lookbehindexample2 = re.search(r'([a-z])\d', "geeks12")print(example2.group())
Output:
1
s1
Using lookbehind the output generated is ‘1’ whereas without using lookbehind the output generated is ‘s1’. Any word character (\w) which precedes any decimal digit is consumed by regex so it doesn’t become part of the search string.
Negative Lookbehind
Negative Lookbehind is the opposite of lookbehind. It is to assure that the search string is not preceded by <lookbehind_regex>.
Syntax:
(?<!<lookbehind_regex>)
Negative Lookbehind
Example 4:
Python3
import re # Lookbehindexample1 = re.search('(?<=[a-z])geeks', 'geeksforgeeks')print(example1.group()) # Negative Lookbehindexample2 = re.search('(?<![a-z])123', 'geeks123') # Output is None because 123 # is preceded by a character i.e 's'print(example2)
Output:
geeks
None
python-regex
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": "\n24 Feb, 2021"
},
{
"code": null,
"e": 319,
"s": 28,
"text": "Regex Lookbehind is used as an assertion in Python regular expressions(re) to determine success or failure whether the pattern is behind i.e to the right of the parser’s current position. They don’t match anything. Hence, Regex Lookbehind and lookahead are termed as a zero-width assertion."
},
{
"code": null,
"e": 327,
"s": 319,
"text": "Syntax:"
},
{
"code": null,
"e": 417,
"s": 327,
"text": "# Positive lookbehind\n(?<=<lookbehind_regex>)\n\n# Positive lookahead\n(?=<lookahead_regex>)"
},
{
"code": null,
"e": 467,
"s": 417,
"text": "In this post we will talk about regex lookbehind."
},
{
"code": null,
"e": 478,
"s": 467,
"text": "Example 1:"
},
{
"code": null,
"e": 486,
"s": 478,
"text": "Python3"
},
{
"code": "# importing regeximport re # Regex Lookbehind exampleexample = re.search(r'(?<=geeks)\\w', 'geeksforgeeks') print(example.group())print(\"Pattern found from index\", example.start(), example.end())",
"e": 709,
"s": 486,
"text": null
},
{
"code": null,
"e": 717,
"s": 709,
"text": "Output:"
},
{
"code": null,
"e": 748,
"s": 717,
"text": "f\nPattern found from index 5 6"
},
{
"code": null,
"e": 948,
"s": 748,
"text": "The regex lookbehind assertion (?<=geeks) specifies that what precedes before any word character(‘\\w’) must be ‘geeks’ string. In this case, it’s the character ‘f’ before which ‘geeks’ string occurs."
},
{
"code": null,
"e": 959,
"s": 948,
"text": "Example 2:"
},
{
"code": null,
"e": 967,
"s": 959,
"text": "Python3"
},
{
"code": "# importing regeximport re # Regex Lookbehind exampleexample = re.search(r'(?<=geeks)\\d', 'geeksforgeeks')print(example)",
"e": 1109,
"s": 967,
"text": null
},
{
"code": null,
"e": 1117,
"s": 1109,
"text": "Output:"
},
{
"code": null,
"e": 1122,
"s": 1117,
"text": "None"
},
{
"code": null,
"e": 1225,
"s": 1122,
"text": "In the above example, the output is None because there is no decimal digit preceded by ‘geeks’ string."
},
{
"code": null,
"e": 1497,
"s": 1225,
"text": "Lookbehind portion is not part of the search string. They are important when you don’t want the output to return lookbehind portion present in search string but want to use it to match pattern which is preceded by a particular section. Below example will make this clear:"
},
{
"code": null,
"e": 1508,
"s": 1497,
"text": "Example 3:"
},
{
"code": null,
"e": 1516,
"s": 1508,
"text": "Python3"
},
{
"code": "import re # Using lookbehindexample1 = re.search(r'(?<=[a-z])\\d', \"geeks12\")print(example1.group()) # Without using lookbehindexample2 = re.search(r'([a-z])\\d', \"geeks12\")print(example2.group())",
"e": 1753,
"s": 1516,
"text": null
},
{
"code": null,
"e": 1761,
"s": 1753,
"text": "Output:"
},
{
"code": null,
"e": 1766,
"s": 1761,
"text": "1\ns1"
},
{
"code": null,
"e": 2002,
"s": 1766,
"text": "Using lookbehind the output generated is ‘1’ whereas without using lookbehind the output generated is ‘s1’. Any word character (\\w) which precedes any decimal digit is consumed by regex so it doesn’t become part of the search string. "
},
{
"code": null,
"e": 2022,
"s": 2002,
"text": "Negative Lookbehind"
},
{
"code": null,
"e": 2151,
"s": 2022,
"text": "Negative Lookbehind is the opposite of lookbehind. It is to assure that the search string is not preceded by <lookbehind_regex>."
},
{
"code": null,
"e": 2159,
"s": 2151,
"text": "Syntax:"
},
{
"code": null,
"e": 2204,
"s": 2159,
"text": "(?<!<lookbehind_regex>) \nNegative Lookbehind"
},
{
"code": null,
"e": 2215,
"s": 2204,
"text": "Example 4:"
},
{
"code": null,
"e": 2223,
"s": 2215,
"text": "Python3"
},
{
"code": "import re # Lookbehindexample1 = re.search('(?<=[a-z])geeks', 'geeksforgeeks')print(example1.group()) # Negative Lookbehindexample2 = re.search('(?<![a-z])123', 'geeks123') # Output is None because 123 # is preceded by a character i.e 's'print(example2)",
"e": 2522,
"s": 2223,
"text": null
},
{
"code": null,
"e": 2530,
"s": 2522,
"text": "Output:"
},
{
"code": null,
"e": 2541,
"s": 2530,
"text": "geeks\nNone"
},
{
"code": null,
"e": 2554,
"s": 2541,
"text": "python-regex"
},
{
"code": null,
"e": 2561,
"s": 2554,
"text": "Python"
},
{
"code": null,
"e": 2659,
"s": 2561,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2677,
"s": 2659,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2719,
"s": 2677,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2741,
"s": 2719,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2776,
"s": 2741,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2802,
"s": 2776,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2834,
"s": 2802,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2863,
"s": 2834,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2890,
"s": 2863,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2920,
"s": 2890,
"text": "Iterate over a list in Python"
}
] |
How to Create Splash Screen Without an Extra Activity in Android? | 18 Jul, 2021
A splash screen is the first screen of the app when it is opened. It is used to display some basic introductory information such as the company logo, content, etc just before the app loads completely. In this article, we will follow the best practice to create a Splash screen that is without creating an extra activity for it and it will be gone as soon as the activity loads. Below is a sample video to show what we are going to build. You can use Java/Kotlin for this project.
Note:
To create a splash screen in Java: Creating a Splash Screen
To create a splash screen in Kotlin: How to Create a Splash Screen in Android using Kotlin?
To create an animated splash screen: How to Create an Animated Splash Screen in Android?
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. You can select Kotlin/Java as the programming language.
Step 2: Create a new drawable file and name it “splash_image.xml”
Go to res -> drawable -> splash_image.xml and the following code. Comments are added.
XML
<?xml version="1.0" encoding="utf-8"?><layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <!--Add the following code add the drawable color to white--> <item android:drawable="@color/white"/> <!--Add the logo that you want to display and its gravity to centre--> <item android:drawable="@drawable/gfg_logo" android:gravity="center"/></layer-list>
Step 3: Add a new style in the themes.xml file
Go to res -> values -> themes.xml add a new style and name it “splashScreenTheme“. This will hold the information that we want to show on our splash screen such as WindowBackground and status bar color.
XML
<resources xmlns:tools="http://schemas.android.com/tools"> <!--Create a new style and name it splashScreenTheme and add the following code--> <style name="splashScreenTheme" parent="Theme.MaterialComponents.Light.NoActionBar"> <item name="android:windowBackground">@drawable/splash_image</item> <item name="android:statusBarColor">@color/black</item> </style> <!-- Default Code do not change it. we will use it as our theme after the aplash screen is shown--> <!-- Base application theme --> <style name="Theme.SplashAPIGFG" parent="Theme.MaterialComponents.DayNight.NoActionBar"> <!-- Primary brand color--> <item name="colorPrimary">#2F8D46</item> <item name="colorPrimaryVariant">#2F8D46</item> <item name="colorOnPrimary">@color/white</item> <!-- Secondary brand color. --> <item name="colorSecondary">#2F8D46</item> <item name="colorSecondaryVariant">@color/teal_700</item> <item name="colorOnSecondary">@color/black</item> <!-- Status bar color. --> <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item> <!-- Customize your theme here. --> </style> </resources>
Step 4: Add the style to the manifest file
XML
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.introidx.splashapigfg"> <!--In the theme add the style that we just created--> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/splashScreenTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application></manifest>
Step 5:Working with the MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Here set the theme that we want to display after the splash screen is shown.
Kotlin
import androidx.appcompat.app.AppCompatActivityimport android.os.Bundle class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // add the default theme here which we want // to display after the splash screen is shown setTheme(R.style.Theme_SplashAPIGFG) setContentView(R.layout.activity_main) }}
Note: activity_main.xml file just has a Text View to display a message.
XML
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="This is test app for Splash Screen" app:layout_constraintBottom_toBottomOf="parent" android:textStyle="bold" android:textSize="22sp" android:textColor="@color/black" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
Output:
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android SDK and it's Components
Flutter - Custom Bottom Navigation Bar
How to Communicate Between Fragments in Android?
Retrofit with Kotlin Coroutine in Android
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android UI Layouts
Kotlin Array
How to Communicate Between Fragments in Android?
Retrofit with Kotlin Coroutine in Android | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Jul, 2021"
},
{
"code": null,
"e": 508,
"s": 28,
"text": "A splash screen is the first screen of the app when it is opened. It is used to display some basic introductory information such as the company logo, content, etc just before the app loads completely. In this article, we will follow the best practice to create a Splash screen that is without creating an extra activity for it and it will be gone as soon as the activity loads. Below is a sample video to show what we are going to build. You can use Java/Kotlin for this project."
},
{
"code": null,
"e": 514,
"s": 508,
"text": "Note:"
},
{
"code": null,
"e": 574,
"s": 514,
"text": "To create a splash screen in Java: Creating a Splash Screen"
},
{
"code": null,
"e": 666,
"s": 574,
"text": "To create a splash screen in Kotlin: How to Create a Splash Screen in Android using Kotlin?"
},
{
"code": null,
"e": 755,
"s": 666,
"text": "To create an animated splash screen: How to Create an Animated Splash Screen in Android?"
},
{
"code": null,
"e": 784,
"s": 755,
"text": "Step 1: Create a new project"
},
{
"code": null,
"e": 951,
"s": 784,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. You can select Kotlin/Java as the programming language."
},
{
"code": null,
"e": 1017,
"s": 951,
"text": "Step 2: Create a new drawable file and name it “splash_image.xml”"
},
{
"code": null,
"e": 1103,
"s": 1017,
"text": "Go to res -> drawable -> splash_image.xml and the following code. Comments are added."
},
{
"code": null,
"e": 1107,
"s": 1103,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><layer-list xmlns:android=\"http://schemas.android.com/apk/res/android\"> <!--Add the following code add the drawable color to white--> <item android:drawable=\"@color/white\"/> <!--Add the logo that you want to display and its gravity to centre--> <item android:drawable=\"@drawable/gfg_logo\" android:gravity=\"center\"/></layer-list>",
"e": 1493,
"s": 1107,
"text": null
},
{
"code": null,
"e": 1540,
"s": 1493,
"text": "Step 3: Add a new style in the themes.xml file"
},
{
"code": null,
"e": 1743,
"s": 1540,
"text": "Go to res -> values -> themes.xml add a new style and name it “splashScreenTheme“. This will hold the information that we want to show on our splash screen such as WindowBackground and status bar color."
},
{
"code": null,
"e": 1747,
"s": 1743,
"text": "XML"
},
{
"code": "<resources xmlns:tools=\"http://schemas.android.com/tools\"> <!--Create a new style and name it splashScreenTheme and add the following code--> <style name=\"splashScreenTheme\" parent=\"Theme.MaterialComponents.Light.NoActionBar\"> <item name=\"android:windowBackground\">@drawable/splash_image</item> <item name=\"android:statusBarColor\">@color/black</item> </style> <!-- Default Code do not change it. we will use it as our theme after the aplash screen is shown--> <!-- Base application theme --> <style name=\"Theme.SplashAPIGFG\" parent=\"Theme.MaterialComponents.DayNight.NoActionBar\"> <!-- Primary brand color--> <item name=\"colorPrimary\">#2F8D46</item> <item name=\"colorPrimaryVariant\">#2F8D46</item> <item name=\"colorOnPrimary\">@color/white</item> <!-- Secondary brand color. --> <item name=\"colorSecondary\">#2F8D46</item> <item name=\"colorSecondaryVariant\">@color/teal_700</item> <item name=\"colorOnSecondary\">@color/black</item> <!-- Status bar color. --> <item name=\"android:statusBarColor\" tools:targetApi=\"l\">?attr/colorPrimaryVariant</item> <!-- Customize your theme here. --> </style> </resources>",
"e": 2987,
"s": 1747,
"text": null
},
{
"code": null,
"e": 3030,
"s": 2987,
"text": "Step 4: Add the style to the manifest file"
},
{
"code": null,
"e": 3034,
"s": 3030,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.introidx.splashapigfg\"> <!--In the theme add the style that we just created--> <application android:allowBackup=\"true\" android:icon=\"@mipmap/ic_launcher\" android:label=\"@string/app_name\" android:roundIcon=\"@mipmap/ic_launcher_round\" android:supportsRtl=\"true\" android:theme=\"@style/splashScreenTheme\"> <activity android:name=\".MainActivity\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity> </application></manifest>",
"e": 3806,
"s": 3034,
"text": null
},
{
"code": null,
"e": 3851,
"s": 3806,
"text": "Step 5:Working with the MainActivity.kt file"
},
{
"code": null,
"e": 4040,
"s": 3851,
"text": "Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Here set the theme that we want to display after the splash screen is shown."
},
{
"code": null,
"e": 4047,
"s": 4040,
"text": "Kotlin"
},
{
"code": "import androidx.appcompat.app.AppCompatActivityimport android.os.Bundle class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // add the default theme here which we want // to display after the splash screen is shown setTheme(R.style.Theme_SplashAPIGFG) setContentView(R.layout.activity_main) }}",
"e": 4477,
"s": 4047,
"text": null
},
{
"code": null,
"e": 4549,
"s": 4477,
"text": "Note: activity_main.xml file just has a Text View to display a message."
},
{
"code": null,
"e": 4553,
"s": 4549,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"This is test app for Splash Screen\" app:layout_constraintBottom_toBottomOf=\"parent\" android:textStyle=\"bold\" android:textSize=\"22sp\" android:textColor=\"@color/black\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> </androidx.constraintlayout.widget.ConstraintLayout>",
"e": 5449,
"s": 4553,
"text": null
},
{
"code": null,
"e": 5457,
"s": 5449,
"text": "Output:"
},
{
"code": null,
"e": 5465,
"s": 5457,
"text": "Android"
},
{
"code": null,
"e": 5472,
"s": 5465,
"text": "Kotlin"
},
{
"code": null,
"e": 5480,
"s": 5472,
"text": "Android"
},
{
"code": null,
"e": 5578,
"s": 5480,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5647,
"s": 5578,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
},
{
"code": null,
"e": 5679,
"s": 5647,
"text": "Android SDK and it's Components"
},
{
"code": null,
"e": 5718,
"s": 5679,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 5767,
"s": 5718,
"text": "How to Communicate Between Fragments in Android?"
},
{
"code": null,
"e": 5809,
"s": 5767,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 5878,
"s": 5809,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
},
{
"code": null,
"e": 5897,
"s": 5878,
"text": "Android UI Layouts"
},
{
"code": null,
"e": 5910,
"s": 5897,
"text": "Kotlin Array"
},
{
"code": null,
"e": 5959,
"s": 5910,
"text": "How to Communicate Between Fragments in Android?"
}
] |
Defaultdict in Python | 08 Jul, 2022
Dictionary in Python is an unordered collection of data values that are used to store data values like a map. Unlike other Data Types that hold only single value as an element, the Dictionary holds key-value pair. In Dictionary, the key must be unique and immutable. This means that a Python Tuple can be a key whereas a Python List can not. A Dictionary can be created by placing a sequence of elements within curly {} braces, separated by ‘comma’.
Example:
Python3
# Python program to demonstrate# dictionary Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'} print("Dictionary:") print(Dict)print(Dict[1]) # Uncommenting this print(Dict[4])# will raise a KeyError as the# 4 is not present in the dictionary
Output:
Dictionary:
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Geeks
Traceback (most recent call last):
File "/home/1ca83108cc81344dc7137900693ced08.py", line 11, in
print(Dict[4])
KeyError: 4
Sometimes, when the KeyError is raised, it might become a problem. To overcome this Python introduces another dictionary like container known as Defaultdict which is present inside the collections module.Note: For more information, refer to Python Dictionary.
Defaultdict is a container like dictionaries present in the module collections. Defaultdict is a sub-class of the dictionary class that returns a dictionary-like object. The functionality of both dictionaries and defaultdict are almost same except for the fact that defaultdict never raises a KeyError. It provides a default value for the key that does not exists.
Syntax: defaultdict(default_factory)Parameters:
default_factory: A function returning the default value for the dictionary defined. If this argument is absent then the dictionary raises a KeyError.
Example:
Python3
# Python program to demonstrate# defaultdict from collections import defaultdict # Function to return a default# values for keys that is not# presentdef def_value(): return "Not Present" # Defining the dictd = defaultdict(def_value)d["a"] = 1d["b"] = 2 print(d["a"])print(d["b"])print(d["c"])
Output:
1
2
Not Present
Defaultdict adds one writable instance variable and one method in addition to the standard dictionary operations. The instance variable is the default_factory parameter and the method provided is __missing__.
Default_factory: It is a function returning the default value for the dictionary defined. If this argument is absent then the dictionary raises a KeyError.Example:
Python3
# Python program to demonstrate# default_factory argument of # defaultdict from collections import defaultdict # Defining the dict and passing # lambda as default_factory argumentd = defaultdict(lambda: "Not Present")d["a"] = 1d["b"] = 2 print(d["a"])print(d["b"])print(d["c"])
Output:
1
2
Not Present
__missing__(): This function is used to provide the default value for the dictionary. This function takes default_factory as an argument and if this argument is None, a KeyError is raised otherwise it provides a default value for the given key. This method is basically called by the __getitem__() method of the dict class when the requested key is not found. __getitem__() raises or return the value returned by the __missing__(). method.Example:
Python3
# Python program to demonstrate# defaultdict from collections import defaultdict # Defining the dictd = defaultdict(lambda: "Not Present")d["a"] = 1d["b"] = 2 # Provides the default value # for the keyprint(d.__missing__('a'))print(d.__missing__('d'))
Output:
Not Present
Not Present
When the list class is passed as the default_factory argument, then a defaultdict is created with the values that are list.Example:
Python3
# Python program to demonstrate# defaultdict from collections import defaultdict # Defining a dictd = defaultdict(list) for i in range(5): d[i].append(i) print("Dictionary with values as list:")print(d)
Output:
Dictionary with values as list:
defaultdict(<class 'list'>, {0: [0], 1: [1], 2: [2], 3: [3], 4: [4]})
When the int class is passed as the default_factory argument, then a defaultdict is created with default value as zero.Example:
Python3
# Python program to demonstrate# defaultdict from collections import defaultdict # Defining the dictd = defaultdict(int) L = [1, 2, 3, 4, 2, 4, 1, 2] # Iterate through the list# for keeping the countfor i in L: # The default value is 0 # so there is no need to # enter the key first d[i] += 1 print(d)
Output:
defaultdict(<class 'int'>, {1: 2, 2: 3, 3: 1, 4: 2})
cbostock20
chhabradhanvi
bagley7
Python collections-module
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n08 Jul, 2022"
},
{
"code": null,
"e": 504,
"s": 54,
"text": "Dictionary in Python is an unordered collection of data values that are used to store data values like a map. Unlike other Data Types that hold only single value as an element, the Dictionary holds key-value pair. In Dictionary, the key must be unique and immutable. This means that a Python Tuple can be a key whereas a Python List can not. A Dictionary can be created by placing a sequence of elements within curly {} braces, separated by ‘comma’."
},
{
"code": null,
"e": 513,
"s": 504,
"text": "Example:"
},
{
"code": null,
"e": 521,
"s": 513,
"text": "Python3"
},
{
"code": "# Python program to demonstrate# dictionary Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'} print(\"Dictionary:\") print(Dict)print(Dict[1]) # Uncommenting this print(Dict[4])# will raise a KeyError as the# 4 is not present in the dictionary",
"e": 759,
"s": 521,
"text": null
},
{
"code": null,
"e": 767,
"s": 759,
"text": "Output:"
},
{
"code": null,
"e": 820,
"s": 767,
"text": "Dictionary:\n{1: 'Geeks', 2: 'For', 3: 'Geeks'}\nGeeks"
},
{
"code": null,
"e": 951,
"s": 820,
"text": "Traceback (most recent call last):\n File \"/home/1ca83108cc81344dc7137900693ced08.py\", line 11, in \n print(Dict[4])\nKeyError: 4"
},
{
"code": null,
"e": 1212,
"s": 951,
"text": "Sometimes, when the KeyError is raised, it might become a problem. To overcome this Python introduces another dictionary like container known as Defaultdict which is present inside the collections module.Note: For more information, refer to Python Dictionary. "
},
{
"code": null,
"e": 1577,
"s": 1212,
"text": "Defaultdict is a container like dictionaries present in the module collections. Defaultdict is a sub-class of the dictionary class that returns a dictionary-like object. The functionality of both dictionaries and defaultdict are almost same except for the fact that defaultdict never raises a KeyError. It provides a default value for the key that does not exists."
},
{
"code": null,
"e": 1627,
"s": 1577,
"text": "Syntax: defaultdict(default_factory)Parameters: "
},
{
"code": null,
"e": 1777,
"s": 1627,
"text": "default_factory: A function returning the default value for the dictionary defined. If this argument is absent then the dictionary raises a KeyError."
},
{
"code": null,
"e": 1786,
"s": 1777,
"text": "Example:"
},
{
"code": null,
"e": 1794,
"s": 1786,
"text": "Python3"
},
{
"code": "# Python program to demonstrate# defaultdict from collections import defaultdict # Function to return a default# values for keys that is not# presentdef def_value(): return \"Not Present\" # Defining the dictd = defaultdict(def_value)d[\"a\"] = 1d[\"b\"] = 2 print(d[\"a\"])print(d[\"b\"])print(d[\"c\"])",
"e": 2102,
"s": 1794,
"text": null
},
{
"code": null,
"e": 2110,
"s": 2102,
"text": "Output:"
},
{
"code": null,
"e": 2127,
"s": 2110,
"text": "1\n2\nNot Present "
},
{
"code": null,
"e": 2336,
"s": 2127,
"text": "Defaultdict adds one writable instance variable and one method in addition to the standard dictionary operations. The instance variable is the default_factory parameter and the method provided is __missing__."
},
{
"code": null,
"e": 2500,
"s": 2336,
"text": "Default_factory: It is a function returning the default value for the dictionary defined. If this argument is absent then the dictionary raises a KeyError.Example:"
},
{
"code": null,
"e": 2508,
"s": 2500,
"text": "Python3"
},
{
"code": "# Python program to demonstrate# default_factory argument of # defaultdict from collections import defaultdict # Defining the dict and passing # lambda as default_factory argumentd = defaultdict(lambda: \"Not Present\")d[\"a\"] = 1d[\"b\"] = 2 print(d[\"a\"])print(d[\"b\"])print(d[\"c\"])",
"e": 2797,
"s": 2508,
"text": null
},
{
"code": null,
"e": 2805,
"s": 2797,
"text": "Output:"
},
{
"code": null,
"e": 2821,
"s": 2805,
"text": "1\n2\nNot Present"
},
{
"code": null,
"e": 3269,
"s": 2821,
"text": "__missing__(): This function is used to provide the default value for the dictionary. This function takes default_factory as an argument and if this argument is None, a KeyError is raised otherwise it provides a default value for the given key. This method is basically called by the __getitem__() method of the dict class when the requested key is not found. __getitem__() raises or return the value returned by the __missing__(). method.Example:"
},
{
"code": null,
"e": 3277,
"s": 3269,
"text": "Python3"
},
{
"code": "# Python program to demonstrate# defaultdict from collections import defaultdict # Defining the dictd = defaultdict(lambda: \"Not Present\")d[\"a\"] = 1d[\"b\"] = 2 # Provides the default value # for the keyprint(d.__missing__('a'))print(d.__missing__('d'))",
"e": 3540,
"s": 3277,
"text": null
},
{
"code": null,
"e": 3548,
"s": 3540,
"text": "Output:"
},
{
"code": null,
"e": 3573,
"s": 3548,
"text": "Not Present\nNot Present "
},
{
"code": null,
"e": 3705,
"s": 3573,
"text": "When the list class is passed as the default_factory argument, then a defaultdict is created with the values that are list.Example:"
},
{
"code": null,
"e": 3713,
"s": 3705,
"text": "Python3"
},
{
"code": "# Python program to demonstrate# defaultdict from collections import defaultdict # Defining a dictd = defaultdict(list) for i in range(5): d[i].append(i) print(\"Dictionary with values as list:\")print(d)",
"e": 3931,
"s": 3713,
"text": null
},
{
"code": null,
"e": 3939,
"s": 3931,
"text": "Output:"
},
{
"code": null,
"e": 4041,
"s": 3939,
"text": "Dictionary with values as list:\ndefaultdict(<class 'list'>, {0: [0], 1: [1], 2: [2], 3: [3], 4: [4]})"
},
{
"code": null,
"e": 4169,
"s": 4041,
"text": "When the int class is passed as the default_factory argument, then a defaultdict is created with default value as zero.Example:"
},
{
"code": null,
"e": 4177,
"s": 4169,
"text": "Python3"
},
{
"code": "# Python program to demonstrate# defaultdict from collections import defaultdict # Defining the dictd = defaultdict(int) L = [1, 2, 3, 4, 2, 4, 1, 2] # Iterate through the list# for keeping the countfor i in L: # The default value is 0 # so there is no need to # enter the key first d[i] += 1 print(d)",
"e": 4519,
"s": 4177,
"text": null
},
{
"code": null,
"e": 4527,
"s": 4519,
"text": "Output:"
},
{
"code": null,
"e": 4580,
"s": 4527,
"text": "defaultdict(<class 'int'>, {1: 2, 2: 3, 3: 1, 4: 2})"
},
{
"code": null,
"e": 4591,
"s": 4580,
"text": "cbostock20"
},
{
"code": null,
"e": 4605,
"s": 4591,
"text": "chhabradhanvi"
},
{
"code": null,
"e": 4613,
"s": 4605,
"text": "bagley7"
},
{
"code": null,
"e": 4639,
"s": 4613,
"text": "Python collections-module"
},
{
"code": null,
"e": 4646,
"s": 4639,
"text": "Python"
},
{
"code": null,
"e": 4662,
"s": 4646,
"text": "Python Programs"
}
] |
HTML <Textarea>maxlength attribute | 09 Jan, 2020
The HTML <Textarea>maxlength attribute is used to specify the maximum number of characters enters into the Textarea element.
Syntax:
<Textarea maxlength ="number">
Attribute Value:
Example:
<!DOCTYPE html> <html> <head> <title>Textarea maxlength Attribute</title> <style> } fieldset { width: 50%; margin-left: 22%; } h1 { color: green; } </style> </head> <body> <center> <h1>GeeksforGeeks</h1> <h2>Textarea maxlength Attribute</h2> <textarea form="mygeeks" maxlength="9"> </textarea> <br> <form id="mygeeks"> Name: <input type="text" name="usrname"> <input type="submit"> </form> </center> </body> </html>
Output:
Supported Browsers: The browsers supported by HTML <Textarea>maxlength attribute are listed below:
Google Chrome
Internet Explorer 10.0 +
Firefox 4.0
Opera 15.0
Safari
HTML-Attributes
HTML-Basics
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 Jan, 2020"
},
{
"code": null,
"e": 153,
"s": 28,
"text": "The HTML <Textarea>maxlength attribute is used to specify the maximum number of characters enters into the Textarea element."
},
{
"code": null,
"e": 161,
"s": 153,
"text": "Syntax:"
},
{
"code": null,
"e": 192,
"s": 161,
"text": "<Textarea maxlength =\"number\">"
},
{
"code": null,
"e": 209,
"s": 192,
"text": "Attribute Value:"
},
{
"code": null,
"e": 218,
"s": 209,
"text": "Example:"
},
{
"code": "<!DOCTYPE html> <html> <head> <title>Textarea maxlength Attribute</title> <style> } fieldset { width: 50%; margin-left: 22%; } h1 { color: green; } </style> </head> <body> <center> <h1>GeeksforGeeks</h1> <h2>Textarea maxlength Attribute</h2> <textarea form=\"mygeeks\" maxlength=\"9\"> </textarea> <br> <form id=\"mygeeks\"> Name: <input type=\"text\" name=\"usrname\"> <input type=\"submit\"> </form> </center> </body> </html> ",
"e": 798,
"s": 218,
"text": null
},
{
"code": null,
"e": 806,
"s": 798,
"text": "Output:"
},
{
"code": null,
"e": 905,
"s": 806,
"text": "Supported Browsers: The browsers supported by HTML <Textarea>maxlength attribute are listed below:"
},
{
"code": null,
"e": 919,
"s": 905,
"text": "Google Chrome"
},
{
"code": null,
"e": 944,
"s": 919,
"text": "Internet Explorer 10.0 +"
},
{
"code": null,
"e": 956,
"s": 944,
"text": "Firefox 4.0"
},
{
"code": null,
"e": 967,
"s": 956,
"text": "Opera 15.0"
},
{
"code": null,
"e": 974,
"s": 967,
"text": "Safari"
},
{
"code": null,
"e": 990,
"s": 974,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 1002,
"s": 990,
"text": "HTML-Basics"
},
{
"code": null,
"e": 1007,
"s": 1002,
"text": "HTML"
},
{
"code": null,
"e": 1024,
"s": 1007,
"text": "Web Technologies"
},
{
"code": null,
"e": 1029,
"s": 1024,
"text": "HTML"
}
] |
PostgreSQL – Size of value | 28 Aug, 2020
The size of a value means the space needed to store a specific value in the database table.In this article we will look into function that is used to get the size of the PostgreSQL database value.The pg_column_size() function is used to get the size of a value.
Syntax: select pg_column_size(no. of values :: type of value)
Here we will be using a sample database for reference which is described here and can be downloaded from hereExample 1:Here we will query for space required to store 10 values of smallint type using the below command:
select pg_column_size(10::smallint);
Output:
Example 2:Here we will query for space required to store 10 values of int type using the below command:
select pg_column_size(10::int);
Output:
Example 3:Here we will query for space required to store 10 values of bigint type using the below command:
select pg_column_size(10::bigint);
Output:
PostgreSQL-function
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - INSERT
PostgreSQL - SELECT
PostgreSQL - LIMIT with OFFSET clause
PostgreSQL- LOWER function
PostgreSQL - EXISTS Operator
PostgreSQL - BIGINT Integer Data Type
PostgreSQL - ROW_NUMBER Function
PostgreSQL - Select Into
PostgreSQL - LAST_VALUE Function
PostgreSQL - DROP INDEX | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Aug, 2020"
},
{
"code": null,
"e": 290,
"s": 28,
"text": "The size of a value means the space needed to store a specific value in the database table.In this article we will look into function that is used to get the size of the PostgreSQL database value.The pg_column_size() function is used to get the size of a value."
},
{
"code": null,
"e": 352,
"s": 290,
"text": "Syntax: select pg_column_size(no. of values :: type of value)"
},
{
"code": null,
"e": 570,
"s": 352,
"text": "Here we will be using a sample database for reference which is described here and can be downloaded from hereExample 1:Here we will query for space required to store 10 values of smallint type using the below command:"
},
{
"code": null,
"e": 607,
"s": 570,
"text": "select pg_column_size(10::smallint);"
},
{
"code": null,
"e": 615,
"s": 607,
"text": "Output:"
},
{
"code": null,
"e": 719,
"s": 615,
"text": "Example 2:Here we will query for space required to store 10 values of int type using the below command:"
},
{
"code": null,
"e": 751,
"s": 719,
"text": "select pg_column_size(10::int);"
},
{
"code": null,
"e": 759,
"s": 751,
"text": "Output:"
},
{
"code": null,
"e": 866,
"s": 759,
"text": "Example 3:Here we will query for space required to store 10 values of bigint type using the below command:"
},
{
"code": null,
"e": 901,
"s": 866,
"text": "select pg_column_size(10::bigint);"
},
{
"code": null,
"e": 909,
"s": 901,
"text": "Output:"
},
{
"code": null,
"e": 929,
"s": 909,
"text": "PostgreSQL-function"
},
{
"code": null,
"e": 940,
"s": 929,
"text": "PostgreSQL"
},
{
"code": null,
"e": 1038,
"s": 940,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1058,
"s": 1038,
"text": "PostgreSQL - INSERT"
},
{
"code": null,
"e": 1078,
"s": 1058,
"text": "PostgreSQL - SELECT"
},
{
"code": null,
"e": 1116,
"s": 1078,
"text": "PostgreSQL - LIMIT with OFFSET clause"
},
{
"code": null,
"e": 1143,
"s": 1116,
"text": "PostgreSQL- LOWER function"
},
{
"code": null,
"e": 1172,
"s": 1143,
"text": "PostgreSQL - EXISTS Operator"
},
{
"code": null,
"e": 1210,
"s": 1172,
"text": "PostgreSQL - BIGINT Integer Data Type"
},
{
"code": null,
"e": 1243,
"s": 1210,
"text": "PostgreSQL - ROW_NUMBER Function"
},
{
"code": null,
"e": 1268,
"s": 1243,
"text": "PostgreSQL - Select Into"
},
{
"code": null,
"e": 1301,
"s": 1268,
"text": "PostgreSQL - LAST_VALUE Function"
}
] |
Python | ScreenManager in Kivy using .kv file | 16 Jan, 2022
Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications.
The screen manager is a widget which is used to managing multiple screens for your application. The default ScreenManager displays only one Screen at a time and uses a TransitionBase to switch from one Screen to another. Multiple transitions are supported.The ScreenManager and Screen class are imported. The ScreenManager will be used for the root like:
from kivy.uix.screenmanager import ScreenManager, Screen
Note:The default ScreenManager.transition is a SlideTransition with options direction and duration.
Basic Approach:
1) import kivy
2) import kivyApp
3) import Screen Manager, Screen, ""Transitions you want to use""
4) Set minimum version(optional)
5) Create Different Screen classes and pass them
6) Create features of Screen classes in .kv file
:: Add features in different screens
7) Create App class
8) return screen manager
9) Run an instance of the class
Below is the implementation of the code with .kv file in .py file.
Python3
# Program to Show how to create a switch# import kivy module import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # this restrict the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require('1.9.0') # Builder is used when .kv file is# to be used in .py filefrom kivy.lang import Builder # The screen manager is a widget# dedicated to managing multiple screens for your application.from kivy.uix.screenmanager import ScreenManager, Screen # You can create your kv code in the Python fileBuilder.load_string("""<ScreenOne>: BoxLayout: Button: text: "Go to Screen 2" background_color : 0, 0, 1, 1 on_press: # You can define the duration of the change # and the direction of the slide root.manager.transition.direction = 'left' root.manager.transition.duration = 1 root.manager.current = 'screen_two' <ScreenTwo>: BoxLayout: Button: text: "Go to Screen 3" background_color : 1, 1, 0, 1 on_press: root.manager.transition.direction = 'left' root.manager.transition.duration = 1 root.manager.current = 'screen_three' <ScreenThree>: BoxLayout: Button: text: "Go to Screen 4" background_color : 1, 0, 1, 1 on_press: root.manager.transition.direction = 'left' root.manager.transition.duration = 1 root.manager.current = 'screen_four' <ScreenFour>: BoxLayout: Button: text: "Go to Screen 5" background_color : 0, 1, 1, 1 on_press: root.manager.transition.direction = 'left' root.manager.transition.duration = 1 root.manager.current = 'screen_five' <ScreenFive>: BoxLayout: Button: text: "Go to Screen 1" background_color : 1, 0, 0, 1 on_press: root.manager.transition.direction = 'right' root.manager.current = 'screen_one' """) # Create a class for all screens in which you can include# helpful methods specific to that screenclass ScreenOne(Screen): pass class ScreenTwo(Screen): pass class ScreenThree(Screen): pass class ScreenFour(Screen): pass class ScreenFive(Screen): pass # The ScreenManager controls moving between screensscreen_manager = ScreenManager() # Add the screens to the manager and then supply a name# that is used to switch screensscreen_manager.add_widget(ScreenOne(name ="screen_one"))screen_manager.add_widget(ScreenTwo(name ="screen_two"))screen_manager.add_widget(ScreenThree(name ="screen_three"))screen_manager.add_widget(ScreenFour(name ="screen_four"))screen_manager.add_widget(ScreenFive(name ="screen_five")) # Create the App classclass ScreenApp(App): def build(self): return screen_manager # run the appsample_app = ScreenApp()sample_app.run()
Output:
Changing Transitions:
You have multiple transitions available by default, such as:
NoTransition – switches screens instantly with no animation
SlideTransition – slide the screen in/out, from any direction
CardTransition – new screen slides on the previous or the old one slides off the new one depending on the mode
SwapTransition – implementation of the iOS swap transition
FadeTransition – shader to fade the screen in/out
WipeTransition – shader to wipe the screens from right to left
FallOutTransition – shader where the old screen ‘falls’ and becomes transparent, revealing the new one behind it.
RiseInTransition – shader where the new screen rises from the screen center while fading from transparent to opaque.
You can easily switch transitions by changing the ScreenManager.transition property:
sm = ScreenManager(transition=FadeTransition())
Python3
# Program to Show how to create a switch# import kivy module import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # this restrict the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require('1.9.0') # Builder is used when .kv file is# to be used in .py filefrom kivy.lang import Builder # The screen manager is a widget# dedicated to managing multiple screens for your application.from kivy.uix.screenmanager import (ScreenManager, Screen, NoTransition,SlideTransition, CardTransition, SwapTransition,FadeTransition, WipeTransition, FallOutTransition, RiseInTransition) # You can create your kv code in the Python fileBuilder.load_string("""<ScreenOne>: BoxLayout: Button: text: "Go to Screen 2" background_color : 0, 0, 1, 1 on_press: # You can define the duration of the change # and the direction of the slide root.manager.transition.direction = 'left' root.manager.transition.duration = 1 root.manager.current = 'screen_two' <ScreenTwo>: BoxLayout: Button: text: "Go to Screen 3" background_color : 1, 1, 0, 1 on_press: root.manager.transition.direction = 'left' root.manager.transition.duration = 1 root.manager.current = 'screen_three' <ScreenThree>: BoxLayout: Button: text: "Go to Screen 4" background_color : 1, 0, 1, 1 on_press: root.manager.transition.direction = 'left' root.manager.transition.duration = 1 root.manager.current = 'screen_four' <ScreenFour>: BoxLayout: Button: text: "Go to Screen 5" background_color : 0, 1, 1, 1 on_press: root.manager.transition.direction = 'left' root.manager.transition.duration = 1 root.manager.current = 'screen_five' <ScreenFive>: BoxLayout: Button: text: "Go to Screen 1" background_color : 1, 0, 0, 1 on_press: root.manager.transition.direction = 'right' root.manager.current = 'screen_one' """) # Create a class for all screens in which you can include# helpful methods specific to that screenclass ScreenOne(Screen): pass class ScreenTwo(Screen): pass class ScreenThree(Screen): pass class ScreenFour(Screen): pass class ScreenFive(Screen): pass # The ScreenManager controls moving between screens# You can change the transitions accordinglyscreen_manager = ScreenManager(transition = RiseInTransition()) # Add the screens to the manager and then supply a name# that is used to switch screensscreen_manager.add_widget(ScreenOne(name ="screen_one"))screen_manager.add_widget(ScreenTwo(name ="screen_two"))screen_manager.add_widget(ScreenThree(name ="screen_three"))screen_manager.add_widget(ScreenFour(name ="screen_four"))screen_manager.add_widget(ScreenFive(name ="screen_five")) # Create the App classclass ScreenApp(App): def build(self): return screen_manager # run the appsample_app = ScreenApp()sample_app.run()
Note: Code is Same some points is added in code don’t confuse.Output Video of Different transitions –
ruhelaa48
saurabh1990aror
Python-gui
Python-kivy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n16 Jan, 2022"
},
{
"code": null,
"e": 289,
"s": 52,
"text": "Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications. "
},
{
"code": null,
"e": 645,
"s": 289,
"text": "The screen manager is a widget which is used to managing multiple screens for your application. The default ScreenManager displays only one Screen at a time and uses a TransitionBase to switch from one Screen to another. Multiple transitions are supported.The ScreenManager and Screen class are imported. The ScreenManager will be used for the root like: "
},
{
"code": null,
"e": 702,
"s": 645,
"text": "from kivy.uix.screenmanager import ScreenManager, Screen"
},
{
"code": null,
"e": 803,
"s": 702,
"text": "Note:The default ScreenManager.transition is a SlideTransition with options direction and duration. "
},
{
"code": null,
"e": 1172,
"s": 803,
"text": "Basic Approach:\n1) import kivy\n2) import kivyApp\n3) import Screen Manager, Screen, \"\"Transitions you want to use\"\" \n4) Set minimum version(optional)\n5) Create Different Screen classes and pass them\n6) Create features of Screen classes in .kv file \n :: Add features in different screens\n7) Create App class\n8) return screen manager\n9) Run an instance of the class"
},
{
"code": null,
"e": 1240,
"s": 1172,
"text": "Below is the implementation of the code with .kv file in .py file. "
},
{
"code": null,
"e": 1248,
"s": 1240,
"text": "Python3"
},
{
"code": "# Program to Show how to create a switch# import kivy module import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # this restrict the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require('1.9.0') # Builder is used when .kv file is# to be used in .py filefrom kivy.lang import Builder # The screen manager is a widget# dedicated to managing multiple screens for your application.from kivy.uix.screenmanager import ScreenManager, Screen # You can create your kv code in the Python fileBuilder.load_string(\"\"\"<ScreenOne>: BoxLayout: Button: text: \"Go to Screen 2\" background_color : 0, 0, 1, 1 on_press: # You can define the duration of the change # and the direction of the slide root.manager.transition.direction = 'left' root.manager.transition.duration = 1 root.manager.current = 'screen_two' <ScreenTwo>: BoxLayout: Button: text: \"Go to Screen 3\" background_color : 1, 1, 0, 1 on_press: root.manager.transition.direction = 'left' root.manager.transition.duration = 1 root.manager.current = 'screen_three' <ScreenThree>: BoxLayout: Button: text: \"Go to Screen 4\" background_color : 1, 0, 1, 1 on_press: root.manager.transition.direction = 'left' root.manager.transition.duration = 1 root.manager.current = 'screen_four' <ScreenFour>: BoxLayout: Button: text: \"Go to Screen 5\" background_color : 0, 1, 1, 1 on_press: root.manager.transition.direction = 'left' root.manager.transition.duration = 1 root.manager.current = 'screen_five' <ScreenFive>: BoxLayout: Button: text: \"Go to Screen 1\" background_color : 1, 0, 0, 1 on_press: root.manager.transition.direction = 'right' root.manager.current = 'screen_one' \"\"\") # Create a class for all screens in which you can include# helpful methods specific to that screenclass ScreenOne(Screen): pass class ScreenTwo(Screen): pass class ScreenThree(Screen): pass class ScreenFour(Screen): pass class ScreenFive(Screen): pass # The ScreenManager controls moving between screensscreen_manager = ScreenManager() # Add the screens to the manager and then supply a name# that is used to switch screensscreen_manager.add_widget(ScreenOne(name =\"screen_one\"))screen_manager.add_widget(ScreenTwo(name =\"screen_two\"))screen_manager.add_widget(ScreenThree(name =\"screen_three\"))screen_manager.add_widget(ScreenFour(name =\"screen_four\"))screen_manager.add_widget(ScreenFive(name =\"screen_five\")) # Create the App classclass ScreenApp(App): def build(self): return screen_manager # run the appsample_app = ScreenApp()sample_app.run()",
"e": 4349,
"s": 1248,
"text": null
},
{
"code": null,
"e": 4359,
"s": 4349,
"text": "Output: "
},
{
"code": null,
"e": 4386,
"s": 4363,
"text": "Changing Transitions: "
},
{
"code": null,
"e": 4449,
"s": 4386,
"text": "You have multiple transitions available by default, such as: "
},
{
"code": null,
"e": 4509,
"s": 4449,
"text": "NoTransition – switches screens instantly with no animation"
},
{
"code": null,
"e": 4571,
"s": 4509,
"text": "SlideTransition – slide the screen in/out, from any direction"
},
{
"code": null,
"e": 4682,
"s": 4571,
"text": "CardTransition – new screen slides on the previous or the old one slides off the new one depending on the mode"
},
{
"code": null,
"e": 4741,
"s": 4682,
"text": "SwapTransition – implementation of the iOS swap transition"
},
{
"code": null,
"e": 4791,
"s": 4741,
"text": "FadeTransition – shader to fade the screen in/out"
},
{
"code": null,
"e": 4854,
"s": 4791,
"text": "WipeTransition – shader to wipe the screens from right to left"
},
{
"code": null,
"e": 4968,
"s": 4854,
"text": "FallOutTransition – shader where the old screen ‘falls’ and becomes transparent, revealing the new one behind it."
},
{
"code": null,
"e": 5085,
"s": 4968,
"text": "RiseInTransition – shader where the new screen rises from the screen center while fading from transparent to opaque."
},
{
"code": null,
"e": 5172,
"s": 5085,
"text": "You can easily switch transitions by changing the ScreenManager.transition property: "
},
{
"code": null,
"e": 5220,
"s": 5172,
"text": "sm = ScreenManager(transition=FadeTransition())"
},
{
"code": null,
"e": 5230,
"s": 5222,
"text": "Python3"
},
{
"code": "# Program to Show how to create a switch# import kivy module import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # this restrict the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require('1.9.0') # Builder is used when .kv file is# to be used in .py filefrom kivy.lang import Builder # The screen manager is a widget# dedicated to managing multiple screens for your application.from kivy.uix.screenmanager import (ScreenManager, Screen, NoTransition,SlideTransition, CardTransition, SwapTransition,FadeTransition, WipeTransition, FallOutTransition, RiseInTransition) # You can create your kv code in the Python fileBuilder.load_string(\"\"\"<ScreenOne>: BoxLayout: Button: text: \"Go to Screen 2\" background_color : 0, 0, 1, 1 on_press: # You can define the duration of the change # and the direction of the slide root.manager.transition.direction = 'left' root.manager.transition.duration = 1 root.manager.current = 'screen_two' <ScreenTwo>: BoxLayout: Button: text: \"Go to Screen 3\" background_color : 1, 1, 0, 1 on_press: root.manager.transition.direction = 'left' root.manager.transition.duration = 1 root.manager.current = 'screen_three' <ScreenThree>: BoxLayout: Button: text: \"Go to Screen 4\" background_color : 1, 0, 1, 1 on_press: root.manager.transition.direction = 'left' root.manager.transition.duration = 1 root.manager.current = 'screen_four' <ScreenFour>: BoxLayout: Button: text: \"Go to Screen 5\" background_color : 0, 1, 1, 1 on_press: root.manager.transition.direction = 'left' root.manager.transition.duration = 1 root.manager.current = 'screen_five' <ScreenFive>: BoxLayout: Button: text: \"Go to Screen 1\" background_color : 1, 0, 0, 1 on_press: root.manager.transition.direction = 'right' root.manager.current = 'screen_one' \"\"\") # Create a class for all screens in which you can include# helpful methods specific to that screenclass ScreenOne(Screen): pass class ScreenTwo(Screen): pass class ScreenThree(Screen): pass class ScreenFour(Screen): pass class ScreenFive(Screen): pass # The ScreenManager controls moving between screens# You can change the transitions accordinglyscreen_manager = ScreenManager(transition = RiseInTransition()) # Add the screens to the manager and then supply a name# that is used to switch screensscreen_manager.add_widget(ScreenOne(name =\"screen_one\"))screen_manager.add_widget(ScreenTwo(name =\"screen_two\"))screen_manager.add_widget(ScreenThree(name =\"screen_three\"))screen_manager.add_widget(ScreenFour(name =\"screen_four\"))screen_manager.add_widget(ScreenFive(name =\"screen_five\")) # Create the App classclass ScreenApp(App): def build(self): return screen_manager # run the appsample_app = ScreenApp()sample_app.run()",
"e": 8538,
"s": 5230,
"text": null
},
{
"code": null,
"e": 8642,
"s": 8538,
"text": "Note: Code is Same some points is added in code don’t confuse.Output Video of Different transitions – "
},
{
"code": null,
"e": 8654,
"s": 8644,
"text": "ruhelaa48"
},
{
"code": null,
"e": 8670,
"s": 8654,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 8681,
"s": 8670,
"text": "Python-gui"
},
{
"code": null,
"e": 8693,
"s": 8681,
"text": "Python-kivy"
},
{
"code": null,
"e": 8700,
"s": 8693,
"text": "Python"
}
] |
Kotlin Regular Expression | 22 Sep, 2021
Regular Expressions are a fundamental part of almost every programming language and Kotlin is no exception to it. In Kotlin, the support for regular expression is provided through Regex class. An object of this class represents a regular expression, that can be used for string matching purposes.
class Regex
We can easily find use of regular expressions in different kind of software, from simplest to incredibly complex applications. Before preceding this article have a look at Regular Expression in Java
<init>(pattern: String): This constructor creates a regular expression based on the pattern string. <init>(pattern: String, option: RegexOption): This constructor creates a regular expression based on the specified pattern and the option. The option is a constant of RegexOption enum class. <init>(pattern: String, options: Set<RegexOption>): This constructor creates a regular expression on the basis of the specified string pattern and the set of options specified in the set.
<init>(pattern: String): This constructor creates a regular expression based on the pattern string.
<init>(pattern: String, option: RegexOption): This constructor creates a regular expression based on the specified pattern and the option. The option is a constant of RegexOption enum class.
<init>(pattern: String, options: Set<RegexOption>): This constructor creates a regular expression on the basis of the specified string pattern and the set of options specified in the set.
val options: Set<RegexOption> : It contains the set of options which are to be used at the time of regex creation. val pattern: String : It contains the string describing the pattern.
val options: Set<RegexOption> : It contains the set of options which are to be used at the time of regex creation.
val pattern: String : It contains the string describing the pattern.
containsMatchIn() – This function returns a boolean indicating whether there exists any match of our pattern in the input.
fun containsMatchIn(input: CharSequence): Boolean
Example to demonstrate containsMatchIn() function in Kotlin
Java
fun main(){ // Regex to match any string starting with 'a' val pattern = Regex("^a") println(pattern.containsMatchIn("abc")) println(pattern.containsMatchIn("bac"))}
Output:
true
false
find() – This function returns the first matched substring pertaining to our pattern in the input, from the specified starting index.
fun find(input: CharSequence, startIndex: Int): MatchResult?
Example to demonstrate find() function in Kotlin
Java
fun main(){ // Regex to match "ll" in a string val pattern1 = Regex("ll") val ans : MatchResult? = pattern1.find("HelloHello", 5) println(ans ?.value)}
Output:
ll
findAll() – This function returns all the matchings of the specified pattern in the input, searching from the given start index.
fun findAll(
input: CharSequence,
startIndex: Int
): Sequence
Example to demonstrate findAll function in Kotlin
Java
fun main(){ // Regex to match a 3 letter pattern beginning with ab val pattern2 = Regex("ab.") val ans1 : Sequence<MatchResult> = pattern2.findAll("abcfffgdbabs", 0) // forEach loop used to display all the matches ans1.forEach() { matchResult -> println(matchResult.value) } println()}
Output:
abc
abs
matches() – This function returns a boolean indicating whether the input string completely matches the pattern or not.
infix fun matches(input: CharSequence): Boolean
Example to demonstrate matches() function in Kotlin
Java
fun main(){ // Tests demonstrating entire string match val pattern = Regex("g([ee]+)ks?") println(pattern.matches("geeks")) println(pattern.matches("geeeeeeeeeeks")) println(pattern.matches("geeksforgeeks"))}
Output:
true
true
false
matchEntire() – This function tries to match the entire input to the specified pattern string, returning the string if it matches. If does not match the string, return null.
fun matchEntire(input: CharSequence): MatchResult?
Example to demonstrate matchEntire() function in Kotlin
Java
fun main(){ // Tests demonstrating entire string match var pattern = Regex("geeks?") println(pattern.matchEntire("geeks")?.value) println(pattern.matchEntire("geeeeeeeks")?.value) pattern = Regex("""\D+""") println(pattern.matchEntire("geeks")?.value) println(pattern.matchEntire("geeks12345")?.value)}
Output:
geeks
null
geeks
null
replace() – This function replaces all the occurrences of the pattern in the input string with the specified replacement string.
fun replace(input: CharSequence, replacement: String): String
replaceFirst() – This function replaces the first match of the regular expression in the input with the replacement string.
fun replaceFirst(
input: CharSequence,
replacement: String
): String
Example to demonstrate replace() and replaceFirst() functions in Kotlin
Java
fun main(){ // Tests demonstrating replacement functions val pattern4 = Regex("xyz") // replace all xyz with abc in the string println(pattern4.replace("xyzxyzzzzzzzzz", "abc")) // replace only first xyz with abc not all println(pattern4.replaceFirst("xyzddddddxyz", "abc")) println()}
Output:
abcabczzzzzzzz // replace all
abcddddddxyz // replace first matching only
split() – This function breaks the input string into tokens according to the specified parameter.
fun split(input: CharSequence, limit: Int): List
Example to demonstrate split() function in Kotlin
Java
fun main(){ // Tests demonstrating split function val pattern = Regex("\\s+") // separate for white-spaces val ans : List<String> = pattern.split("This is a sentence") ans.forEach { word -> println(word) }}
Output:
This
is
a
sentence
ruhelaa48
Picked
Kotlin
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android RecyclerView in Kotlin
Retrofit with Kotlin Coroutine in Android
Kotlin constructor
How to Communicate Between Fragments in Android?
Kotlin Setters and Getters
How to Add and Customize Back Button of Action Bar in Android?
Suspend Function In Kotlin Coroutines
How to Change the Color of Status Bar in an Android App?
Kotlin when expression | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Sep, 2021"
},
{
"code": null,
"e": 327,
"s": 28,
"text": "Regular Expressions are a fundamental part of almost every programming language and Kotlin is no exception to it. In Kotlin, the support for regular expression is provided through Regex class. An object of this class represents a regular expression, that can be used for string matching purposes. "
},
{
"code": null,
"e": 339,
"s": 327,
"text": "class Regex"
},
{
"code": null,
"e": 539,
"s": 339,
"text": "We can easily find use of regular expressions in different kind of software, from simplest to incredibly complex applications. Before preceding this article have a look at Regular Expression in Java "
},
{
"code": null,
"e": 1022,
"s": 539,
"text": "<init>(pattern: String): This constructor creates a regular expression based on the pattern string. <init>(pattern: String, option: RegexOption): This constructor creates a regular expression based on the specified pattern and the option. The option is a constant of RegexOption enum class. <init>(pattern: String, options: Set<RegexOption>): This constructor creates a regular expression on the basis of the specified string pattern and the set of options specified in the set. "
},
{
"code": null,
"e": 1124,
"s": 1022,
"text": "<init>(pattern: String): This constructor creates a regular expression based on the pattern string. "
},
{
"code": null,
"e": 1317,
"s": 1124,
"text": "<init>(pattern: String, option: RegexOption): This constructor creates a regular expression based on the specified pattern and the option. The option is a constant of RegexOption enum class. "
},
{
"code": null,
"e": 1507,
"s": 1317,
"text": "<init>(pattern: String, options: Set<RegexOption>): This constructor creates a regular expression on the basis of the specified string pattern and the set of options specified in the set. "
},
{
"code": null,
"e": 1694,
"s": 1507,
"text": "val options: Set<RegexOption> : It contains the set of options which are to be used at the time of regex creation. val pattern: String : It contains the string describing the pattern. "
},
{
"code": null,
"e": 1811,
"s": 1694,
"text": "val options: Set<RegexOption> : It contains the set of options which are to be used at the time of regex creation. "
},
{
"code": null,
"e": 1882,
"s": 1811,
"text": "val pattern: String : It contains the string describing the pattern. "
},
{
"code": null,
"e": 2006,
"s": 1882,
"text": "containsMatchIn() – This function returns a boolean indicating whether there exists any match of our pattern in the input. "
},
{
"code": null,
"e": 2056,
"s": 2006,
"text": "fun containsMatchIn(input: CharSequence): Boolean"
},
{
"code": null,
"e": 2117,
"s": 2056,
"text": "Example to demonstrate containsMatchIn() function in Kotlin "
},
{
"code": null,
"e": 2122,
"s": 2117,
"text": "Java"
},
{
"code": "fun main(){ // Regex to match any string starting with 'a' val pattern = Regex(\"^a\") println(pattern.containsMatchIn(\"abc\")) println(pattern.containsMatchIn(\"bac\"))}",
"e": 2300,
"s": 2122,
"text": null
},
{
"code": null,
"e": 2309,
"s": 2300,
"text": "Output: "
},
{
"code": null,
"e": 2320,
"s": 2309,
"text": "true\nfalse"
},
{
"code": null,
"e": 2455,
"s": 2320,
"text": "find() – This function returns the first matched substring pertaining to our pattern in the input, from the specified starting index. "
},
{
"code": null,
"e": 2516,
"s": 2455,
"text": "fun find(input: CharSequence, startIndex: Int): MatchResult?"
},
{
"code": null,
"e": 2566,
"s": 2516,
"text": "Example to demonstrate find() function in Kotlin "
},
{
"code": null,
"e": 2571,
"s": 2566,
"text": "Java"
},
{
"code": "fun main(){ // Regex to match \"ll\" in a string val pattern1 = Regex(\"ll\") val ans : MatchResult? = pattern1.find(\"HelloHello\", 5) println(ans ?.value)}",
"e": 2735,
"s": 2571,
"text": null
},
{
"code": null,
"e": 2744,
"s": 2735,
"text": "Output: "
},
{
"code": null,
"e": 2747,
"s": 2744,
"text": "ll"
},
{
"code": null,
"e": 2877,
"s": 2747,
"text": "findAll() – This function returns all the matchings of the specified pattern in the input, searching from the given start index. "
},
{
"code": null,
"e": 2948,
"s": 2877,
"text": "fun findAll(\n input: CharSequence, \n startIndex: Int\n): Sequence"
},
{
"code": null,
"e": 2999,
"s": 2948,
"text": "Example to demonstrate findAll function in Kotlin "
},
{
"code": null,
"e": 3004,
"s": 2999,
"text": "Java"
},
{
"code": "fun main(){ // Regex to match a 3 letter pattern beginning with ab val pattern2 = Regex(\"ab.\") val ans1 : Sequence<MatchResult> = pattern2.findAll(\"abcfffgdbabs\", 0) // forEach loop used to display all the matches ans1.forEach() { matchResult -> println(matchResult.value) } println()}",
"e": 3325,
"s": 3004,
"text": null
},
{
"code": null,
"e": 3334,
"s": 3325,
"text": "Output: "
},
{
"code": null,
"e": 3342,
"s": 3334,
"text": "abc\nabs"
},
{
"code": null,
"e": 3463,
"s": 3342,
"text": "matches() – This function returns a boolean indicating whether the input string completely matches the pattern or not. "
},
{
"code": null,
"e": 3511,
"s": 3463,
"text": "infix fun matches(input: CharSequence): Boolean"
},
{
"code": null,
"e": 3564,
"s": 3511,
"text": "Example to demonstrate matches() function in Kotlin "
},
{
"code": null,
"e": 3569,
"s": 3564,
"text": "Java"
},
{
"code": "fun main(){ // Tests demonstrating entire string match val pattern = Regex(\"g([ee]+)ks?\") println(pattern.matches(\"geeks\")) println(pattern.matches(\"geeeeeeeeeeks\")) println(pattern.matches(\"geeksforgeeks\"))}",
"e": 3793,
"s": 3569,
"text": null
},
{
"code": null,
"e": 3803,
"s": 3793,
"text": "Output: "
},
{
"code": null,
"e": 3819,
"s": 3803,
"text": "true\ntrue\nfalse"
},
{
"code": null,
"e": 3995,
"s": 3819,
"text": "matchEntire() – This function tries to match the entire input to the specified pattern string, returning the string if it matches. If does not match the string, return null. "
},
{
"code": null,
"e": 4046,
"s": 3995,
"text": "fun matchEntire(input: CharSequence): MatchResult?"
},
{
"code": null,
"e": 4103,
"s": 4046,
"text": "Example to demonstrate matchEntire() function in Kotlin "
},
{
"code": null,
"e": 4108,
"s": 4103,
"text": "Java"
},
{
"code": "fun main(){ // Tests demonstrating entire string match var pattern = Regex(\"geeks?\") println(pattern.matchEntire(\"geeks\")?.value) println(pattern.matchEntire(\"geeeeeeeks\")?.value) pattern = Regex(\"\"\"\\D+\"\"\") println(pattern.matchEntire(\"geeks\")?.value) println(pattern.matchEntire(\"geeks12345\")?.value)}",
"e": 4432,
"s": 4108,
"text": null
},
{
"code": null,
"e": 4441,
"s": 4432,
"text": "Output: "
},
{
"code": null,
"e": 4463,
"s": 4441,
"text": "geeks\nnull\ngeeks\nnull"
},
{
"code": null,
"e": 4594,
"s": 4463,
"text": "replace() – This function replaces all the occurrences of the pattern in the input string with the specified replacement string. "
},
{
"code": null,
"e": 4656,
"s": 4594,
"text": "fun replace(input: CharSequence, replacement: String): String"
},
{
"code": null,
"e": 4782,
"s": 4656,
"text": "replaceFirst() – This function replaces the first match of the regular expression in the input with the replacement string. "
},
{
"code": null,
"e": 4860,
"s": 4782,
"text": "fun replaceFirst(\n input: CharSequence, \n replacement: String\n): String"
},
{
"code": null,
"e": 4933,
"s": 4860,
"text": "Example to demonstrate replace() and replaceFirst() functions in Kotlin "
},
{
"code": null,
"e": 4938,
"s": 4933,
"text": "Java"
},
{
"code": "fun main(){ // Tests demonstrating replacement functions val pattern4 = Regex(\"xyz\") // replace all xyz with abc in the string println(pattern4.replace(\"xyzxyzzzzzzzzz\", \"abc\")) // replace only first xyz with abc not all println(pattern4.replaceFirst(\"xyzddddddxyz\", \"abc\")) println()}",
"e": 5245,
"s": 4938,
"text": null
},
{
"code": null,
"e": 5255,
"s": 5245,
"text": "Output: "
},
{
"code": null,
"e": 5337,
"s": 5255,
"text": "abcabczzzzzzzz // replace all\nabcddddddxyz // replace first matching only"
},
{
"code": null,
"e": 5437,
"s": 5337,
"text": "split() – This function breaks the input string into tokens according to the specified parameter. "
},
{
"code": null,
"e": 5486,
"s": 5437,
"text": "fun split(input: CharSequence, limit: Int): List"
},
{
"code": null,
"e": 5537,
"s": 5486,
"text": "Example to demonstrate split() function in Kotlin "
},
{
"code": null,
"e": 5542,
"s": 5537,
"text": "Java"
},
{
"code": "fun main(){ // Tests demonstrating split function val pattern = Regex(\"\\\\s+\") // separate for white-spaces val ans : List<String> = pattern.split(\"This is a sentence\") ans.forEach { word -> println(word) }}",
"e": 5762,
"s": 5542,
"text": null
},
{
"code": null,
"e": 5771,
"s": 5762,
"text": "Output: "
},
{
"code": null,
"e": 5790,
"s": 5771,
"text": "This\nis\na\nsentence"
},
{
"code": null,
"e": 5800,
"s": 5790,
"text": "ruhelaa48"
},
{
"code": null,
"e": 5807,
"s": 5800,
"text": "Picked"
},
{
"code": null,
"e": 5814,
"s": 5807,
"text": "Kotlin"
},
{
"code": null,
"e": 5912,
"s": 5814,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5981,
"s": 5912,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
},
{
"code": null,
"e": 6012,
"s": 5981,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 6054,
"s": 6012,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 6073,
"s": 6054,
"text": "Kotlin constructor"
},
{
"code": null,
"e": 6122,
"s": 6073,
"text": "How to Communicate Between Fragments in Android?"
},
{
"code": null,
"e": 6149,
"s": 6122,
"text": "Kotlin Setters and Getters"
},
{
"code": null,
"e": 6212,
"s": 6149,
"text": "How to Add and Customize Back Button of Action Bar in Android?"
},
{
"code": null,
"e": 6250,
"s": 6212,
"text": "Suspend Function In Kotlin Coroutines"
},
{
"code": null,
"e": 6307,
"s": 6250,
"text": "How to Change the Color of Status Bar in an Android App?"
}
] |
How to specify a fixed background-image in CSS ? | 02 Jul, 2021
In this article, we are going to see how to specify a fixed background image in CSS. To keep your background fixed, scroll, or local in CSS, we have to use the background-attachment property.
Background-attachment: This property is used in CSS to set a background image as fixed or scroll. The default value of this property is scroll.
Values of background-attachment property:
Scroll: It is the default value for the background-attachment property. It is used to scroll the image with the background page.
Fixed: The background image will not scroll. It is fixed with the page.
Local: The background image will scroll with the content.
To keep your background image fixed, you have to use background-attachment property with the value Fixed.
Syntax:
background-attachment: fixed;
Example:
HTML
<!DOCTYPE html><html> <head> <style type="text/css"> h1 { text-align: center; } #ex { text-align: center; background-image:url("https://media.geeksforgeeks.org/wp-content/uploads/geeks-25.png"); background-position: center; background-repeat: no-repeat; background-attachment: fixed; } </style></head> <body> <h1>Example for fixed Background Image</h1> <div id="ex"> <p> Paragraphs are the building blocks of papers. Many students define paragraphs in terms of length: a paragraph is a group of at least five sentences, </p> <br><br> <p> a paragraph is half a page long, etc. In reality, though, the unity and coherence of ideas among sentences is what constitutes a paragraph. </p> <br><br> <p> A paragraph is defined as “a group of sentences or a single sentence that forms a unit” (Lunsford and Connors 116). </p> <br><br> <p> Length and appearance do not determine whether a section in a paper is a paragraph. </p> <br><br> <p> For instance, in some styles of writing, particularly journalistic styles, a paragraph can be just one sentence long. Ultimately, a paragraph is a sentence or group of sentences that support one main idea. </p> <br><br> <p> In this handout, we will refer to this as the “controlling idea,” because it controls what happens in the rest of the paragraph. </p> </div></body> </html>
Output:
Supported Browsers:
Google Chrome 1.0
Internet Explorer 4.0
Firefox 1.0
Opera 3.5
Safari 1.0
ysachin2314
CSS-Properties
CSS-Questions
Picked
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
Build a Survey Form using HTML and CSS
Design a web page using HTML and CSS
Form validation using jQuery
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n02 Jul, 2021"
},
{
"code": null,
"e": 246,
"s": 54,
"text": "In this article, we are going to see how to specify a fixed background image in CSS. To keep your background fixed, scroll, or local in CSS, we have to use the background-attachment property."
},
{
"code": null,
"e": 390,
"s": 246,
"text": "Background-attachment: This property is used in CSS to set a background image as fixed or scroll. The default value of this property is scroll."
},
{
"code": null,
"e": 432,
"s": 390,
"text": "Values of background-attachment property:"
},
{
"code": null,
"e": 561,
"s": 432,
"text": "Scroll: It is the default value for the background-attachment property. It is used to scroll the image with the background page."
},
{
"code": null,
"e": 633,
"s": 561,
"text": "Fixed: The background image will not scroll. It is fixed with the page."
},
{
"code": null,
"e": 691,
"s": 633,
"text": "Local: The background image will scroll with the content."
},
{
"code": null,
"e": 797,
"s": 691,
"text": "To keep your background image fixed, you have to use background-attachment property with the value Fixed."
},
{
"code": null,
"e": 805,
"s": 797,
"text": "Syntax:"
},
{
"code": null,
"e": 835,
"s": 805,
"text": "background-attachment: fixed;"
},
{
"code": null,
"e": 844,
"s": 835,
"text": "Example:"
},
{
"code": null,
"e": 849,
"s": 844,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style type=\"text/css\"> h1 { text-align: center; } #ex { text-align: center; background-image:url(\"https://media.geeksforgeeks.org/wp-content/uploads/geeks-25.png\"); background-position: center; background-repeat: no-repeat; background-attachment: fixed; } </style></head> <body> <h1>Example for fixed Background Image</h1> <div id=\"ex\"> <p> Paragraphs are the building blocks of papers. Many students define paragraphs in terms of length: a paragraph is a group of at least five sentences, </p> <br><br> <p> a paragraph is half a page long, etc. In reality, though, the unity and coherence of ideas among sentences is what constitutes a paragraph. </p> <br><br> <p> A paragraph is defined as “a group of sentences or a single sentence that forms a unit” (Lunsford and Connors 116). </p> <br><br> <p> Length and appearance do not determine whether a section in a paper is a paragraph. </p> <br><br> <p> For instance, in some styles of writing, particularly journalistic styles, a paragraph can be just one sentence long. Ultimately, a paragraph is a sentence or group of sentences that support one main idea. </p> <br><br> <p> In this handout, we will refer to this as the “controlling idea,” because it controls what happens in the rest of the paragraph. </p> </div></body> </html>",
"e": 2706,
"s": 849,
"text": null
},
{
"code": null,
"e": 2715,
"s": 2706,
"text": "Output: "
},
{
"code": null,
"e": 2735,
"s": 2715,
"text": "Supported Browsers:"
},
{
"code": null,
"e": 2753,
"s": 2735,
"text": "Google Chrome 1.0"
},
{
"code": null,
"e": 2775,
"s": 2753,
"text": "Internet Explorer 4.0"
},
{
"code": null,
"e": 2787,
"s": 2775,
"text": "Firefox 1.0"
},
{
"code": null,
"e": 2797,
"s": 2787,
"text": "Opera 3.5"
},
{
"code": null,
"e": 2808,
"s": 2797,
"text": "Safari 1.0"
},
{
"code": null,
"e": 2820,
"s": 2808,
"text": "ysachin2314"
},
{
"code": null,
"e": 2835,
"s": 2820,
"text": "CSS-Properties"
},
{
"code": null,
"e": 2849,
"s": 2835,
"text": "CSS-Questions"
},
{
"code": null,
"e": 2856,
"s": 2849,
"text": "Picked"
},
{
"code": null,
"e": 2860,
"s": 2856,
"text": "CSS"
},
{
"code": null,
"e": 2877,
"s": 2860,
"text": "Web Technologies"
},
{
"code": null,
"e": 2975,
"s": 2877,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3014,
"s": 2975,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 3053,
"s": 3014,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 3092,
"s": 3053,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 3129,
"s": 3092,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 3158,
"s": 3129,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 3191,
"s": 3158,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3252,
"s": 3191,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3295,
"s": 3252,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 3367,
"s": 3295,
"text": "Differences between Functional Components and Class Components in React"
}
] |
MySQL Tryit Editor v1.0 | SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;
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": 46,
"s": 0,
"text": "SELECT Orders.OrderID, Customers.CustomerName"
},
{
"code": null,
"e": 58,
"s": 46,
"text": "FROM Orders"
},
{
"code": null,
"e": 124,
"s": 58,
"text": "INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;"
},
{
"code": null,
"e": 126,
"s": 124,
"text": ""
},
{
"code": null,
"e": 198,
"s": 135,
"text": "Edit the SQL Statement, and click \"Run SQL\" to see the result."
},
{
"code": null,
"e": 258,
"s": 198,
"text": "This SQL-Statement is not supported in the WebSQL Database."
},
{
"code": null,
"e": 326,
"s": 258,
"text": "The example still works, because it uses a modified version of SQL."
},
{
"code": null,
"e": 364,
"s": 326,
"text": "Your browser does not support WebSQL."
},
{
"code": null,
"e": 449,
"s": 364,
"text": "Your are now using a light-version of the Try-SQL Editor, with a read-only Database."
},
{
"code": null,
"e": 623,
"s": 449,
"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": 674,
"s": 623,
"text": "Our Try-SQL Editor uses WebSQL to demonstrate SQL."
},
{
"code": null,
"e": 742,
"s": 674,
"text": "A Database-object is created in your browser, for testing purposes."
},
{
"code": null,
"e": 913,
"s": 742,
"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": 1013,
"s": 913,
"text": "WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object."
},
{
"code": null,
"e": 1063,
"s": 1013,
"text": "WebSQL is supported in Chrome, Safari, and Opera."
}
] |
How to Use fastai to Evaluate DICOM Medical Files | by Charlie Craine | Towards Data Science | Get started in Kaggle medical-based competitions
Kaggle competitions can be really intense and just gaining domain knowledge can take quite a good amount of work upfront.
I have quite a bit of experience using fastai, now, that doesn’t mean I always use it for a final competition entry, but it is a great tool for quickly prototyping and learning about a dataset.
This article is going to show you some helpful tips to get up-and-running fast on learning about DICOM medical files and the data associated with them. This article won’t be full of all of the code, that is being shared on Kaggle with everyone. So I’ll add some snippets here but will point you to the full notebook on Kaggle. I also used the amazing fastai tutorial on medical imaging to learn.
The first question you might be asking yourself (or not if you were Googling “fastai dicom files”): what are DICOM files?
DICOM stands for (Digital Imaging and COmmunications in Medicine) and is the de-facto standard that establishes rules that allow medical images(X-Ray, MRI, CT) and associated information to be exchanged between imaging equipment from different vendors, computers, and hospitals. The DICOM format provides a suitable means that meets health information exchange (HIE) standards for transmission of health-related data among facilities and HL7 standards which is the messaging standard that enables clinical applications to exchange data
DICOM is generally associated with a .dcm extension. What is really amazing about DICOM files is that they provide a means of storing data in separate ‘tags’ such as patient information as well as image/pixel data. A DICOM file consists of a header and image data sets packed into a single file.
This is a good chance for us to see how fastai allows you to quickly see the information stored in the .dcm file. If you are used to using fastai you’ll be familiar with a few imports, but note the medical import. This is important to work with DICOM files.
from fastai.basics import *from fastai.callback.all import *from fastai.vision.all import *from fastai.medical.imaging import *import pydicomimport pandas as pd
The dataset I’m using is on Kaggle: VinBigData Chest X-ray Abnormalities Detection. This is an interesting competition; you can read the information on Kaggle to learn more. For the sake of a simple tutorial, you’ll see my code below to access the file. The structure is very straight-forward with a parent folder “vinbigdata-chest-xray-abnormalities-detection” and the training path with the DICOM images within it:
path = Path('../input/vinbigdata-chest-xray-abnormalities-detection')train_imgs = path/'train'
Next, you can set up your images so they can be read.
items = get_dicom_files(train_imgs)
Pydicom is a python package for parsing DICOM files, making it easier to access the header of the DICOM as well as converting the raw pixel_data into pythonic structures for easier manipulation. fastai.medical.imaging uses pydicom.dcmread to load the DICOM file.
To plot an X-ray, we can select an entry in the items list and load the DICOM file with dcmread. Here we can write a simple line of code to see interesting, and potentially valuable, data associated with the dcm file.
#add any number here to pick one single patient patient = 3xray_sample = items[patient].dcmread()
Now we can view the header metadata within the dicom file.
xray_sampleOutput:Dataset.file_meta -------------------------------(0002, 0000) File Meta Information Group Length UL: 160(0002, 0001) File Meta Information Version OB: b'\x00\x01'(0002, 0002) Media Storage SOP Class UID UI: Digital X-Ray Image Storage - For Presentation(0002, 0003) Media Storage SOP Instance UID UI: 7ecd6f67f649f26c05805c8359f9e528(0002, 0010) Transfer Syntax UID UI: JPEG 2000 Image Compression (Lossless Only)(0002, 0012) Implementation Class UID UI: 1.2.3.4(0002, 0013) Implementation Version Name SH: 'OFFIS_DCMTK_360'-------------------------------------------------(0010, 0040) Patient's Sex CS: 'M'(0010, 1010) Patient's Age AS: '061Y'(0028, 0002) Samples per Pixel US: 1(0028, 0004) Photometric Interpretation CS: 'MONOCHROME2'(0028, 0010) Rows US: 2952(0028, 0011) Columns US: 2744(0028, 0030) Pixel Spacing DS: [0.127, 0.127](0028, 0100) Bits Allocated US: 16(0028, 0101) Bits Stored US: 14(0028, 0102) High Bit US: 13(0028, 0103) Pixel Representation US: 0(0028, 1050) Window Center DS: "8190.0"(0028, 1051) Window Width DS: "7259.0"(0028, 1052) Rescale Intercept DS: "0.0"(0028, 1053) Rescale Slope DS: "1.0"(0028, 2110) Lossy Image Compression CS: '00'(0028, 2112) Lossy Image Compression Ratio DS: "2.0"(7fe0, 0010) Pixel Data OB: Array of 5827210 elements
There is a lot of information here and the good news is there is an excellent resource to learn more about these:
http://dicom.nema.org/medical/dicom/current/output/chtml/part03/sect_C.7.6.3.html#sect_C.7.6.3.1.4
Finally, you can see an actual x-ray.
xray_sample.show()
Remember all the metadata above that seemed interesting and may have wondered how you could make it useful? The good news is, you can pull that data into a dataframe.
As a quick note. I’ll add two versions of the code below. One for Google Colab and click the link to see a more complex version for Kaggle. Anyone who has used Kaggle knows that sometimes you have to change things up a bit there to make things work.
Here is the simple way to pull your metadata into a dataframe:
dicom_dataframe = pd.DataFrame.from_dicoms(items)dicom_dataframe[:5]
I’ll add a screenshot below since the data is 29 columns and will go off the page.
Hopefully, this will be helpful for some of you. Next, I’m going to set up the bounding boxes to detect the various diseases within the x-rays.
If anyone does something great with fastai and/or medical data, I want to hear about it! Please let everyone know what you’ve created in the responses below or reach out any time on LinkedIn. | [
{
"code": null,
"e": 221,
"s": 172,
"text": "Get started in Kaggle medical-based competitions"
},
{
"code": null,
"e": 343,
"s": 221,
"text": "Kaggle competitions can be really intense and just gaining domain knowledge can take quite a good amount of work upfront."
},
{
"code": null,
"e": 537,
"s": 343,
"text": "I have quite a bit of experience using fastai, now, that doesn’t mean I always use it for a final competition entry, but it is a great tool for quickly prototyping and learning about a dataset."
},
{
"code": null,
"e": 933,
"s": 537,
"text": "This article is going to show you some helpful tips to get up-and-running fast on learning about DICOM medical files and the data associated with them. This article won’t be full of all of the code, that is being shared on Kaggle with everyone. So I’ll add some snippets here but will point you to the full notebook on Kaggle. I also used the amazing fastai tutorial on medical imaging to learn."
},
{
"code": null,
"e": 1055,
"s": 933,
"text": "The first question you might be asking yourself (or not if you were Googling “fastai dicom files”): what are DICOM files?"
},
{
"code": null,
"e": 1591,
"s": 1055,
"text": "DICOM stands for (Digital Imaging and COmmunications in Medicine) and is the de-facto standard that establishes rules that allow medical images(X-Ray, MRI, CT) and associated information to be exchanged between imaging equipment from different vendors, computers, and hospitals. The DICOM format provides a suitable means that meets health information exchange (HIE) standards for transmission of health-related data among facilities and HL7 standards which is the messaging standard that enables clinical applications to exchange data"
},
{
"code": null,
"e": 1887,
"s": 1591,
"text": "DICOM is generally associated with a .dcm extension. What is really amazing about DICOM files is that they provide a means of storing data in separate ‘tags’ such as patient information as well as image/pixel data. A DICOM file consists of a header and image data sets packed into a single file."
},
{
"code": null,
"e": 2145,
"s": 1887,
"text": "This is a good chance for us to see how fastai allows you to quickly see the information stored in the .dcm file. If you are used to using fastai you’ll be familiar with a few imports, but note the medical import. This is important to work with DICOM files."
},
{
"code": null,
"e": 2306,
"s": 2145,
"text": "from fastai.basics import *from fastai.callback.all import *from fastai.vision.all import *from fastai.medical.imaging import *import pydicomimport pandas as pd"
},
{
"code": null,
"e": 2723,
"s": 2306,
"text": "The dataset I’m using is on Kaggle: VinBigData Chest X-ray Abnormalities Detection. This is an interesting competition; you can read the information on Kaggle to learn more. For the sake of a simple tutorial, you’ll see my code below to access the file. The structure is very straight-forward with a parent folder “vinbigdata-chest-xray-abnormalities-detection” and the training path with the DICOM images within it:"
},
{
"code": null,
"e": 2818,
"s": 2723,
"text": "path = Path('../input/vinbigdata-chest-xray-abnormalities-detection')train_imgs = path/'train'"
},
{
"code": null,
"e": 2872,
"s": 2818,
"text": "Next, you can set up your images so they can be read."
},
{
"code": null,
"e": 2908,
"s": 2872,
"text": "items = get_dicom_files(train_imgs)"
},
{
"code": null,
"e": 3171,
"s": 2908,
"text": "Pydicom is a python package for parsing DICOM files, making it easier to access the header of the DICOM as well as converting the raw pixel_data into pythonic structures for easier manipulation. fastai.medical.imaging uses pydicom.dcmread to load the DICOM file."
},
{
"code": null,
"e": 3389,
"s": 3171,
"text": "To plot an X-ray, we can select an entry in the items list and load the DICOM file with dcmread. Here we can write a simple line of code to see interesting, and potentially valuable, data associated with the dcm file."
},
{
"code": null,
"e": 3487,
"s": 3389,
"text": "#add any number here to pick one single patient patient = 3xray_sample = items[patient].dcmread()"
},
{
"code": null,
"e": 3546,
"s": 3487,
"text": "Now we can view the header metadata within the dicom file."
},
{
"code": null,
"e": 5259,
"s": 3546,
"text": "xray_sampleOutput:Dataset.file_meta -------------------------------(0002, 0000) File Meta Information Group Length UL: 160(0002, 0001) File Meta Information Version OB: b'\\x00\\x01'(0002, 0002) Media Storage SOP Class UID UI: Digital X-Ray Image Storage - For Presentation(0002, 0003) Media Storage SOP Instance UID UI: 7ecd6f67f649f26c05805c8359f9e528(0002, 0010) Transfer Syntax UID UI: JPEG 2000 Image Compression (Lossless Only)(0002, 0012) Implementation Class UID UI: 1.2.3.4(0002, 0013) Implementation Version Name SH: 'OFFIS_DCMTK_360'-------------------------------------------------(0010, 0040) Patient's Sex CS: 'M'(0010, 1010) Patient's Age AS: '061Y'(0028, 0002) Samples per Pixel US: 1(0028, 0004) Photometric Interpretation CS: 'MONOCHROME2'(0028, 0010) Rows US: 2952(0028, 0011) Columns US: 2744(0028, 0030) Pixel Spacing DS: [0.127, 0.127](0028, 0100) Bits Allocated US: 16(0028, 0101) Bits Stored US: 14(0028, 0102) High Bit US: 13(0028, 0103) Pixel Representation US: 0(0028, 1050) Window Center DS: \"8190.0\"(0028, 1051) Window Width DS: \"7259.0\"(0028, 1052) Rescale Intercept DS: \"0.0\"(0028, 1053) Rescale Slope DS: \"1.0\"(0028, 2110) Lossy Image Compression CS: '00'(0028, 2112) Lossy Image Compression Ratio DS: \"2.0\"(7fe0, 0010) Pixel Data OB: Array of 5827210 elements"
},
{
"code": null,
"e": 5373,
"s": 5259,
"text": "There is a lot of information here and the good news is there is an excellent resource to learn more about these:"
},
{
"code": null,
"e": 5472,
"s": 5373,
"text": "http://dicom.nema.org/medical/dicom/current/output/chtml/part03/sect_C.7.6.3.html#sect_C.7.6.3.1.4"
},
{
"code": null,
"e": 5510,
"s": 5472,
"text": "Finally, you can see an actual x-ray."
},
{
"code": null,
"e": 5529,
"s": 5510,
"text": "xray_sample.show()"
},
{
"code": null,
"e": 5696,
"s": 5529,
"text": "Remember all the metadata above that seemed interesting and may have wondered how you could make it useful? The good news is, you can pull that data into a dataframe."
},
{
"code": null,
"e": 5946,
"s": 5696,
"text": "As a quick note. I’ll add two versions of the code below. One for Google Colab and click the link to see a more complex version for Kaggle. Anyone who has used Kaggle knows that sometimes you have to change things up a bit there to make things work."
},
{
"code": null,
"e": 6009,
"s": 5946,
"text": "Here is the simple way to pull your metadata into a dataframe:"
},
{
"code": null,
"e": 6078,
"s": 6009,
"text": "dicom_dataframe = pd.DataFrame.from_dicoms(items)dicom_dataframe[:5]"
},
{
"code": null,
"e": 6161,
"s": 6078,
"text": "I’ll add a screenshot below since the data is 29 columns and will go off the page."
},
{
"code": null,
"e": 6305,
"s": 6161,
"text": "Hopefully, this will be helpful for some of you. Next, I’m going to set up the bounding boxes to detect the various diseases within the x-rays."
}
] |
Create multiple buttons with "different" command function in Tkinter | A Button can be initialized using the for loop in a Tkinter application. Let us suppose that we want to create multiple buttons, each with different commands or operations defined in it. We have to first initialize the Button inside a for loop. The iterator will return the object for which multiple instances of the button will be created.
In this example, we will define some buttons that will have different commands or functionalities.
#Import the required Libraries
from tkinter import *
from tkinter import ttk
#Create an instance of Tkinter frame
win = Tk()
#Set the geometry of the Tkinter frame
win.geometry("750x250")
#Define a function to update the entry widget
def entry_update(text):
entry.delete(0,END)
entry.insert(0,text)
#Create an Entry Widget
entry= Entry(win, width= 30, bg= "white")
entry.pack(pady=10)
#Create Multiple Buttons with different commands
button_dict={}
option= ["Python", "Java", "Go", "C++"]
for i in option:
def func(x=i):
return entry_update(x)
button_dict[i]=ttk.Button(win, text=i, command= func)
button_dict[i].pack()
win.mainloop()
Running the above code will display a window that contains some buttons. When we click a particular button, it will update the message in the Entry widget.
Now, click each button to see the resultant output. | [
{
"code": null,
"e": 1403,
"s": 1062,
"text": "A Button can be initialized using the for loop in a Tkinter application. Let us suppose that we want to create multiple buttons, each with different commands or operations defined in it. We have to first initialize the Button inside a for loop. The iterator will return the object for which multiple instances of the button will be created."
},
{
"code": null,
"e": 1502,
"s": 1403,
"text": "In this example, we will define some buttons that will have different commands or functionalities."
},
{
"code": null,
"e": 2164,
"s": 1502,
"text": "#Import the required Libraries\nfrom tkinter import *\nfrom tkinter import ttk\n#Create an instance of Tkinter frame\nwin = Tk()\n#Set the geometry of the Tkinter frame\nwin.geometry(\"750x250\")\n\n#Define a function to update the entry widget\ndef entry_update(text):\n entry.delete(0,END)\n entry.insert(0,text)\n\n#Create an Entry Widget\nentry= Entry(win, width= 30, bg= \"white\")\nentry.pack(pady=10)\n\n#Create Multiple Buttons with different commands\nbutton_dict={}\noption= [\"Python\", \"Java\", \"Go\", \"C++\"]\n\nfor i in option:\n def func(x=i):\n return entry_update(x)\n\n button_dict[i]=ttk.Button(win, text=i, command= func)\n button_dict[i].pack()\n\nwin.mainloop()"
},
{
"code": null,
"e": 2320,
"s": 2164,
"text": "Running the above code will display a window that contains some buttons. When we click a particular button, it will update the message in the Entry widget."
},
{
"code": null,
"e": 2372,
"s": 2320,
"text": "Now, click each button to see the resultant output."
}
] |
Ceil and Floor functions in C++ - GeeksforGeeks | 04 Apr, 2018
In mathematics and computer science, the floor and ceiling functions map a real number to the greatest preceding or the least succeeding integer, respectively.
floor(x) : Returns the largest integer that is smaller than or equal to x (i.e : rounds downs the nearest integer).
// Here x is the floating point value.
// Returns the largest integer smaller
// than or equal to x
double floor(double x)
Examples of Floor:
Input : 2.5
Output : 2
Input : -2.1
Output : -3
Input : 2.9
Output : 2
// C++ program to demonstrate floor function#include <iostream>#include <cmath>using namespace std; // Driver functionint main(){ // using floor function which return // floor of input value cout << "Floor is : " << floor(2.3) << endl; cout << "Floor is : " << floor(-2.3) << endl; return 0;}
Output:
Floor is : 2
Floor is : -3
ceil(x) : Returns the smallest integer that is greater than or equal to x (i.e : rounds up the nearest integer).
// Here x is the floating point value.
// Returns the smallest integer greater
// than or equal to x
double ceiling(double x)
Examples of Ceil:
Input : 2.5
Output : 3
Input : -2.1
Output : -2
Input : 2.9
Output : 3
// C++ program to demonstrate ceil function#include <iostream>#include <cmath>using namespace std; // Driver functionint main(){ // using ceil function which return // floor of input value cout << " Ceil is : " << ceil(2.3) << endl; cout << " Ceil is : " << ceil(-2.3) << endl; return 0;}
Ceil is : 3
Ceil is : -2
This article is contributed by Sahil Rajput. 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.
CPP-Library
cpp-math
C++
School Programming
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Socket Programming in C/C++
Operator Overloading in C++
Iterators in C++ STL
C++ Classes and Objects
Multidimensional Arrays in C / C++
Python Dictionary
Reverse a string in Java
Interfaces in Java
Operator Overloading in C++
C++ Classes and Objects | [
{
"code": null,
"e": 24075,
"s": 24047,
"text": "\n04 Apr, 2018"
},
{
"code": null,
"e": 24235,
"s": 24075,
"text": "In mathematics and computer science, the floor and ceiling functions map a real number to the greatest preceding or the least succeeding integer, respectively."
},
{
"code": null,
"e": 24351,
"s": 24235,
"text": "floor(x) : Returns the largest integer that is smaller than or equal to x (i.e : rounds downs the nearest integer)."
},
{
"code": null,
"e": 24478,
"s": 24351,
"text": "// Here x is the floating point value.\n// Returns the largest integer smaller \n// than or equal to x \ndouble floor(double x) "
},
{
"code": null,
"e": 24497,
"s": 24478,
"text": "Examples of Floor:"
},
{
"code": null,
"e": 24571,
"s": 24497,
"text": "Input : 2.5\nOutput : 2\n\nInput : -2.1\nOutput : -3\n\nInput : 2.9\nOutput : 2\n"
},
{
"code": "// C++ program to demonstrate floor function#include <iostream>#include <cmath>using namespace std; // Driver functionint main(){ // using floor function which return // floor of input value cout << \"Floor is : \" << floor(2.3) << endl; cout << \"Floor is : \" << floor(-2.3) << endl; return 0;}",
"e": 24882,
"s": 24571,
"text": null
},
{
"code": null,
"e": 24890,
"s": 24882,
"text": "Output:"
},
{
"code": null,
"e": 24918,
"s": 24890,
"text": "Floor is : 2\nFloor is : -3\n"
},
{
"code": null,
"e": 25033,
"s": 24920,
"text": "ceil(x) : Returns the smallest integer that is greater than or equal to x (i.e : rounds up the nearest integer)."
},
{
"code": null,
"e": 25163,
"s": 25033,
"text": "// Here x is the floating point value.\n// Returns the smallest integer greater \n// than or equal to x \ndouble ceiling(double x) "
},
{
"code": null,
"e": 25181,
"s": 25163,
"text": "Examples of Ceil:"
},
{
"code": null,
"e": 25255,
"s": 25181,
"text": "Input : 2.5\nOutput : 3\n\nInput : -2.1\nOutput : -2\n\nInput : 2.9\nOutput : 3\n"
},
{
"code": "// C++ program to demonstrate ceil function#include <iostream>#include <cmath>using namespace std; // Driver functionint main(){ // using ceil function which return // floor of input value cout << \" Ceil is : \" << ceil(2.3) << endl; cout << \" Ceil is : \" << ceil(-2.3) << endl; return 0;}",
"e": 25562,
"s": 25255,
"text": null
},
{
"code": null,
"e": 25588,
"s": 25562,
"text": "Ceil is : 3\nCeil is : -2\n"
},
{
"code": null,
"e": 25888,
"s": 25588,
"text": "This article is contributed by Sahil Rajput. 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": 26013,
"s": 25888,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 26025,
"s": 26013,
"text": "CPP-Library"
},
{
"code": null,
"e": 26034,
"s": 26025,
"text": "cpp-math"
},
{
"code": null,
"e": 26038,
"s": 26034,
"text": "C++"
},
{
"code": null,
"e": 26057,
"s": 26038,
"text": "School Programming"
},
{
"code": null,
"e": 26061,
"s": 26057,
"text": "CPP"
},
{
"code": null,
"e": 26159,
"s": 26061,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26168,
"s": 26159,
"text": "Comments"
},
{
"code": null,
"e": 26181,
"s": 26168,
"text": "Old Comments"
},
{
"code": null,
"e": 26209,
"s": 26181,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 26237,
"s": 26209,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 26258,
"s": 26237,
"text": "Iterators in C++ STL"
},
{
"code": null,
"e": 26282,
"s": 26258,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 26317,
"s": 26282,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 26335,
"s": 26317,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26360,
"s": 26335,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 26379,
"s": 26360,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 26407,
"s": 26379,
"text": "Operator Overloading in C++"
}
] |
CSS Positioning Elements - GeeksforGeeks | 01 Nov, 2021
The position property in CSS tells about the method of positioning for an element or an HTML entity. There are five different types of position property available in CSS:
Fixed
Static
Relative
Absolute
Sticky
The positioning of an element can be done using the top, right, bottom, and left properties. These specify the distance of an HTML element from the edge of the viewport. To set the position by these four properties, we have to declare the positioning method. Let’s understand each of these position methods in detail:
Fixed: Any HTML element with position: fixed property will be positioned relative to the viewport. An element with fixed positioning allows it to remain at the same position even we scroll the page. We can set the position of the element using the top, right, bottom, left.
Example: The below example illustrates the CSS positioning element by using the position: fixed property.
HTML
<!DOCTYPE html><html> <head> <title> CSS Positioning Element</title> <style> body { margin: 0; padding: 20px; font-family: sans-serif; background: #efefef; } .fixed { position: fixed; background: #cc0000; color: #ffffff; padding: 30px; top: 50; left: 10; } span { padding: 5px; border: 1px #ffffff dotted; } </style></head> <body> <div class="fixed">This div has <span>position: fixed;</span> </div> <pre> Learn the most common Data Structures & Algorithms to solve coding problems. Enrol now! Master core Data Structures & Algorithms to ace interviews from IIT & Stanford Alumni. TA Support. Placements in Companies. Get Certified. 350+ Problems.A data structure is a particular way of organizing data in a computer so that it can be used effectively. Learn the most common Data Structures & Algorithms to solve coding problems. Enrol now! Master core Data Structures & Algorithms to ace interviews from IIT & Stanford Alumni. TA Support. Placements in Companies. Get Certified. 350+ Problems.A data structure is a particular way of organizing data in a computer so that it can be used effectively. Learn the most common Data Structures & Algorithms to solve coding problems. Enrol now! Master core Data Structures & Algorithms to ace interviews from IIT & Stanford Alumni. TA Support. Placements in Companies. Get Certified. 350+ Problems.A data structure is a particular way of organizing data in a computer so that it can be used effectively. Learn the most common Data Structures & Algorithms to solve coding problems. Enrol now! Master core Data Structures & Algorithms to ace interviews from IIT & Stanford Alumni. TA Support. Placements in Companies. Get Certified. 350+ Problems.A data structure is a particular way of organizing data in a computer so that it can be used effectively. </pre></body> </html>
Output:
Static: This method of positioning is set by default. If we don’t mention the method of positioning for any element, the element has the position: static method by default. By defining Static, the top, right, bottom and left will not have any control over the element. The element will be positioned with the normal flow of the page.
Example: The below example illustrates the CSS positioning element by using the position: static property.
HTML
<!DOCTYPE html><html> <head> <title> CSS Positioning Element</title> <style> body { margin: 0; padding: 20px; font-family: sans-serif; background: #efefef; } .static { position: static; background: #cc0000; color: #ffffff; padding: 30px; } span { padding: 5px; border: 1px #ffffff dotted; } </style></head> <body> <div class="static"> This div has <span>position: static;</span> </div> <pre> Learn the most common Data Structures & Algorithms to solve coding problems. Enrol now! Master core Data Structures & Algorithms to ace interviews from IIT & Stanford Alumni. TA Support. Placements in Companies. Get Certified. 350+ Problems.A data structure is a particular way of organizing data in a computer so that it can be used effectively. Learn the most common Data Structures & Algorithms to solve coding problems. Enrol now! Master core Data Structures & Algorithms to ace interviews from IIT & Stanford Alumni. TA Support. Placements in Companies. Get Certified. 350+ Problems.A data structure is a particular way of organizing data in a computer so that it can be used effectively. Learn the most common Data Structures & Algorithms to solve coding problems. Enrol now! Master core Data Structures & Algorithms to ace interviews from IIT & Stanford Alumni. TA Support. Placements in Companies. Get Certified. 350+ Problems.A data structure is a particular way of organizing data in a computer so that it can be used effectively. Learn the most common Data Structures & Algorithms to solve coding problems. Enrol now! Master core Data Structures & Algorithms to ace interviews from IIT & Stanford Alumni. TA Support. Placements in Companies. Get Certified. 350+ Problems.A data structure is a particular way of organizing data in a computer so that it can be used effectively. </pre></body> </html>
Output:
Relative: An element with position: relative is positioned relatively with the other elements which are sitting at top of it. If we set its top, right, bottom, or left, other elements will not fill up the gap left by this element.
Example: The below example illustrates the CSS positioning element by using the position: relative property.
HTML
<!DOCTYPE html><html> <head> <title> CSS Positioning Element</title> <style> body { margin: 0; padding: 20px; font-family: sans-serif; background: #efefef; } .relative { position: relative; background: #cc0000; color: #ffffff; padding: 30px; } span { padding: 5px; border: 1px #ffffff dotted; } </style></head> <body> <pre> Learn the most common Data Structures & Algorithms to solve coding problems. Enrol now! Master core Data Structures & Algorithms to ace interviews from IIT & Stanford Alumni. TA Support. Placements in Companies. Get Certified. 350+ Problems.A data structure is a particular way of organizing data in a computer so that it can be used effectively. Learn the most common Data Structures & Algorithms to solve coding problems. Enrol now! Master core Data Structures & Algorithms to ace interviews from IIT & Stanford Alumni. TA Support. Placements in Companies. Get Certified. 350+ Problems.A data structure is a particular way of organizing data in a computer so that it can be used effectively. <div class="relative"> This div has <span>position: relative;</span> </div> Learn the most common Data Structures & Algorithms to solve coding problems. Enrol now! Master core Data Structures & Algorithms to ace interviews from IIT & Stanford Alumni. TA Support. Placements in Companies. Get Certified. 350+ Problems.A data structure is a particular way of organizing data in a computer so that it can be used effectively. Learn the most common Data Structures & Algorithms to solve coding problems. Enrol now! Master core Data Structures & Algorithms to ace interviews from IIT & Stanford Alumni. TA Support. Placements in Companies. Get Certified. 350+ Problems.A data structure is a particular way of organizing data in a computer so that it can be used effectively. </pre></body> </html>
Output:
Absolute: An element with position: absolute will be positioned with respect to its parent. The positioning of this element does not depend upon its siblings or the elements which are at the same level.
Example: The below example illustrates the CSS positioning element by using the position: absolute property.
HTML
<!DOCTYPE html><html> <head> <title> CSS Positioning Element</title> <style> body { margin: 0; padding: 20px; font-family: sans-serif; background: #efefef; } .absolute { position: absolute; background: #cc0000; color: #ffffff; padding: 30px; font-size: 15px; bottom: 20px; right: 20px; } .relative { position: relative; background: #aad000; height: 300px; font-size: 30px; border: 1px solid #121212; text-align: center; } span { padding: 5px; border: 1px #ffffff dotted; } pre { padding: 20px; border: 1px solid #000000; } </style></head> <body> <pre> Learn the most common Data Structures & Algorithms to solve coding problems. Enrol now! Master core Data Structures & Algorithms to ace interviews from IIT & Stanford Alumni. TA Support. Placements in Companies. Get Certified. 350+ Problems.A data structure is a particular way of organizing data in a computer so that it can be used effectively. Learn the most common Data Structures & Algorithms to solve coding problems. Enrol now! Master core Data Structures & Algorithms to ace interviews from IIT & Stanford Alumni. TA Support. Placements in Companies. Get Certified. 350+ Problems.A data structure is a particular way of organizing data in a computer so that it can be used effectively. <div class="relative"> <div > This div has <span> <strong>position: relative;</strong> </span> </div> <div class="absolute"> This div has <span> <strong>position: absolute;</strong> </span> </div> </div> Learn the most common Data Structures & Algorithms to solve coding problems. Enrol now! Master core Data Structures & Algorithms to ace interviews from IIT & Stanford Alumni. TA Support. Placements in Companies. Get Certified. 350+ Problems.A data structure is a particular way of organizing data in a computer so that it can be used effectively. Learn the most common Data Structures & Algorithms to solve coding problems. Enrol now! Master core Data Structures & Algorithms to ace interviews from IIT & Stanford Alumni. TA Support. Placements in Companies. Get Certified. 350+ Problems.A data structure is a particular way of organizing data in a computer so that it can be used effectively. Learn the most common Data Structures & Algorithms to solve coding problems. Enrol now! Master core Data Structures & Algorithms to ace interviews from IIT & Stanford Alumni. TA Support. Placements in Companies. Get Certified. 350+ Problems.A data structure is a particular way of organizing data in a computer so that it can be used effectively. Learn the most common Data Structures & Algorithms to solve coding problems. Enrol now! Master core Data Structures & Algorithms to ace interviews from IIT & Stanford Alumni. TA Support. Placements in Companies. Get Certified. 350+ Problems.A data structure is a particular way of organizing data in a computer so that it can be used effectively. Learn the most common Data Structures & Algorithms to solve coding problems. Enrol now! Master core Data Structures & Algorithms to ace interviews from IIT & Stanford Alumni. TA Support. Placements in Companies. Get Certified. 350+ Problems.A data structure is a particular way of organizing data in a computer so that it can be used effectively. </pre></body> </html>
Output:
Sticky: Element with position: sticky and top: 0 played a role between fixed & relative based on the position where it is placed. If the element is placed at the middle of the document then when the user scrolls the document, the sticky element starts scrolling until it touches the top. When it touches the top, it will be fixed at that place in spite of further scrolling. We can stick the element at the bottom, with the bottom property.
Example: The below example illustrates the CSS positioning element by using the position: sticky property.
HTML
<!DOCTYPE html><html> <head> <title> CSS Positioning Element</title> <style> body { margin: 0; padding: 20px; font-family: sans-serif; background: #efefef; } .sticky { position: sticky; background: #cc0000; color: #ffffff; padding: 30px; top: 10px; right: 50px; } span { padding: 5px; border: 1px #ffffff dotted; } pre { padding: 20px; border: 1px solid #000000; } </style></head> <body> <pre> Learn the most common Data Structures & Algorithms to solve coding problems. Enrol now! Master core Data Structures & Algorithms to ace interviews from IIT & Stanford Alumni. TA Support. Placements in Companies. Get Certified. 350+ Problems.A data structure is a particular way of organizing data in a computer so that it can be used effectively. Learn the most common Data Structures & Algorithms to solve coding problems. Enrol now! Master core Data Structures & Algorithms to ace interviews from IIT & Stanford Alumni. TA Support. Placements in Companies. Get Certified. 350+ Problems.A data structure is a particular way of organizing data in a computer so that it can be used effectively. <div class="sticky"> This div has <span>position: sticky;</span> </div> Learn the most common Data Structures & Algorithms to solve coding problems. Enrol now! Master core Data Structures & Algorithms to ace interviews from IIT & Stanford Alumni. TA Support. Placements in Companies. Get Certified. 350+ Problems.A data structure is a particular way of organizing data in a computer so that it can be used effectively. Learn the most common Data Structures & Algorithms to solve coding problems. Enrol now! Master core Data Structures & Algorithms to ace interviews from IIT & Stanford Alumni. TA Support. Placements in Companies. Get Certified. 350+ Problems.A data structure is a particular way of organizing data in a computer so that it can be used effectively. Learn the most common Data Structures & Algorithms to solve coding problems. Enrol now! Master core Data Structures & Algorithms to ace interviews from IIT & Stanford Alumni. TA Support. Placements in Companies. Get Certified. 350+ Problems.A data structure is a particular way of organizing data in a computer so that it can be used effectively. Learn the most common Data Structures & Algorithms to solve coding problems. Enrol now! Master core Data Structures & Algorithms to ace interviews from IIT & Stanford Alumni. TA Support. Placements in Companies. Get Certified. 350+ Problems.A data structure is a particular way of organizing data in a computer so that it can be used effectively. Learn the most common Data Structures & Algorithms to solve coding problems. Enrol now! Master core Data Structures & Algorithms to ace interviews from IIT & Stanford Alumni. TA Support. Placements in Companies. Get Certified. 350+ Problems.A data structure is a particular way of organizing data in a computer so that it can be used effectively. </pre></body> </html>
Output:
Supported Browser:
Google Chrome 1.0
Microsoft Edge 12.0
Firefox 1.0
Internet Explorer 4.0
Opera 4.0
Safari 1.0
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
bhaskargeeksforgeeks
CSS-Basics
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Types of CSS (Cascading Style Sheet)
How to create footer to stay at the bottom of a Web page?
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
Types of CSS (Cascading Style Sheet) | [
{
"code": null,
"e": 27990,
"s": 27962,
"text": "\n01 Nov, 2021"
},
{
"code": null,
"e": 28161,
"s": 27990,
"text": "The position property in CSS tells about the method of positioning for an element or an HTML entity. There are five different types of position property available in CSS:"
},
{
"code": null,
"e": 28167,
"s": 28161,
"text": "Fixed"
},
{
"code": null,
"e": 28174,
"s": 28167,
"text": "Static"
},
{
"code": null,
"e": 28183,
"s": 28174,
"text": "Relative"
},
{
"code": null,
"e": 28192,
"s": 28183,
"text": "Absolute"
},
{
"code": null,
"e": 28199,
"s": 28192,
"text": "Sticky"
},
{
"code": null,
"e": 28517,
"s": 28199,
"text": "The positioning of an element can be done using the top, right, bottom, and left properties. These specify the distance of an HTML element from the edge of the viewport. To set the position by these four properties, we have to declare the positioning method. Let’s understand each of these position methods in detail:"
},
{
"code": null,
"e": 28791,
"s": 28517,
"text": "Fixed: Any HTML element with position: fixed property will be positioned relative to the viewport. An element with fixed positioning allows it to remain at the same position even we scroll the page. We can set the position of the element using the top, right, bottom, left."
},
{
"code": null,
"e": 28897,
"s": 28791,
"text": "Example: The below example illustrates the CSS positioning element by using the position: fixed property."
},
{
"code": null,
"e": 28902,
"s": 28897,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title> CSS Positioning Element</title> <style> body { margin: 0; padding: 20px; font-family: sans-serif; background: #efefef; } .fixed { position: fixed; background: #cc0000; color: #ffffff; padding: 30px; top: 50; left: 10; } span { padding: 5px; border: 1px #ffffff dotted; } </style></head> <body> <div class=\"fixed\">This div has <span>position: fixed;</span> </div> <pre> Learn the most common Data Structures & Algorithms to solve coding problems. Enrol now! Master core Data Structures & Algorithms to ace interviews from IIT & Stanford Alumni. TA Support. Placements in Companies. Get Certified. 350+ Problems.A data structure is a particular way of organizing data in a computer so that it can be used effectively. Learn the most common Data Structures & Algorithms to solve coding problems. Enrol now! Master core Data Structures & Algorithms to ace interviews from IIT & Stanford Alumni. TA Support. Placements in Companies. Get Certified. 350+ Problems.A data structure is a particular way of organizing data in a computer so that it can be used effectively. Learn the most common Data Structures & Algorithms to solve coding problems. Enrol now! Master core Data Structures & Algorithms to ace interviews from IIT & Stanford Alumni. TA Support. Placements in Companies. Get Certified. 350+ Problems.A data structure is a particular way of organizing data in a computer so that it can be used effectively. Learn the most common Data Structures & Algorithms to solve coding problems. Enrol now! Master core Data Structures & Algorithms to ace interviews from IIT & Stanford Alumni. TA Support. Placements in Companies. Get Certified. 350+ Problems.A data structure is a particular way of organizing data in a computer so that it can be used effectively. </pre></body> </html>",
"e": 31166,
"s": 28902,
"text": null
},
{
"code": null,
"e": 31174,
"s": 31166,
"text": "Output:"
},
{
"code": null,
"e": 31508,
"s": 31174,
"text": "Static: This method of positioning is set by default. If we don’t mention the method of positioning for any element, the element has the position: static method by default. By defining Static, the top, right, bottom and left will not have any control over the element. The element will be positioned with the normal flow of the page."
},
{
"code": null,
"e": 31615,
"s": 31508,
"text": "Example: The below example illustrates the CSS positioning element by using the position: static property."
},
{
"code": null,
"e": 31620,
"s": 31615,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title> CSS Positioning Element</title> <style> body { margin: 0; padding: 20px; font-family: sans-serif; background: #efefef; } .static { position: static; background: #cc0000; color: #ffffff; padding: 30px; } span { padding: 5px; border: 1px #ffffff dotted; } </style></head> <body> <div class=\"static\"> This div has <span>position: static;</span> </div> <pre> Learn the most common Data Structures & Algorithms to solve coding problems. Enrol now! Master core Data Structures & Algorithms to ace interviews from IIT & Stanford Alumni. TA Support. Placements in Companies. Get Certified. 350+ Problems.A data structure is a particular way of organizing data in a computer so that it can be used effectively. Learn the most common Data Structures & Algorithms to solve coding problems. Enrol now! Master core Data Structures & Algorithms to ace interviews from IIT & Stanford Alumni. TA Support. Placements in Companies. Get Certified. 350+ Problems.A data structure is a particular way of organizing data in a computer so that it can be used effectively. Learn the most common Data Structures & Algorithms to solve coding problems. Enrol now! Master core Data Structures & Algorithms to ace interviews from IIT & Stanford Alumni. TA Support. Placements in Companies. Get Certified. 350+ Problems.A data structure is a particular way of organizing data in a computer so that it can be used effectively. Learn the most common Data Structures & Algorithms to solve coding problems. Enrol now! Master core Data Structures & Algorithms to ace interviews from IIT & Stanford Alumni. TA Support. Placements in Companies. Get Certified. 350+ Problems.A data structure is a particular way of organizing data in a computer so that it can be used effectively. </pre></body> </html>",
"e": 33755,
"s": 31620,
"text": null
},
{
"code": null,
"e": 33763,
"s": 33755,
"text": "Output:"
},
{
"code": null,
"e": 33994,
"s": 33763,
"text": "Relative: An element with position: relative is positioned relatively with the other elements which are sitting at top of it. If we set its top, right, bottom, or left, other elements will not fill up the gap left by this element."
},
{
"code": null,
"e": 34103,
"s": 33994,
"text": "Example: The below example illustrates the CSS positioning element by using the position: relative property."
},
{
"code": null,
"e": 34108,
"s": 34103,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title> CSS Positioning Element</title> <style> body { margin: 0; padding: 20px; font-family: sans-serif; background: #efefef; } .relative { position: relative; background: #cc0000; color: #ffffff; padding: 30px; } span { padding: 5px; border: 1px #ffffff dotted; } </style></head> <body> <pre> Learn the most common Data Structures & Algorithms to solve coding problems. Enrol now! Master core Data Structures & Algorithms to ace interviews from IIT & Stanford Alumni. TA Support. Placements in Companies. Get Certified. 350+ Problems.A data structure is a particular way of organizing data in a computer so that it can be used effectively. Learn the most common Data Structures & Algorithms to solve coding problems. Enrol now! Master core Data Structures & Algorithms to ace interviews from IIT & Stanford Alumni. TA Support. Placements in Companies. Get Certified. 350+ Problems.A data structure is a particular way of organizing data in a computer so that it can be used effectively. <div class=\"relative\"> This div has <span>position: relative;</span> </div> Learn the most common Data Structures & Algorithms to solve coding problems. Enrol now! Master core Data Structures & Algorithms to ace interviews from IIT & Stanford Alumni. TA Support. Placements in Companies. Get Certified. 350+ Problems.A data structure is a particular way of organizing data in a computer so that it can be used effectively. Learn the most common Data Structures & Algorithms to solve coding problems. Enrol now! Master core Data Structures & Algorithms to ace interviews from IIT & Stanford Alumni. TA Support. Placements in Companies. Get Certified. 350+ Problems.A data structure is a particular way of organizing data in a computer so that it can be used effectively. </pre></body> </html>",
"e": 36252,
"s": 34108,
"text": null
},
{
"code": null,
"e": 36260,
"s": 36252,
"text": "Output:"
},
{
"code": null,
"e": 36463,
"s": 36260,
"text": "Absolute: An element with position: absolute will be positioned with respect to its parent. The positioning of this element does not depend upon its siblings or the elements which are at the same level."
},
{
"code": null,
"e": 36572,
"s": 36463,
"text": "Example: The below example illustrates the CSS positioning element by using the position: absolute property."
},
{
"code": null,
"e": 36577,
"s": 36572,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title> CSS Positioning Element</title> <style> body { margin: 0; padding: 20px; font-family: sans-serif; background: #efefef; } .absolute { position: absolute; background: #cc0000; color: #ffffff; padding: 30px; font-size: 15px; bottom: 20px; right: 20px; } .relative { position: relative; background: #aad000; height: 300px; font-size: 30px; border: 1px solid #121212; text-align: center; } span { padding: 5px; border: 1px #ffffff dotted; } pre { padding: 20px; border: 1px solid #000000; } </style></head> <body> <pre> Learn the most common Data Structures & Algorithms to solve coding problems. Enrol now! Master core Data Structures & Algorithms to ace interviews from IIT & Stanford Alumni. TA Support. Placements in Companies. Get Certified. 350+ Problems.A data structure is a particular way of organizing data in a computer so that it can be used effectively. Learn the most common Data Structures & Algorithms to solve coding problems. Enrol now! Master core Data Structures & Algorithms to ace interviews from IIT & Stanford Alumni. TA Support. Placements in Companies. Get Certified. 350+ Problems.A data structure is a particular way of organizing data in a computer so that it can be used effectively. <div class=\"relative\"> <div > This div has <span> <strong>position: relative;</strong> </span> </div> <div class=\"absolute\"> This div has <span> <strong>position: absolute;</strong> </span> </div> </div> Learn the most common Data Structures & Algorithms to solve coding problems. Enrol now! Master core Data Structures & Algorithms to ace interviews from IIT & Stanford Alumni. TA Support. Placements in Companies. Get Certified. 350+ Problems.A data structure is a particular way of organizing data in a computer so that it can be used effectively. Learn the most common Data Structures & Algorithms to solve coding problems. Enrol now! Master core Data Structures & Algorithms to ace interviews from IIT & Stanford Alumni. TA Support. Placements in Companies. Get Certified. 350+ Problems.A data structure is a particular way of organizing data in a computer so that it can be used effectively. Learn the most common Data Structures & Algorithms to solve coding problems. Enrol now! Master core Data Structures & Algorithms to ace interviews from IIT & Stanford Alumni. TA Support. Placements in Companies. Get Certified. 350+ Problems.A data structure is a particular way of organizing data in a computer so that it can be used effectively. Learn the most common Data Structures & Algorithms to solve coding problems. Enrol now! Master core Data Structures & Algorithms to ace interviews from IIT & Stanford Alumni. TA Support. Placements in Companies. Get Certified. 350+ Problems.A data structure is a particular way of organizing data in a computer so that it can be used effectively. Learn the most common Data Structures & Algorithms to solve coding problems. Enrol now! Master core Data Structures & Algorithms to ace interviews from IIT & Stanford Alumni. TA Support. Placements in Companies. Get Certified. 350+ Problems.A data structure is a particular way of organizing data in a computer so that it can be used effectively. </pre></body> </html>",
"e": 40649,
"s": 36577,
"text": null
},
{
"code": null,
"e": 40657,
"s": 40649,
"text": "Output:"
},
{
"code": null,
"e": 41098,
"s": 40657,
"text": "Sticky: Element with position: sticky and top: 0 played a role between fixed & relative based on the position where it is placed. If the element is placed at the middle of the document then when the user scrolls the document, the sticky element starts scrolling until it touches the top. When it touches the top, it will be fixed at that place in spite of further scrolling. We can stick the element at the bottom, with the bottom property."
},
{
"code": null,
"e": 41205,
"s": 41098,
"text": "Example: The below example illustrates the CSS positioning element by using the position: sticky property."
},
{
"code": null,
"e": 41210,
"s": 41205,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title> CSS Positioning Element</title> <style> body { margin: 0; padding: 20px; font-family: sans-serif; background: #efefef; } .sticky { position: sticky; background: #cc0000; color: #ffffff; padding: 30px; top: 10px; right: 50px; } span { padding: 5px; border: 1px #ffffff dotted; } pre { padding: 20px; border: 1px solid #000000; } </style></head> <body> <pre> Learn the most common Data Structures & Algorithms to solve coding problems. Enrol now! Master core Data Structures & Algorithms to ace interviews from IIT & Stanford Alumni. TA Support. Placements in Companies. Get Certified. 350+ Problems.A data structure is a particular way of organizing data in a computer so that it can be used effectively. Learn the most common Data Structures & Algorithms to solve coding problems. Enrol now! Master core Data Structures & Algorithms to ace interviews from IIT & Stanford Alumni. TA Support. Placements in Companies. Get Certified. 350+ Problems.A data structure is a particular way of organizing data in a computer so that it can be used effectively. <div class=\"sticky\"> This div has <span>position: sticky;</span> </div> Learn the most common Data Structures & Algorithms to solve coding problems. Enrol now! Master core Data Structures & Algorithms to ace interviews from IIT & Stanford Alumni. TA Support. Placements in Companies. Get Certified. 350+ Problems.A data structure is a particular way of organizing data in a computer so that it can be used effectively. Learn the most common Data Structures & Algorithms to solve coding problems. Enrol now! Master core Data Structures & Algorithms to ace interviews from IIT & Stanford Alumni. TA Support. Placements in Companies. Get Certified. 350+ Problems.A data structure is a particular way of organizing data in a computer so that it can be used effectively. Learn the most common Data Structures & Algorithms to solve coding problems. Enrol now! Master core Data Structures & Algorithms to ace interviews from IIT & Stanford Alumni. TA Support. Placements in Companies. Get Certified. 350+ Problems.A data structure is a particular way of organizing data in a computer so that it can be used effectively. Learn the most common Data Structures & Algorithms to solve coding problems. Enrol now! Master core Data Structures & Algorithms to ace interviews from IIT & Stanford Alumni. TA Support. Placements in Companies. Get Certified. 350+ Problems.A data structure is a particular way of organizing data in a computer so that it can be used effectively. Learn the most common Data Structures & Algorithms to solve coding problems. Enrol now! Master core Data Structures & Algorithms to ace interviews from IIT & Stanford Alumni. TA Support. Placements in Companies. Get Certified. 350+ Problems.A data structure is a particular way of organizing data in a computer so that it can be used effectively. </pre></body> </html>",
"e": 44676,
"s": 41210,
"text": null
},
{
"code": null,
"e": 44684,
"s": 44676,
"text": "Output:"
},
{
"code": null,
"e": 44703,
"s": 44684,
"text": "Supported Browser:"
},
{
"code": null,
"e": 44721,
"s": 44703,
"text": "Google Chrome 1.0"
},
{
"code": null,
"e": 44741,
"s": 44721,
"text": "Microsoft Edge 12.0"
},
{
"code": null,
"e": 44753,
"s": 44741,
"text": "Firefox 1.0"
},
{
"code": null,
"e": 44775,
"s": 44753,
"text": "Internet Explorer 4.0"
},
{
"code": null,
"e": 44785,
"s": 44775,
"text": "Opera 4.0"
},
{
"code": null,
"e": 44796,
"s": 44785,
"text": "Safari 1.0"
},
{
"code": null,
"e": 44933,
"s": 44796,
"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": 44954,
"s": 44933,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 44965,
"s": 44954,
"text": "CSS-Basics"
},
{
"code": null,
"e": 44969,
"s": 44965,
"text": "CSS"
},
{
"code": null,
"e": 44974,
"s": 44969,
"text": "HTML"
},
{
"code": null,
"e": 44991,
"s": 44974,
"text": "Web Technologies"
},
{
"code": null,
"e": 44996,
"s": 44991,
"text": "HTML"
},
{
"code": null,
"e": 45094,
"s": 44996,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 45103,
"s": 45094,
"text": "Comments"
},
{
"code": null,
"e": 45116,
"s": 45103,
"text": "Old Comments"
},
{
"code": null,
"e": 45178,
"s": 45116,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 45228,
"s": 45178,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 45265,
"s": 45228,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 45323,
"s": 45265,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 45371,
"s": 45323,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 45433,
"s": 45371,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 45483,
"s": 45433,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 45507,
"s": 45483,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 45557,
"s": 45507,
"text": "How to Insert Form Data into Database using PHP ?"
}
] |
Difference between List, Set and Map in Java | 27 Sep, 2021
List interface in Java is a sub-interface of the Java collections interface. It contains the index-based methods to insert, update, delete, and search the elements. It can have duplicate elements also. We can also store the null elements in the list. List preserves the insertion order, it allows positional access and insertion of elements. It found in the java.util package. Let’s consider an example for a better understanding where you will see how you can add elements by using a list interface in java.
Example:
Java
// Java Program to illustrate the// addition of elements in a List import java.util.*;public class GFG { public static void main(String args[]) { // Creating a List List<String> al = new ArrayList<>(); // Adding elements in the List al.add("mango"); al.add("orange"); al.add("Grapes"); // Iterating the List // element using for-each loop for (String fruit : al) System.out.println(fruit); }}
Output :
mango
orange
Grapes
The Set follows the unordered way and it found in java.util package and extends the collection interface in java. Duplicate item will be ignored in Set and it will not print in the final output. Let’s consider an example for a better understanding where you will see how you can add elements by using a set interface in java. Let’s have a look.
Example:
Java
// A Java program to demonstrate a Set.// Here, you will see how you can add// Elements using Set. import java.util.*; public class SetExample { public static void main(String[] args) { // Set demonstration using HashSet Set<String> Set = new HashSet<String>(); // Adding Elements Set.add("one"); Set.add("two"); Set.add("three"); Set.add("four"); Set.add("five"); // Set follows unordered way. System.out.println(Set); }}
Output :
[four, one, two, three, five]
The Java Map interface, java.util.Map represents a mapping between a key and a value. More specifically, a Java Map can store pairs of keys and values. Each key is linked to a specific value. Once stored in a Map, you can later look up the value using just the key. Let’s consider an example for a better understanding where you will see how you can add elements by using the Map interface in java. Let’s have a look.
Example:
Java
// A sample program to demonstrate Map. // Here, you will see how you// can add elements using Mapimport java.util.*; class MapExample { public static void main(String args[]) { // Creating object for Map. Map<Integer, String> map = new HashMap<Integer, String>(); // Adding Elements using Map. map.put(100, "Amit"); map.put(101, "Vijay"); map.put(102, "Rahul"); // Elements can traverse in any order for (Map.Entry m : map.entrySet()) { System.out.println(m.getKey() + " " + m.getValue()); } }}
Output :
100 Amit
101 Vijay
102 Rahul
Difference between List, Set, and Map in Java
List
Set
Map
The list interface allows duplicate elements
Set does not allow duplicate elements.
The map does not allow duplicate elements
The list maintains insertion order.
Set do not maintain any insertion order.
The map also does not maintain any insertion order.
We can add any number of null values.
But in set almost only one null value.
The map allows a single null key at most and any number of null values.
List implementation classes are Array List, LinkedList.
Set implementation classes are HashSet, LinkedHashSet, and TreeSet.
Map implementation classes are HashMap, HashTable, TreeMap, ConcurrentHashMap, and LinkedHashMap.
The list provides get() method to get the element at a specified index.
Set does not provide get method to get the elements at a specified index
The map does not provide get method to get the elements at a specified index
If you need to access the elements frequently by using the index then we can use the list
If you want to create a collection of unique elements then we can use set
If you want to store the data in the form of key/value pair then we can use the map.
To traverse the list elements by using Listlterator.
Iterator can be used traverse the set elements
Through keyset, value, and entry set.
surinderdawra388
Java-Collections
java-list
java-map
java-set
Difference Between
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n27 Sep, 2021"
},
{
"code": null,
"e": 564,
"s": 54,
"text": "List interface in Java is a sub-interface of the Java collections interface. It contains the index-based methods to insert, update, delete, and search the elements. It can have duplicate elements also. We can also store the null elements in the list. List preserves the insertion order, it allows positional access and insertion of elements. It found in the java.util package. Let’s consider an example for a better understanding where you will see how you can add elements by using a list interface in java. "
},
{
"code": null,
"e": 573,
"s": 564,
"text": "Example:"
},
{
"code": null,
"e": 578,
"s": 573,
"text": "Java"
},
{
"code": "// Java Program to illustrate the// addition of elements in a List import java.util.*;public class GFG { public static void main(String args[]) { // Creating a List List<String> al = new ArrayList<>(); // Adding elements in the List al.add(\"mango\"); al.add(\"orange\"); al.add(\"Grapes\"); // Iterating the List // element using for-each loop for (String fruit : al) System.out.println(fruit); }}",
"e": 1058,
"s": 578,
"text": null
},
{
"code": null,
"e": 1067,
"s": 1058,
"text": "Output :"
},
{
"code": null,
"e": 1087,
"s": 1067,
"text": "mango\norange\nGrapes"
},
{
"code": null,
"e": 1432,
"s": 1087,
"text": "The Set follows the unordered way and it found in java.util package and extends the collection interface in java. Duplicate item will be ignored in Set and it will not print in the final output. Let’s consider an example for a better understanding where you will see how you can add elements by using a set interface in java. Let’s have a look."
},
{
"code": null,
"e": 1441,
"s": 1432,
"text": "Example:"
},
{
"code": null,
"e": 1446,
"s": 1441,
"text": "Java"
},
{
"code": "// A Java program to demonstrate a Set.// Here, you will see how you can add// Elements using Set. import java.util.*; public class SetExample { public static void main(String[] args) { // Set demonstration using HashSet Set<String> Set = new HashSet<String>(); // Adding Elements Set.add(\"one\"); Set.add(\"two\"); Set.add(\"three\"); Set.add(\"four\"); Set.add(\"five\"); // Set follows unordered way. System.out.println(Set); }}",
"e": 1970,
"s": 1446,
"text": null
},
{
"code": null,
"e": 1979,
"s": 1970,
"text": "Output :"
},
{
"code": null,
"e": 2009,
"s": 1979,
"text": "[four, one, two, three, five]"
},
{
"code": null,
"e": 2427,
"s": 2009,
"text": "The Java Map interface, java.util.Map represents a mapping between a key and a value. More specifically, a Java Map can store pairs of keys and values. Each key is linked to a specific value. Once stored in a Map, you can later look up the value using just the key. Let’s consider an example for a better understanding where you will see how you can add elements by using the Map interface in java. Let’s have a look."
},
{
"code": null,
"e": 2436,
"s": 2427,
"text": "Example:"
},
{
"code": null,
"e": 2441,
"s": 2436,
"text": "Java"
},
{
"code": "// A sample program to demonstrate Map. // Here, you will see how you// can add elements using Mapimport java.util.*; class MapExample { public static void main(String args[]) { // Creating object for Map. Map<Integer, String> map = new HashMap<Integer, String>(); // Adding Elements using Map. map.put(100, \"Amit\"); map.put(101, \"Vijay\"); map.put(102, \"Rahul\"); // Elements can traverse in any order for (Map.Entry m : map.entrySet()) { System.out.println(m.getKey() + \" \" + m.getValue()); } }}",
"e": 3065,
"s": 2441,
"text": null
},
{
"code": null,
"e": 3074,
"s": 3065,
"text": "Output :"
},
{
"code": null,
"e": 3103,
"s": 3074,
"text": "100 Amit\n101 Vijay\n102 Rahul"
},
{
"code": null,
"e": 3149,
"s": 3103,
"text": "Difference between List, Set, and Map in Java"
},
{
"code": null,
"e": 3154,
"s": 3149,
"text": "List"
},
{
"code": null,
"e": 3158,
"s": 3154,
"text": "Set"
},
{
"code": null,
"e": 3162,
"s": 3158,
"text": "Map"
},
{
"code": null,
"e": 3207,
"s": 3162,
"text": "The list interface allows duplicate elements"
},
{
"code": null,
"e": 3246,
"s": 3207,
"text": "Set does not allow duplicate elements."
},
{
"code": null,
"e": 3288,
"s": 3246,
"text": "The map does not allow duplicate elements"
},
{
"code": null,
"e": 3324,
"s": 3288,
"text": "The list maintains insertion order."
},
{
"code": null,
"e": 3366,
"s": 3324,
"text": "Set do not maintain any insertion order. "
},
{
"code": null,
"e": 3419,
"s": 3366,
"text": "The map also does not maintain any insertion order. "
},
{
"code": null,
"e": 3457,
"s": 3419,
"text": "We can add any number of null values."
},
{
"code": null,
"e": 3496,
"s": 3457,
"text": "But in set almost only one null value."
},
{
"code": null,
"e": 3568,
"s": 3496,
"text": "The map allows a single null key at most and any number of null values."
},
{
"code": null,
"e": 3624,
"s": 3568,
"text": "List implementation classes are Array List, LinkedList."
},
{
"code": null,
"e": 3693,
"s": 3624,
"text": "Set implementation classes are HashSet, LinkedHashSet, and TreeSet. "
},
{
"code": null,
"e": 3791,
"s": 3693,
"text": "Map implementation classes are HashMap, HashTable, TreeMap, ConcurrentHashMap, and LinkedHashMap."
},
{
"code": null,
"e": 3863,
"s": 3791,
"text": "The list provides get() method to get the element at a specified index."
},
{
"code": null,
"e": 3936,
"s": 3863,
"text": "Set does not provide get method to get the elements at a specified index"
},
{
"code": null,
"e": 4014,
"s": 3936,
"text": "The map does not provide get method to get the elements at a specified index"
},
{
"code": null,
"e": 4104,
"s": 4014,
"text": "If you need to access the elements frequently by using the index then we can use the list"
},
{
"code": null,
"e": 4178,
"s": 4104,
"text": "If you want to create a collection of unique elements then we can use set"
},
{
"code": null,
"e": 4263,
"s": 4178,
"text": "If you want to store the data in the form of key/value pair then we can use the map."
},
{
"code": null,
"e": 4316,
"s": 4263,
"text": "To traverse the list elements by using Listlterator."
},
{
"code": null,
"e": 4363,
"s": 4316,
"text": "Iterator can be used traverse the set elements"
},
{
"code": null,
"e": 4401,
"s": 4363,
"text": "Through keyset, value, and entry set."
},
{
"code": null,
"e": 4418,
"s": 4401,
"text": "surinderdawra388"
},
{
"code": null,
"e": 4435,
"s": 4418,
"text": "Java-Collections"
},
{
"code": null,
"e": 4445,
"s": 4435,
"text": "java-list"
},
{
"code": null,
"e": 4454,
"s": 4445,
"text": "java-map"
},
{
"code": null,
"e": 4463,
"s": 4454,
"text": "java-set"
},
{
"code": null,
"e": 4482,
"s": 4463,
"text": "Difference Between"
},
{
"code": null,
"e": 4487,
"s": 4482,
"text": "Java"
},
{
"code": null,
"e": 4492,
"s": 4487,
"text": "Java"
},
{
"code": null,
"e": 4509,
"s": 4492,
"text": "Java-Collections"
}
] |
Python program to read character by character from a file | 24 Jan, 2022
Given a text file. The task is to read the text from the file character by character.Function used:
Syntax: file.read(length)Parameters: An integer value specified the length of data to be read from the file.Return value: Returns the read bytes in form of a string.
Examples 1: Suppose the text file looks like this.
Python3
# Demonstrated Python Program# to read file character by character file = open('file.txt', 'r') while 1: # read by character char = file.read(1) if not char: break print(char) file.close()
Output
Example 2: REading more than one characters at a time.
Python3
# Python code to demonstrate# Read character by character with open('file.txt') as f: while True: # Read from file c = f.read(5) if not c: break # print the character print(c)
Output
anikakapoor
khushboogoyal499
Python file-handling-programs
python-file-handling
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
How to Install PIP on Windows ?
Python String | replace()
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Iterate over a list in Python
Introduction To PYTHON | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n24 Jan, 2022"
},
{
"code": null,
"e": 153,
"s": 52,
"text": "Given a text file. The task is to read the text from the file character by character.Function used: "
},
{
"code": null,
"e": 321,
"s": 153,
"text": "Syntax: file.read(length)Parameters: An integer value specified the length of data to be read from the file.Return value: Returns the read bytes in form of a string. "
},
{
"code": null,
"e": 373,
"s": 321,
"text": "Examples 1: Suppose the text file looks like this. "
},
{
"code": null,
"e": 383,
"s": 375,
"text": "Python3"
},
{
"code": "# Demonstrated Python Program# to read file character by character file = open('file.txt', 'r') while 1: # read by character char = file.read(1) if not char: break print(char) file.close()",
"e": 615,
"s": 383,
"text": null
},
{
"code": null,
"e": 624,
"s": 615,
"text": "Output "
},
{
"code": null,
"e": 681,
"s": 624,
"text": "Example 2: REading more than one characters at a time. "
},
{
"code": null,
"e": 689,
"s": 681,
"text": "Python3"
},
{
"code": "# Python code to demonstrate# Read character by character with open('file.txt') as f: while True: # Read from file c = f.read(5) if not c: break # print the character print(c)",
"e": 930,
"s": 689,
"text": null
},
{
"code": null,
"e": 939,
"s": 930,
"text": "Output "
},
{
"code": null,
"e": 953,
"s": 941,
"text": "anikakapoor"
},
{
"code": null,
"e": 970,
"s": 953,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 1000,
"s": 970,
"text": "Python file-handling-programs"
},
{
"code": null,
"e": 1021,
"s": 1000,
"text": "python-file-handling"
},
{
"code": null,
"e": 1028,
"s": 1021,
"text": "Python"
},
{
"code": null,
"e": 1126,
"s": 1028,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1144,
"s": 1126,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1186,
"s": 1144,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1208,
"s": 1186,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1240,
"s": 1208,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1266,
"s": 1240,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1295,
"s": 1266,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1322,
"s": 1295,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1343,
"s": 1322,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1373,
"s": 1343,
"text": "Iterate over a list in Python"
}
] |
Python Plotly – How to add multiple Y-axes? | 12 Jan, 2022
In this article let’s see how to add multiple y-axes of different scales in Plotly charts in Python.
Currently, Plotly Express does not support multiple Y axes on a single figure. So, we shall use Plotly go. Plotly provides a function called make_subplots() to plot charts with multiple Y – axes.
Syntax:
plotly.subplots.make_subplots(rows=1, cols=1, specs=None)
Parameter:
rows: A number of rows in the subplot grid. (rows > 0). default 1
cols: A number of columns in the subplot grid. (cols> 0). default 1
specs: (list of lists of dict or None (default None)). Per subplot specifications of subplot type, row/column spanning, and spacing.
First, import the necessary functions from the Plotly package and create the secondary axes using the specs parameter in the make_subplots() function as shown. Plot a scatter plot with multiple y-axes. Make the chart readable by adding titles to the x and y axes.
Example: Adding 2 y-axis
Python3
# import graph_objects from plotly packageimport plotly.graph_objects as go # import make_subplots function from plotly.subplots# to make grid of plotsfrom plotly.subplots import make_subplots # use specs parameter in make_subplots function# to create secondary y-axisfig = make_subplots(specs=[[{"secondary_y": True}]]) # plot a scatter chart by specifying the x and y values# Use add_trace function to specify secondary_y axes.fig.add_trace( go.Scatter(x=[10, 20, 30], y=[400, 500, 600], name="yaxis values"), secondary_y=False) # Use add_trace function and specify secondary_y axes = True.fig.add_trace( go.Scatter(x=[20, 30, 40], y=[40, 50, 60], name="yaxis2 values"), secondary_y=True,) # Adding title text to the figurefig.update_layout( title_text="Multiple Y Axis in Plotly") # Naming x-axisfig.update_xaxes(title_text="X - axis") # Naming y-axesfig.update_yaxes(title_text="<b>Main</b> Y - axis ", secondary_y=False)fig.update_yaxes(title_text="<b>secondary</b> Y - axis ", secondary_y=True)
Output:
Plotly scatter plot with multiple y-axes
Example: Adding 2 y-axis
Python3
# import graph_objects from plotly packageimport plotly.graph_objects as go # import make_subplots function from plotly.subplots# to make grid of plotsfrom plotly.subplots import make_subplots # use specs parameter in make_subplots function# to create secondary y-axisfig = make_subplots(specs=[[{"secondary_y": True}]]) # plot a bar chart by specifying the x and y values# Use add_trace function to specify secondary_y axes.fig.add_trace( go.Bar(x=[10, 20, 30], y=[40, 50, 60], name="yaxis values"), secondary_y=False) # Use add_trace function and specify secondary_y axes = True.fig.add_trace( go.Bar(x=[20, 30, 40], y=[400, 500, 600], name="yaxis2 values"), secondary_y=True,) # Adding title text to the figurefig.update_layout( title_text="Multiple Y Axis in Plotly") # Naming x-axisfig.update_xaxes(title_text="X - axis") # Naming y-axesfig.update_yaxes(title_text="<b>Main</b> Y - axis ", secondary_y=False)fig.update_yaxes(title_text="<b>secondary</b> Y - axis ", secondary_y=True)
Output:
Plotly bar chart with multiple y axes
Now, let us look at how to plot a scatter chart with more than 2 Y-axes or multiple Y-axis. The procedure is the same as above, the change comes in the figure layout part to make the chart more visually pleasing.
Import the necessary functions from the Plotly package. Create the secondary axes using the specs parameter in the make_subplots function as shown. Plot a scatter plot with multiple y-axes.
Example: Adding more than multiple y-axis
Python3
# import the graph_objects function from# plotly packageimport plotly.graph_objects as go # initialize a Figure object and store it in# a variable figfig = go.Figure() # add x and y values for the 1st scatter# plot and name the yaxis as yaxis1 valuesfig.add_trace(go.Scatter( x=[10, 12, 13], y=[41, 58, 60], name="yaxis1 values")) # add x and y values for the 2nd scatter# plot and name the yaxis as yaxis2 valuesfig.add_trace(go.Scatter( x=[12, 13, 14], y=[401, 501, 610], name="yaxis2 values", yaxis="y2")) # add x and y values for the 3rd scatter# plot and name the yaxis as yaxis3 valuesfig.add_trace(go.Scatter( x=[14, 15, 16], y=[42000, 53000, 65000], name="yaxis3 values", yaxis="y3")) # add x and y values for the 4th scatter plot# and name the yaxis as yaxis4 valuesfig.add_trace(go.Scatter( x=[15, 16, 17], y=[2000, 5000, 7000], name="yaxis4 values", yaxis="y4")) # Create axis objectsfig.update_layout( # split the x-axis to fraction of plots in # proportions xaxis=dict( domain=[0.3, 0.7] ), # pass the y-axis title, titlefont, color # and tickfont as a dictionary and store # it an variable yaxis yaxis=dict( title="yaxis 1", titlefont=dict( color="#0000ff" ), tickfont=dict( color="#0000ff" ) ), # pass the y-axis 2 title, titlefont, color and # tickfont as a dictionary and store it an # variable yaxis 2 yaxis2=dict( title="yaxis 2", titlefont=dict( color="#FF0000" ), tickfont=dict( color="#FF0000" ), anchor="free", # specifying x - axis has to be the fixed overlaying="y", # specifyinfg y - axis has to be separated side="left", # specifying the side the axis should be present position=0.2 # specifying the position of the axis ), # pass the y-axis 3 title, titlefont, color and # tickfont as a dictionary and store it an # variable yaxis 3 yaxis3=dict( title="yaxis 3", titlefont=dict( color="#006400" ), tickfont=dict( color="#006400" ), anchor="x", # specifying x - axis has to be the fixed overlaying="y", # specifyinfg y - axis has to be separated side="right" # specifying the side the axis should be present ), # pass the y-axis 4 title, titlefont, color and # tickfont as a dictionary and store it an # variable yaxis 4 yaxis4=dict( title="yaxis 4", titlefont=dict( color="#8f00ff" ), tickfont=dict( color="#8f00ff" ), anchor="free", # specifying x - axis has to be the fixed overlaying="y", # specifyinfg y - axis has to be separated side="right", # specifying the side the axis should be present position=0.8 # specifying the position of the axis )) # Update layout of the plot namely title_text, width# and place it in the center using title_x parameter# as shownfig.update_layout( title_text="4 y-axes scatter plot in plotly", width=1000, title_x=0.5)
Output:
Plotly scatter plot with multiple y – axes
sweetyty
sagartomar9927
Picked
Python-Plotly
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate over a list in Python
How to iterate through Excel rows in Python?
Rotate axis tick labels in Seaborn and Matplotlib
Enumerate() in Python
Deque in Python
Queue in Python
Defaultdict in Python
Read a file line by line in Python
Stack in Python
Different ways to create Pandas Dataframe | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Jan, 2022"
},
{
"code": null,
"e": 129,
"s": 28,
"text": "In this article let’s see how to add multiple y-axes of different scales in Plotly charts in Python."
},
{
"code": null,
"e": 326,
"s": 129,
"text": "Currently, Plotly Express does not support multiple Y axes on a single figure. So, we shall use Plotly go. Plotly provides a function called make_subplots() to plot charts with multiple Y – axes. "
},
{
"code": null,
"e": 334,
"s": 326,
"text": "Syntax:"
},
{
"code": null,
"e": 392,
"s": 334,
"text": "plotly.subplots.make_subplots(rows=1, cols=1, specs=None)"
},
{
"code": null,
"e": 403,
"s": 392,
"text": "Parameter:"
},
{
"code": null,
"e": 469,
"s": 403,
"text": "rows: A number of rows in the subplot grid. (rows > 0). default 1"
},
{
"code": null,
"e": 537,
"s": 469,
"text": "cols: A number of columns in the subplot grid. (cols> 0). default 1"
},
{
"code": null,
"e": 670,
"s": 537,
"text": "specs: (list of lists of dict or None (default None)). Per subplot specifications of subplot type, row/column spanning, and spacing."
},
{
"code": null,
"e": 934,
"s": 670,
"text": "First, import the necessary functions from the Plotly package and create the secondary axes using the specs parameter in the make_subplots() function as shown. Plot a scatter plot with multiple y-axes. Make the chart readable by adding titles to the x and y axes."
},
{
"code": null,
"e": 959,
"s": 934,
"text": "Example: Adding 2 y-axis"
},
{
"code": null,
"e": 967,
"s": 959,
"text": "Python3"
},
{
"code": "# import graph_objects from plotly packageimport plotly.graph_objects as go # import make_subplots function from plotly.subplots# to make grid of plotsfrom plotly.subplots import make_subplots # use specs parameter in make_subplots function# to create secondary y-axisfig = make_subplots(specs=[[{\"secondary_y\": True}]]) # plot a scatter chart by specifying the x and y values# Use add_trace function to specify secondary_y axes.fig.add_trace( go.Scatter(x=[10, 20, 30], y=[400, 500, 600], name=\"yaxis values\"), secondary_y=False) # Use add_trace function and specify secondary_y axes = True.fig.add_trace( go.Scatter(x=[20, 30, 40], y=[40, 50, 60], name=\"yaxis2 values\"), secondary_y=True,) # Adding title text to the figurefig.update_layout( title_text=\"Multiple Y Axis in Plotly\") # Naming x-axisfig.update_xaxes(title_text=\"X - axis\") # Naming y-axesfig.update_yaxes(title_text=\"<b>Main</b> Y - axis \", secondary_y=False)fig.update_yaxes(title_text=\"<b>secondary</b> Y - axis \", secondary_y=True)",
"e": 1983,
"s": 967,
"text": null
},
{
"code": null,
"e": 1992,
"s": 1983,
"text": " Output:"
},
{
"code": null,
"e": 2033,
"s": 1992,
"text": "Plotly scatter plot with multiple y-axes"
},
{
"code": null,
"e": 2059,
"s": 2033,
"text": "Example: Adding 2 y-axis "
},
{
"code": null,
"e": 2067,
"s": 2059,
"text": "Python3"
},
{
"code": "# import graph_objects from plotly packageimport plotly.graph_objects as go # import make_subplots function from plotly.subplots# to make grid of plotsfrom plotly.subplots import make_subplots # use specs parameter in make_subplots function# to create secondary y-axisfig = make_subplots(specs=[[{\"secondary_y\": True}]]) # plot a bar chart by specifying the x and y values# Use add_trace function to specify secondary_y axes.fig.add_trace( go.Bar(x=[10, 20, 30], y=[40, 50, 60], name=\"yaxis values\"), secondary_y=False) # Use add_trace function and specify secondary_y axes = True.fig.add_trace( go.Bar(x=[20, 30, 40], y=[400, 500, 600], name=\"yaxis2 values\"), secondary_y=True,) # Adding title text to the figurefig.update_layout( title_text=\"Multiple Y Axis in Plotly\") # Naming x-axisfig.update_xaxes(title_text=\"X - axis\") # Naming y-axesfig.update_yaxes(title_text=\"<b>Main</b> Y - axis \", secondary_y=False)fig.update_yaxes(title_text=\"<b>secondary</b> Y - axis \", secondary_y=True)",
"e": 3071,
"s": 2067,
"text": null
},
{
"code": null,
"e": 3079,
"s": 3071,
"text": "Output:"
},
{
"code": null,
"e": 3117,
"s": 3079,
"text": "Plotly bar chart with multiple y axes"
},
{
"code": null,
"e": 3330,
"s": 3117,
"text": "Now, let us look at how to plot a scatter chart with more than 2 Y-axes or multiple Y-axis. The procedure is the same as above, the change comes in the figure layout part to make the chart more visually pleasing."
},
{
"code": null,
"e": 3520,
"s": 3330,
"text": "Import the necessary functions from the Plotly package. Create the secondary axes using the specs parameter in the make_subplots function as shown. Plot a scatter plot with multiple y-axes."
},
{
"code": null,
"e": 3562,
"s": 3520,
"text": "Example: Adding more than multiple y-axis"
},
{
"code": null,
"e": 3570,
"s": 3562,
"text": "Python3"
},
{
"code": "# import the graph_objects function from# plotly packageimport plotly.graph_objects as go # initialize a Figure object and store it in# a variable figfig = go.Figure() # add x and y values for the 1st scatter# plot and name the yaxis as yaxis1 valuesfig.add_trace(go.Scatter( x=[10, 12, 13], y=[41, 58, 60], name=\"yaxis1 values\")) # add x and y values for the 2nd scatter# plot and name the yaxis as yaxis2 valuesfig.add_trace(go.Scatter( x=[12, 13, 14], y=[401, 501, 610], name=\"yaxis2 values\", yaxis=\"y2\")) # add x and y values for the 3rd scatter# plot and name the yaxis as yaxis3 valuesfig.add_trace(go.Scatter( x=[14, 15, 16], y=[42000, 53000, 65000], name=\"yaxis3 values\", yaxis=\"y3\")) # add x and y values for the 4th scatter plot# and name the yaxis as yaxis4 valuesfig.add_trace(go.Scatter( x=[15, 16, 17], y=[2000, 5000, 7000], name=\"yaxis4 values\", yaxis=\"y4\")) # Create axis objectsfig.update_layout( # split the x-axis to fraction of plots in # proportions xaxis=dict( domain=[0.3, 0.7] ), # pass the y-axis title, titlefont, color # and tickfont as a dictionary and store # it an variable yaxis yaxis=dict( title=\"yaxis 1\", titlefont=dict( color=\"#0000ff\" ), tickfont=dict( color=\"#0000ff\" ) ), # pass the y-axis 2 title, titlefont, color and # tickfont as a dictionary and store it an # variable yaxis 2 yaxis2=dict( title=\"yaxis 2\", titlefont=dict( color=\"#FF0000\" ), tickfont=dict( color=\"#FF0000\" ), anchor=\"free\", # specifying x - axis has to be the fixed overlaying=\"y\", # specifyinfg y - axis has to be separated side=\"left\", # specifying the side the axis should be present position=0.2 # specifying the position of the axis ), # pass the y-axis 3 title, titlefont, color and # tickfont as a dictionary and store it an # variable yaxis 3 yaxis3=dict( title=\"yaxis 3\", titlefont=dict( color=\"#006400\" ), tickfont=dict( color=\"#006400\" ), anchor=\"x\", # specifying x - axis has to be the fixed overlaying=\"y\", # specifyinfg y - axis has to be separated side=\"right\" # specifying the side the axis should be present ), # pass the y-axis 4 title, titlefont, color and # tickfont as a dictionary and store it an # variable yaxis 4 yaxis4=dict( title=\"yaxis 4\", titlefont=dict( color=\"#8f00ff\" ), tickfont=dict( color=\"#8f00ff\" ), anchor=\"free\", # specifying x - axis has to be the fixed overlaying=\"y\", # specifyinfg y - axis has to be separated side=\"right\", # specifying the side the axis should be present position=0.8 # specifying the position of the axis )) # Update layout of the plot namely title_text, width# and place it in the center using title_x parameter# as shownfig.update_layout( title_text=\"4 y-axes scatter plot in plotly\", width=1000, title_x=0.5)",
"e": 6723,
"s": 3570,
"text": null
},
{
"code": null,
"e": 6731,
"s": 6723,
"text": "Output:"
},
{
"code": null,
"e": 6774,
"s": 6731,
"text": "Plotly scatter plot with multiple y – axes"
},
{
"code": null,
"e": 6783,
"s": 6774,
"text": "sweetyty"
},
{
"code": null,
"e": 6798,
"s": 6783,
"text": "sagartomar9927"
},
{
"code": null,
"e": 6805,
"s": 6798,
"text": "Picked"
},
{
"code": null,
"e": 6819,
"s": 6805,
"text": "Python-Plotly"
},
{
"code": null,
"e": 6826,
"s": 6819,
"text": "Python"
},
{
"code": null,
"e": 6924,
"s": 6826,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6954,
"s": 6924,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 6999,
"s": 6954,
"text": "How to iterate through Excel rows in Python?"
},
{
"code": null,
"e": 7049,
"s": 6999,
"text": "Rotate axis tick labels in Seaborn and Matplotlib"
},
{
"code": null,
"e": 7071,
"s": 7049,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 7087,
"s": 7071,
"text": "Deque in Python"
},
{
"code": null,
"e": 7103,
"s": 7087,
"text": "Queue in Python"
},
{
"code": null,
"e": 7125,
"s": 7103,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 7160,
"s": 7125,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 7176,
"s": 7160,
"text": "Stack in Python"
}
] |
How to create softlink of a file using Python? | The method os.symlink(src, dst) creates a symbolic link dst pointing to src. For example, if you have a file called photo.jpg and want to create a softlink/symbolic link to it called my_photo.jpg, then you could simply use:
>>> import os
>>> os.symlink('photo.jpg', 'my_photo.jpg')
Now if you list the files in that directory, you'll get the my_photo.jpg there as well. | [
{
"code": null,
"e": 1411,
"s": 1187,
"text": "The method os.symlink(src, dst) creates a symbolic link dst pointing to src. For example, if you have a file called photo.jpg and want to create a softlink/symbolic link to it called my_photo.jpg, then you could simply use:"
},
{
"code": null,
"e": 1469,
"s": 1411,
"text": ">>> import os\n>>> os.symlink('photo.jpg', 'my_photo.jpg')"
},
{
"code": null,
"e": 1557,
"s": 1469,
"text": "Now if you list the files in that directory, you'll get the my_photo.jpg there as well."
}
] |
Comments In Scala | 25 Jan, 2022
Comments are entities, in our code, that the interpreter/compiler ignores. We generally use them to explain the code, and also to hide code details. It means comments will not be the part of the code. It will not be executed, rather it will be used only to explain the code in detail.In other words, The scala comments are statements which are not executed by the compiler or interpreter. The comments can be used to provide explanation or information about the variable, class, method, or any statement. This can also be used to hide program code details.In Scala, there are three types of comments:
Single – line comments.Multi – line comments.Documentation comments.
Single – line comments.
Multi – line comments.
Documentation comments.
Here we are going to explain each and every type with their syntax and example:Scala Single-Line Comments When we need only one line of a comment in Scala that is we only want to write a single line comment then we can use the characters ‘//’ preceding the comment. These character will make the line a comment. Syntax:
//Comments here( Text in this line only is considered as comment )
Example:
Scala
// This is a single line comment. object MainObject{ def main(args: Array[String]) { println("Single line comment above") }}
Output:
Single line comment above
Scala Multiline Comments If our comment is spanning in more than one line than we can use a multiline comment. we use characters ‘/*’ and ‘*/’ around the comment. That is we write a text in between these characters and it become a comment. Syntax
/*Comment starts
continues
continues
.
.
.
Comment ends*/
Example
Scala
// Scala program to show multi line comments object MainObject{ def main(args: Array[String]) { println("Multi line comments below") } /*Comment line 1 Comment line 2 Comment line 3*/}
Output
Multi line comments below
Documentation Comments in Scala A documentation comment is used for quick documentation lookup. These comments are used to document the source code by the compiler. We have the following syntax for creating a documentation comment: Syntax
/**Comment start
*
*tags are used in order to specify a parameter
*or method or heading
*HTML tags can also be used
*such as <h1>
*
*comment ends*/
Example
Scala
// Scala program to show Documentation comments object MainOb{ def main(args: Array[String]) { println("Documentation comments below") } /** * This is geek for geeks * geeks coders * */}
Output
Documentation comments below
For the declaration of such a comment, type the characters ‘/**’, and then type something, or we can press. So every time when we press the enter, the IDE will be put in a ‘*’. To end a comment, type ‘/’ after one of the carets(*).
sumitgumber28
Scala
Scala-Basics
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Type Casting in Scala
Scala Map
Scala List filter() method with example
Scala Tutorial – Learn Scala with Step By Step Guide
Scala Lists
Scala String substring() method with example
Scala | Arrays
Lambda Expression in Scala
How to Install Scala with VSCode?
How to get the first element of List in Scala | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Jan, 2022"
},
{
"code": null,
"e": 631,
"s": 28,
"text": "Comments are entities, in our code, that the interpreter/compiler ignores. We generally use them to explain the code, and also to hide code details. It means comments will not be the part of the code. It will not be executed, rather it will be used only to explain the code in detail.In other words, The scala comments are statements which are not executed by the compiler or interpreter. The comments can be used to provide explanation or information about the variable, class, method, or any statement. This can also be used to hide program code details.In Scala, there are three types of comments: "
},
{
"code": null,
"e": 700,
"s": 631,
"text": "Single – line comments.Multi – line comments.Documentation comments."
},
{
"code": null,
"e": 724,
"s": 700,
"text": "Single – line comments."
},
{
"code": null,
"e": 747,
"s": 724,
"text": "Multi – line comments."
},
{
"code": null,
"e": 771,
"s": 747,
"text": "Documentation comments."
},
{
"code": null,
"e": 1093,
"s": 771,
"text": "Here we are going to explain each and every type with their syntax and example:Scala Single-Line Comments When we need only one line of a comment in Scala that is we only want to write a single line comment then we can use the characters ‘//’ preceding the comment. These character will make the line a comment. Syntax: "
},
{
"code": null,
"e": 1160,
"s": 1093,
"text": "//Comments here( Text in this line only is considered as comment )"
},
{
"code": null,
"e": 1170,
"s": 1160,
"text": "Example: "
},
{
"code": null,
"e": 1176,
"s": 1170,
"text": "Scala"
},
{
"code": "// This is a single line comment. object MainObject{ def main(args: Array[String]) { println(\"Single line comment above\") }}",
"e": 1317,
"s": 1176,
"text": null
},
{
"code": null,
"e": 1326,
"s": 1317,
"text": "Output: "
},
{
"code": null,
"e": 1352,
"s": 1326,
"text": "Single line comment above"
},
{
"code": null,
"e": 1601,
"s": 1352,
"text": "Scala Multiline Comments If our comment is spanning in more than one line than we can use a multiline comment. we use characters ‘/*’ and ‘*/’ around the comment. That is we write a text in between these characters and it become a comment. Syntax "
},
{
"code": null,
"e": 1659,
"s": 1601,
"text": "/*Comment starts\ncontinues\ncontinues\n.\n.\n.\nComment ends*/"
},
{
"code": null,
"e": 1669,
"s": 1659,
"text": "Example "
},
{
"code": null,
"e": 1675,
"s": 1669,
"text": "Scala"
},
{
"code": "// Scala program to show multi line comments object MainObject{ def main(args: Array[String]) { println(\"Multi line comments below\") } /*Comment line 1 Comment line 2 Comment line 3*/}",
"e": 1896,
"s": 1675,
"text": null
},
{
"code": null,
"e": 1905,
"s": 1896,
"text": "Output "
},
{
"code": null,
"e": 1931,
"s": 1905,
"text": "Multi line comments below"
},
{
"code": null,
"e": 2172,
"s": 1931,
"text": "Documentation Comments in Scala A documentation comment is used for quick documentation lookup. These comments are used to document the source code by the compiler. We have the following syntax for creating a documentation comment: Syntax "
},
{
"code": null,
"e": 2321,
"s": 2172,
"text": "/**Comment start\n*\n*tags are used in order to specify a parameter\n*or method or heading\n*HTML tags can also be used \n*such as <h1>\n*\n*comment ends*/"
},
{
"code": null,
"e": 2331,
"s": 2321,
"text": "Example "
},
{
"code": null,
"e": 2337,
"s": 2331,
"text": "Scala"
},
{
"code": "// Scala program to show Documentation comments object MainOb{ def main(args: Array[String]) { println(\"Documentation comments below\") } /** * This is geek for geeks * geeks coders * */}",
"e": 2566,
"s": 2337,
"text": null
},
{
"code": null,
"e": 2575,
"s": 2566,
"text": "Output "
},
{
"code": null,
"e": 2604,
"s": 2575,
"text": "Documentation comments below"
},
{
"code": null,
"e": 2837,
"s": 2604,
"text": "For the declaration of such a comment, type the characters ‘/**’, and then type something, or we can press. So every time when we press the enter, the IDE will be put in a ‘*’. To end a comment, type ‘/’ after one of the carets(*). "
},
{
"code": null,
"e": 2851,
"s": 2837,
"text": "sumitgumber28"
},
{
"code": null,
"e": 2857,
"s": 2851,
"text": "Scala"
},
{
"code": null,
"e": 2870,
"s": 2857,
"text": "Scala-Basics"
},
{
"code": null,
"e": 2876,
"s": 2870,
"text": "Scala"
},
{
"code": null,
"e": 2974,
"s": 2876,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2996,
"s": 2974,
"text": "Type Casting in Scala"
},
{
"code": null,
"e": 3006,
"s": 2996,
"text": "Scala Map"
},
{
"code": null,
"e": 3046,
"s": 3006,
"text": "Scala List filter() method with example"
},
{
"code": null,
"e": 3099,
"s": 3046,
"text": "Scala Tutorial – Learn Scala with Step By Step Guide"
},
{
"code": null,
"e": 3111,
"s": 3099,
"text": "Scala Lists"
},
{
"code": null,
"e": 3156,
"s": 3111,
"text": "Scala String substring() method with example"
},
{
"code": null,
"e": 3171,
"s": 3156,
"text": "Scala | Arrays"
},
{
"code": null,
"e": 3198,
"s": 3171,
"text": "Lambda Expression in Scala"
},
{
"code": null,
"e": 3232,
"s": 3198,
"text": "How to Install Scala with VSCode?"
}
] |
Number of Coins | Practice | GeeksforGeeks | Given a value V and array coins[] of size M, the task is to make the change for V cents, given that you have an infinite supply of each of coins{coins1, coins2, ..., coinsm} valued coins. Find the minimum number of coins to make the change. If not possible to make change then return -1.
Example 1:
Input: V = 30, M = 3, coins[] = {25, 10, 5}
Output: 2
Explanation: Use one 25 cent coin
and one 5 cent coin
Input: V = 11, M = 4,coins[] = {9, 6, 5, 1}
Output: 2
Explanation: Use one 6 cent coin
and one 5 cent coin
0
aamitprasad618in 12 hours
CPP
int minCoins(int arr[], int n, int sum)
{
int dp[n+1][sum+1];
for(int i=0;i<=n;i++){
dp[i][0]=0;
}
for(int j=1;j<=sum;j++){
dp[0][j]=INT_MAX-1;
}
for(int j=1;j<=sum;j++){
if(j%arr[0]==0){
dp[1][j]=j/arr[0];
}
else{
dp[1][j]=INT_MAX-1;
}
}
for(int i=2;i<=n;i++){
for(int j=1;j<=sum;j++){
if(arr[i-1] <= j){
dp[i][j]=min(dp[i][j-arr[i-1]]+1,0+dp[i-1][j]);
}
else{
dp[i][j]=dp[i-1][j];
}
}
}
if(dp[n][sum]==INT_MAX-1){
return -1;
}
else{
return dp[n][sum];
}
}
0
anandpatil44053 days ago
Easy C++ code
vector<int>dp(V+1,INT_MAX); dp[0] = 0; for(int i=0;i<M;i++) { for(int j=1;j<=V;j++) { if(j-coins[i] >=0) { if(dp[j-coins[i]] != INT_MAX) dp[j] = min(dp[j],1+dp[j-coins[i]]); } } } return dp[V] ==INT_MAX ? -1:dp[V];
0
chessnoobdj4 days ago
C++ space optimized
int minCoins(int coins[], int M, int target)
{
vector <long> dp(target+1, INT_MAX);
dp[0] = 0;
for(int i=0; i<M; i++){
for(int j=1; j<=target; j++){
if(j-coins[i] >= 0)
dp[j] = min(dp[j], 1+dp[j-coins[i]]);
}
}
return dp[target] == INT_MAX ? -1 : dp[target];
}
0
parvathirajesh20015 days ago
// Simple and the best CPP soln
int dp[M+1][V+1];
for(int i=0;i<=M;++i)
{
for(int j=0;j<=V;++j)
{
if(j==0)
dp[i][j] = 0;
else if(i==0)
dp[i][j] = INT_MAX-1;
else if(coins[i-1]>j)
dp[i][j] = dp[i-1][j];
else
dp[i][j] = min(1 + dp[i][j-coins[i-1]], dp[i-1][j]);
}
}
if(dp[M][V] == INT_MAX-1)
return -1;
return dp[M][V];
}
0
akkeshri140420011 week ago
int minCoins(int coins[], int M, int V)
{
// Your code goes here
int n=M;
int W=V;
vector<vector<int>>dp(n+1,vector<int>(W+1));
for(int i=0;i<n+1;i++){
for(int j=0;j<W+1;j++){
if(i==0 and j>0){
dp[i][j]=INT_MAX-1;
}
else if(j==0){
dp[i][j]=0;
}
}
}
for(int j=1;j<W+1;j++){
if(j%coins[0]==0){
dp[1][j]=j/coins[0];
}
else{
dp[1][j]=INT_MAX-1;
}
}
for(int i=2;i<n+1;i++){
for(int j=1;j<W+1;j++){
if(j>=coins[i-1]){
dp[i][j]=min(1+dp[i][j-coins[i-1]],dp[i-1][j]);
}
else{
dp[i][j]=dp[i-1][j];
}
}
}
return dp[n][W]=(dp[n][W]==INT_MAX-1)?-1:dp[n][W];
}
0
tahabasra921 week ago
c++ recursion + memoization
public:int solve(int coins[],int i,int &V,int &M,int curr_v,vector<vector<int>> &dp){ if(curr_v==V){ return 0; } if(curr_v>V){ return 1e8; } if(i==M){ return 1e8; } if(dp[i][curr_v]!=-1) { return dp[i][curr_v]; } int a=1+solve(coins,i,V,M,curr_v+coins[i],dp); int b=solve(coins,i+1,V,M,curr_v,dp); return dp[i][curr_v]=min(a,b);}int minCoins(int coins[], int M, int V) { // Your code goes here vector<vector<int>> dp(M,vector<int>(V+1,-1)); int ans=solve(coins,0,V,M,0,dp); if( ans==1e8){ return -1; }else{ return ans; }}
0
riteshranka1 week ago
int minCoins(int coins[], int M, int V) { sort(coins, coins+M); vector<int> dp(V+1, INT_MAX); dp[0] = 0; for(int i = 1; i <= V; i++){ int j = 0; while(j < M && coins[j] <= i){ if(dp[i-coins[j]] != INT_MAX){ dp[i] = min(dp[i], dp[i-coins[j]]+1); } j++; } } if(dp[V] == INT_MAX) return -1; return dp[V];}
0
shivaraj52 weeks ago
int minCoins(int a[], int M, int V) { // Your code goes here int W=V; int n=M; int dp[n+1][W+1]; for(int i=0;i<=n;i++) dp[i][0]=0; for(int j=0;j<=W;j++) dp[0][j]=INT_MAX-1; for(int j=1;j<=W;j++){ if(j%a[0]==0) dp[1][j]=j/a[0]; else dp[1][j]=INT_MAX-1; } for(int i=2;i<=n;i++){ for(int j=1;j<=W;j++){ if(a[i-1]<=j) dp[i][j]=min(dp[i-1][j],1+dp[i][j-a[i-1]]); else dp[i][j]=dp[i-1][j]; } } if(dp[n][W]==INT_MAX || dp[n][W]==INT_MAX-1) return -1; return dp[n][W];}
0
ritikk51882 weeks ago
public: int solve(int index,int target,int coins[], vector<vector<int>> &dp){ if(dp[index][target]!=-1) return(dp[index][target]); if(index==0){ if(target%coins[0]==0) return(target/coins[0]); return(1e9); } int take=INT_MAX,notake=INT_MAX; if(target>=coins[index]) take=1+solve(index,target-coins[index],coins,dp); notake=solve(index-1,target,coins,dp); return(dp[index][target]=min(take,notake)); }int minCoins(int coins[], int M, int V) { vector<vector<int>> dp(M,vector<int>(V+1,-1)); vector<int> prev(V+1,0); for(int i=0;i<M;i++){ vector<int> curr(V+1,0); for(int j=0;j<=V;j++){ if(i==0){ if((j%coins[0])==0) curr[j]=(j/coins[0]); else curr[j]=1e9; } else{ int take=INT_MAX,notake=INT_MAX; if(j>=coins[i]) take=1+curr[j-coins[i]]; notake=prev[j]; curr[j]=min(take,notake); } } prev=curr; } //int ans=solve(M-1,V,coins,dp); if(prev[V]>=1e9) return(-1); return prev[V];}
+1
gobacktocode2 weeks ago
EASY UNDERSTANDING|| RECURSIVE+MEMOIZATION+TABULATION||
//recursive+memoization code :)int memo(int coins[],int n,int v,vector<vector<int>>& t){ if(v==0) return 0; if(n==0){ if(v%coins[0]==0) return v/coins[0]; return 1e9;//not by INT_MAX bcz to reduce memory overflow 1+1+1...memo(coins,n,v-coins[n-1],t); } if(t[n][v]!=-1) return t[n][v]; if(coins[n-1]<=v){ return t[n][v]= min(1+memo(coins,n,v-coins[n-1],t),0+memo(coins,n-1,v,t)); } return t[n][v]=memo(coins,n-1,v,t);}
//tabulation code :)int tab(int coins[],int val,int n){ int t[n+1][val+1]; for(int i=0;i<n+1;i++){ t[i][0]=0; } for(int j=0;j<=val;j++){ //only this condition is needed ..we convert base case into initialization so don't write it directly // it is formed from our memoized code in which the base case converted into initializtion condition if(val%coins[0]==0) { t[0][j]=val/coins[0]; } t[0][j]= 1e9; } for(int i=1;i<=n;i++){ for(int j=1;j<=val;j++){ if(coins[i-1]<=j){ t[i][j]= min(1+t[i][j-coins[i-1]],0+t[i-1][j]); } else t[i][j]=t[i-1][j]; } } return t[n][val]; }int minCoins(int coins[], int n, int v) { vector<vector<int>> t(n+1,vector<int>(v+1,-1));
//int ans =memo(coins,n,v,t); int ans= tab(coins,v,n); return ans>=1e9?-1:ans;}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code.
On submission, your code is tested against multiple test cases consisting of all
possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as
the final solution code.
You can view the solutions submitted by other users from the submission tab.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems 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": 526,
"s": 238,
"text": "Given a value V and array coins[] of size M, the task is to make the change for V cents, given that you have an infinite supply of each of coins{coins1, coins2, ..., coinsm} valued coins. Find the minimum number of coins to make the change. If not possible to make change then return -1."
},
{
"code": null,
"e": 538,
"s": 526,
"text": "\nExample 1:"
},
{
"code": null,
"e": 646,
"s": 538,
"text": "Input: V = 30, M = 3, coins[] = {25, 10, 5}\nOutput: 2\nExplanation: Use one 25 cent coin\nand one 5 cent coin"
},
{
"code": null,
"e": 755,
"s": 646,
"text": "Input: V = 11, M = 4,coins[] = {9, 6, 5, 1} \nOutput: 2 \nExplanation: Use one 6 cent coin\nand one 5 cent coin"
},
{
"code": null,
"e": 757,
"s": 755,
"text": "0"
},
{
"code": null,
"e": 783,
"s": 757,
"text": "aamitprasad618in 12 hours"
},
{
"code": null,
"e": 787,
"s": 783,
"text": "CPP"
},
{
"code": null,
"e": 1549,
"s": 789,
"text": "int minCoins(int arr[], int n, int sum) \n\t{ \n\t int dp[n+1][sum+1];\n\t \n\t for(int i=0;i<=n;i++){\n\t dp[i][0]=0;\n\t }\n\t for(int j=1;j<=sum;j++){\n\t dp[0][j]=INT_MAX-1;\n\t }\n\t \n\t for(int j=1;j<=sum;j++){\n\t if(j%arr[0]==0){\n\t dp[1][j]=j/arr[0];\n\t }\n\t else{\n\t dp[1][j]=INT_MAX-1;\n\t }\n\t }\n\t \n\t for(int i=2;i<=n;i++){\n\t for(int j=1;j<=sum;j++){\n\t if(arr[i-1] <= j){\n\t dp[i][j]=min(dp[i][j-arr[i-1]]+1,0+dp[i-1][j]);\n\t }\n\t else{\n\t dp[i][j]=dp[i-1][j];\n\t }\n\t }\n\t }\n\t \n\t if(dp[n][sum]==INT_MAX-1){\n\t return -1;\n\t }\n\t else{\n\t return dp[n][sum];\n\t }\n\t \n\t} "
},
{
"code": null,
"e": 1551,
"s": 1549,
"text": "0"
},
{
"code": null,
"e": 1576,
"s": 1551,
"text": "anandpatil44053 days ago"
},
{
"code": null,
"e": 1590,
"s": 1576,
"text": "Easy C++ code"
},
{
"code": null,
"e": 1906,
"s": 1592,
"text": "vector<int>dp(V+1,INT_MAX); dp[0] = 0; for(int i=0;i<M;i++) { for(int j=1;j<=V;j++) { if(j-coins[i] >=0) { if(dp[j-coins[i]] != INT_MAX) dp[j] = min(dp[j],1+dp[j-coins[i]]); } } } return dp[V] ==INT_MAX ? -1:dp[V];"
},
{
"code": null,
"e": 1908,
"s": 1906,
"text": "0"
},
{
"code": null,
"e": 1930,
"s": 1908,
"text": "chessnoobdj4 days ago"
},
{
"code": null,
"e": 1950,
"s": 1930,
"text": "C++ space optimized"
},
{
"code": null,
"e": 2250,
"s": 1950,
"text": "int minCoins(int coins[], int M, int target) \n{\n\tvector <long> dp(target+1, INT_MAX);\n\tdp[0] = 0;\n\tfor(int i=0; i<M; i++){\n\t for(int j=1; j<=target; j++){\n\t if(j-coins[i] >= 0)\n\t dp[j] = min(dp[j], 1+dp[j-coins[i]]);\n\t }\n\t}\n\treturn dp[target] == INT_MAX ? -1 : dp[target];\n} "
},
{
"code": null,
"e": 2252,
"s": 2250,
"text": "0"
},
{
"code": null,
"e": 2281,
"s": 2252,
"text": "parvathirajesh20015 days ago"
},
{
"code": null,
"e": 2313,
"s": 2281,
"text": "// Simple and the best CPP soln"
},
{
"code": null,
"e": 2838,
"s": 2315,
"text": "int dp[M+1][V+1];\n \n for(int i=0;i<=M;++i)\n {\n for(int j=0;j<=V;++j)\n {\n if(j==0)\n dp[i][j] = 0;\n else if(i==0)\n dp[i][j] = INT_MAX-1;\n else if(coins[i-1]>j)\n dp[i][j] = dp[i-1][j];\n else\n dp[i][j] = min(1 + dp[i][j-coins[i-1]], dp[i-1][j]);\n }\n }\n if(dp[M][V] == INT_MAX-1) \n return -1;\n \n return dp[M][V];\n }"
},
{
"code": null,
"e": 2840,
"s": 2838,
"text": "0"
},
{
"code": null,
"e": 2867,
"s": 2840,
"text": "akkeshri140420011 week ago"
},
{
"code": null,
"e": 3709,
"s": 2867,
"text": "int minCoins(int coins[], int M, int V) \n{ \n // Your code goes here\n int n=M;\n int W=V;\n vector<vector<int>>dp(n+1,vector<int>(W+1));\n for(int i=0;i<n+1;i++){\n for(int j=0;j<W+1;j++){\n if(i==0 and j>0){\n dp[i][j]=INT_MAX-1;\n }\n else if(j==0){\n dp[i][j]=0;\n }\n }\n }\n for(int j=1;j<W+1;j++){\n if(j%coins[0]==0){\n dp[1][j]=j/coins[0];\n }\n else{\n dp[1][j]=INT_MAX-1;\n }\n }\n for(int i=2;i<n+1;i++){\n for(int j=1;j<W+1;j++){\n if(j>=coins[i-1]){\n dp[i][j]=min(1+dp[i][j-coins[i-1]],dp[i-1][j]);\n }\n else{\n dp[i][j]=dp[i-1][j];\n }\n }\n }\n return dp[n][W]=(dp[n][W]==INT_MAX-1)?-1:dp[n][W];\n} \n "
},
{
"code": null,
"e": 3711,
"s": 3709,
"text": "0"
},
{
"code": null,
"e": 3733,
"s": 3711,
"text": "tahabasra921 week ago"
},
{
"code": null,
"e": 3761,
"s": 3733,
"text": "c++ recursion + memoization"
},
{
"code": null,
"e": 4395,
"s": 3765,
"text": "public:int solve(int coins[],int i,int &V,int &M,int curr_v,vector<vector<int>> &dp){ if(curr_v==V){ return 0; } if(curr_v>V){ return 1e8; } if(i==M){ return 1e8; } if(dp[i][curr_v]!=-1) { return dp[i][curr_v]; } int a=1+solve(coins,i,V,M,curr_v+coins[i],dp); int b=solve(coins,i+1,V,M,curr_v,dp); return dp[i][curr_v]=min(a,b);}int minCoins(int coins[], int M, int V) { // Your code goes here vector<vector<int>> dp(M,vector<int>(V+1,-1)); int ans=solve(coins,0,V,M,0,dp); if( ans==1e8){ return -1; }else{ return ans; }} "
},
{
"code": null,
"e": 4397,
"s": 4395,
"text": "0"
},
{
"code": null,
"e": 4419,
"s": 4397,
"text": "riteshranka1 week ago"
},
{
"code": null,
"e": 4866,
"s": 4419,
"text": "int minCoins(int coins[], int M, int V) { sort(coins, coins+M); vector<int> dp(V+1, INT_MAX); dp[0] = 0; for(int i = 1; i <= V; i++){ int j = 0; while(j < M && coins[j] <= i){ if(dp[i-coins[j]] != INT_MAX){ dp[i] = min(dp[i], dp[i-coins[j]]+1); } j++; } } if(dp[V] == INT_MAX) return -1; return dp[V];} "
},
{
"code": null,
"e": 4868,
"s": 4866,
"text": "0"
},
{
"code": null,
"e": 4889,
"s": 4868,
"text": "shivaraj52 weeks ago"
},
{
"code": null,
"e": 5452,
"s": 4889,
"text": "int minCoins(int a[], int M, int V) { // Your code goes here int W=V; int n=M; int dp[n+1][W+1]; for(int i=0;i<=n;i++) dp[i][0]=0; for(int j=0;j<=W;j++) dp[0][j]=INT_MAX-1; for(int j=1;j<=W;j++){ if(j%a[0]==0) dp[1][j]=j/a[0]; else dp[1][j]=INT_MAX-1; } for(int i=2;i<=n;i++){ for(int j=1;j<=W;j++){ if(a[i-1]<=j) dp[i][j]=min(dp[i-1][j],1+dp[i][j-a[i-1]]); else dp[i][j]=dp[i-1][j]; } } if(dp[n][W]==INT_MAX || dp[n][W]==INT_MAX-1) return -1; return dp[n][W];} "
},
{
"code": null,
"e": 5454,
"s": 5452,
"text": "0"
},
{
"code": null,
"e": 5476,
"s": 5454,
"text": "ritikk51882 weeks ago"
},
{
"code": null,
"e": 6673,
"s": 5476,
"text": "public: int solve(int index,int target,int coins[], vector<vector<int>> &dp){ if(dp[index][target]!=-1) return(dp[index][target]); if(index==0){ if(target%coins[0]==0) return(target/coins[0]); return(1e9); } int take=INT_MAX,notake=INT_MAX; if(target>=coins[index]) take=1+solve(index,target-coins[index],coins,dp); notake=solve(index-1,target,coins,dp); return(dp[index][target]=min(take,notake)); }int minCoins(int coins[], int M, int V) { vector<vector<int>> dp(M,vector<int>(V+1,-1)); vector<int> prev(V+1,0); for(int i=0;i<M;i++){ vector<int> curr(V+1,0); for(int j=0;j<=V;j++){ if(i==0){ if((j%coins[0])==0) curr[j]=(j/coins[0]); else curr[j]=1e9; } else{ int take=INT_MAX,notake=INT_MAX; if(j>=coins[i]) take=1+curr[j-coins[i]]; notake=prev[j]; curr[j]=min(take,notake); } } prev=curr; } //int ans=solve(M-1,V,coins,dp); if(prev[V]>=1e9) return(-1); return prev[V];} "
},
{
"code": null,
"e": 6676,
"s": 6673,
"text": "+1"
},
{
"code": null,
"e": 6700,
"s": 6676,
"text": "gobacktocode2 weeks ago"
},
{
"code": null,
"e": 6756,
"s": 6700,
"text": "EASY UNDERSTANDING|| RECURSIVE+MEMOIZATION+TABULATION||"
},
{
"code": null,
"e": 7221,
"s": 6756,
"text": "//recursive+memoization code :)int memo(int coins[],int n,int v,vector<vector<int>>& t){ if(v==0) return 0; if(n==0){ if(v%coins[0]==0) return v/coins[0]; return 1e9;//not by INT_MAX bcz to reduce memory overflow 1+1+1...memo(coins,n,v-coins[n-1],t); } if(t[n][v]!=-1) return t[n][v]; if(coins[n-1]<=v){ return t[n][v]= min(1+memo(coins,n,v-coins[n-1],t),0+memo(coins,n-1,v,t)); } return t[n][v]=memo(coins,n-1,v,t);}"
},
{
"code": null,
"e": 8163,
"s": 7221,
"text": "//tabulation code :)int tab(int coins[],int val,int n){ int t[n+1][val+1]; for(int i=0;i<n+1;i++){ t[i][0]=0; } for(int j=0;j<=val;j++){ //only this condition is needed ..we convert base case into initialization so don't write it directly // it is formed from our memoized code in which the base case converted into initializtion condition if(val%coins[0]==0) { t[0][j]=val/coins[0]; } t[0][j]= 1e9; } for(int i=1;i<=n;i++){ for(int j=1;j<=val;j++){ if(coins[i-1]<=j){ t[i][j]= min(1+t[i][j-coins[i-1]],0+t[i-1][j]); } else t[i][j]=t[i-1][j]; } } return t[n][val]; }int minCoins(int coins[], int n, int v) { vector<vector<int>> t(n+1,vector<int>(v+1,-1));"
},
{
"code": null,
"e": 8259,
"s": 8163,
"text": " //int ans =memo(coins,n,v,t); int ans= tab(coins,v,n); return ans>=1e9?-1:ans;} "
},
{
"code": null,
"e": 8407,
"s": 8261,
"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": 8443,
"s": 8407,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 8453,
"s": 8443,
"text": "\nProblem\n"
},
{
"code": null,
"e": 8463,
"s": 8453,
"text": "\nContest\n"
},
{
"code": null,
"e": 8526,
"s": 8463,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 8711,
"s": 8526,
"text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 8995,
"s": 8711,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints."
},
{
"code": null,
"e": 9141,
"s": 8995,
"text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code."
},
{
"code": null,
"e": 9218,
"s": 9141,
"text": "You can view the solutions submitted by other users from the submission tab."
},
{
"code": null,
"e": 9259,
"s": 9218,
"text": "Make sure you are not using ad-blockers."
},
{
"code": null,
"e": 9287,
"s": 9259,
"text": "Disable browser extensions."
},
{
"code": null,
"e": 9358,
"s": 9287,
"text": "We recommend using latest version of your browser for best experience."
},
{
"code": null,
"e": 9545,
"s": 9358,
"text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values."
}
] |
Types of Schedules based Recoverability in DBMS | 26 Apr, 2021
Generally, there are three types of schedule given as follows:
1. Recoverable Schedule – A schedule is said to be recoverable if it is recoverable as name suggest. Only reads are allowed before write operation on same data. Only reads (Ti->Tj) is permissible.
Example –
S1: R1(x), W1(x), R2(x), R1(y), R2(y),
W2(x), W1(y), C1, C2;
Given schedule follows order of Ti->Tj => C1->C2. Transaction T1 is executed before T2 hence there is no chances of conflict occur. R1(x) appears before W1(x) and transaction T1 is committed before T2 i.e. completion of first transaction performed first update on data item x, hence given schedule is recoverable.
Lets see example of unrecoverable schedule to clear the concept more:
S2: R1(x), R2(x), R1(z), R3(x), R3(y), W1(x),
W3(y), R2(y), W2(z), W2(y), C1, C2, C3;
Ti->Tj => C2->C3 but W3(y) executed before W2(y) which leads to conflicts thus it must be committed before T2 transaction. So given schedule is unrecoverable. if Ti->Tj => C3->C2 is given in schedule then it will become recoverable schedule.
Note: A committed transaction should never be rollback. It means that reading value from uncommitted transaction and commit it will enter the current transaction into inconsistent or unrecoverable state this is called Dirty Read problem.
Example:
2. Cascadeless Schedule – When no read or write-write occurs before execution of transaction then corresponding schedule is called cascadeless schedule.
Example –
S3: R1(x), R2(z), R3(x), R1(z), R2(y), R3(y), W1(x), C1,
W2(z), W3(y), W2(y), C3, C2;
In this schedule W3(y) and W2(y) overwrite conflicts and there is no read, therefore given schedule is cascadeless schedule.
Special Case – A committed transaction desired to abort. As given below all the transactions are reading committed data hence it’s cascadeless schedule.
3. Strict Schedule – if schedule contains no read or write before commit then it is known as strict schedule. Strict schedule is strict in nature.
Example –
S4: R1(x), R2(x), R1(z), R3(x), R3(y),
W1(x), C1, W3(y), C3, R2(y), W2(z), W2(y), C2;
In this schedule no read-write or write-write conflict arises before commit hence its strict schedule:
4. Cascading Abort – Cascading Abort can also be rollback. If transaction T1 abort as T2 read data that written by T1 which is not committed. Hence it’s cascading rollback.
Example:
Correlation between Strict, Cascadeless and Recoverable schedule:
From above figure:
Strict schedules are all recoverable and cascadeless schedules All cascadeless schedules are recoverable
Strict schedules are all recoverable and cascadeless schedules
All cascadeless schedules are recoverable
simmytarika5
DBMS
GATE CS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n26 Apr, 2021"
},
{
"code": null,
"e": 116,
"s": 52,
"text": "Generally, there are three types of schedule given as follows: "
},
{
"code": null,
"e": 316,
"s": 118,
"text": "1. Recoverable Schedule – A schedule is said to be recoverable if it is recoverable as name suggest. Only reads are allowed before write operation on same data. Only reads (Ti->Tj) is permissible. "
},
{
"code": null,
"e": 328,
"s": 316,
"text": "Example – "
},
{
"code": null,
"e": 400,
"s": 328,
"text": "S1: R1(x), W1(x), R2(x), R1(y), R2(y), \n W2(x), W1(y), C1, C2; "
},
{
"code": null,
"e": 715,
"s": 400,
"text": "Given schedule follows order of Ti->Tj => C1->C2. Transaction T1 is executed before T2 hence there is no chances of conflict occur. R1(x) appears before W1(x) and transaction T1 is committed before T2 i.e. completion of first transaction performed first update on data item x, hence given schedule is recoverable. "
},
{
"code": null,
"e": 787,
"s": 715,
"text": "Lets see example of unrecoverable schedule to clear the concept more: "
},
{
"code": null,
"e": 882,
"s": 787,
"text": "S2: R1(x), R2(x), R1(z), R3(x), R3(y), W1(x), \n W3(y), R2(y), W2(z), W2(y), C1, C2, C3; "
},
{
"code": null,
"e": 1125,
"s": 882,
"text": "Ti->Tj => C2->C3 but W3(y) executed before W2(y) which leads to conflicts thus it must be committed before T2 transaction. So given schedule is unrecoverable. if Ti->Tj => C3->C2 is given in schedule then it will become recoverable schedule. "
},
{
"code": null,
"e": 1364,
"s": 1125,
"text": "Note: A committed transaction should never be rollback. It means that reading value from uncommitted transaction and commit it will enter the current transaction into inconsistent or unrecoverable state this is called Dirty Read problem. "
},
{
"code": null,
"e": 1374,
"s": 1364,
"text": "Example: "
},
{
"code": null,
"e": 1530,
"s": 1376,
"text": "2. Cascadeless Schedule – When no read or write-write occurs before execution of transaction then corresponding schedule is called cascadeless schedule. "
},
{
"code": null,
"e": 1542,
"s": 1530,
"text": "Example – "
},
{
"code": null,
"e": 1639,
"s": 1542,
"text": "S3: R1(x), R2(z), R3(x), R1(z), R2(y), R3(y), W1(x), C1, \n W2(z), W3(y), W2(y), C3, C2; "
},
{
"code": null,
"e": 1765,
"s": 1639,
"text": "In this schedule W3(y) and W2(y) overwrite conflicts and there is no read, therefore given schedule is cascadeless schedule. "
},
{
"code": null,
"e": 1919,
"s": 1765,
"text": "Special Case – A committed transaction desired to abort. As given below all the transactions are reading committed data hence it’s cascadeless schedule. "
},
{
"code": null,
"e": 2069,
"s": 1921,
"text": "3. Strict Schedule – if schedule contains no read or write before commit then it is known as strict schedule. Strict schedule is strict in nature. "
},
{
"code": null,
"e": 2081,
"s": 2069,
"text": "Example – "
},
{
"code": null,
"e": 2177,
"s": 2081,
"text": "S4: R1(x), R2(x), R1(z), R3(x), R3(y), \n W1(x), C1, W3(y), C3, R2(y), W2(z), W2(y), C2; "
},
{
"code": null,
"e": 2281,
"s": 2177,
"text": "In this schedule no read-write or write-write conflict arises before commit hence its strict schedule: "
},
{
"code": null,
"e": 2457,
"s": 2283,
"text": "4. Cascading Abort – Cascading Abort can also be rollback. If transaction T1 abort as T2 read data that written by T1 which is not committed. Hence it’s cascading rollback. "
},
{
"code": null,
"e": 2467,
"s": 2457,
"text": "Example: "
},
{
"code": null,
"e": 2536,
"s": 2469,
"text": "Correlation between Strict, Cascadeless and Recoverable schedule: "
},
{
"code": null,
"e": 2559,
"s": 2538,
"text": "From above figure: "
},
{
"code": null,
"e": 2667,
"s": 2559,
"text": "Strict schedules are all recoverable and cascadeless schedules All cascadeless schedules are recoverable "
},
{
"code": null,
"e": 2732,
"s": 2667,
"text": "Strict schedules are all recoverable and cascadeless schedules "
},
{
"code": null,
"e": 2776,
"s": 2732,
"text": "All cascadeless schedules are recoverable "
},
{
"code": null,
"e": 2791,
"s": 2778,
"text": "simmytarika5"
},
{
"code": null,
"e": 2796,
"s": 2791,
"text": "DBMS"
},
{
"code": null,
"e": 2804,
"s": 2796,
"text": "GATE CS"
},
{
"code": null,
"e": 2809,
"s": 2804,
"text": "DBMS"
}
] |
How to find the maximum element of a Vector using STL in C++? | 19 Mar, 2019
Given a vector, find the maximum element of this vector using STL in C++.
Example:
Input: {1, 45, 54, 71, 76, 12}
Output: 76
Input: {1, 7, 5, 4, 6, 12}
Output: 12
Approach: Max or Maximum element can be found with the help of *max_element() function provided in STL.
Syntax:
*max_element (first_index, last_index);
// C++ program to find the max// of Array using *max_element() in STL #include <bits/stdc++.h>using namespace std; int main(){ // Get the vector vector<int> a = { 1, 45, 54, 71, 76, 12 }; // Print the vector cout << "Vector: "; for (int i = 0; i < a.size(); i++) cout << a[i] << " "; cout << endl; // Find the max element cout << "\nMax Element = " << *max_element(a.begin(), a.end()); return 0;}
Vector: 1 45 54 71 76 12
Max Element = 76
cpp-vector
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bitwise Operators in C/C++
Set in C++ Standard Template Library (STL)
Priority Queue in C++ Standard Template Library (STL)
vector erase() and clear() in C++
Substring in C++
unordered_map in C++ STL
Object Oriented Programming in C++
Inheritance in C++
C++ Classes and Objects
Sorting a vector in C++ | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n19 Mar, 2019"
},
{
"code": null,
"e": 126,
"s": 52,
"text": "Given a vector, find the maximum element of this vector using STL in C++."
},
{
"code": null,
"e": 135,
"s": 126,
"text": "Example:"
},
{
"code": null,
"e": 217,
"s": 135,
"text": "Input: {1, 45, 54, 71, 76, 12}\nOutput: 76\n\nInput: {1, 7, 5, 4, 6, 12}\nOutput: 12\n"
},
{
"code": null,
"e": 321,
"s": 217,
"text": "Approach: Max or Maximum element can be found with the help of *max_element() function provided in STL."
},
{
"code": null,
"e": 329,
"s": 321,
"text": "Syntax:"
},
{
"code": null,
"e": 370,
"s": 329,
"text": "*max_element (first_index, last_index);\n"
},
{
"code": "// C++ program to find the max// of Array using *max_element() in STL #include <bits/stdc++.h>using namespace std; int main(){ // Get the vector vector<int> a = { 1, 45, 54, 71, 76, 12 }; // Print the vector cout << \"Vector: \"; for (int i = 0; i < a.size(); i++) cout << a[i] << \" \"; cout << endl; // Find the max element cout << \"\\nMax Element = \" << *max_element(a.begin(), a.end()); return 0;}",
"e": 815,
"s": 370,
"text": null
},
{
"code": null,
"e": 860,
"s": 815,
"text": "Vector: 1 45 54 71 76 12 \n\nMax Element = 76\n"
},
{
"code": null,
"e": 871,
"s": 860,
"text": "cpp-vector"
},
{
"code": null,
"e": 875,
"s": 871,
"text": "STL"
},
{
"code": null,
"e": 879,
"s": 875,
"text": "C++"
},
{
"code": null,
"e": 883,
"s": 879,
"text": "STL"
},
{
"code": null,
"e": 887,
"s": 883,
"text": "CPP"
},
{
"code": null,
"e": 985,
"s": 887,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1012,
"s": 985,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 1055,
"s": 1012,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 1109,
"s": 1055,
"text": "Priority Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 1143,
"s": 1109,
"text": "vector erase() and clear() in C++"
},
{
"code": null,
"e": 1160,
"s": 1143,
"text": "Substring in C++"
},
{
"code": null,
"e": 1185,
"s": 1160,
"text": "unordered_map in C++ STL"
},
{
"code": null,
"e": 1220,
"s": 1185,
"text": "Object Oriented Programming in C++"
},
{
"code": null,
"e": 1239,
"s": 1220,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 1263,
"s": 1239,
"text": "C++ Classes and Objects"
}
] |
How to get file content and other details in AngularJS? | 14 Aug, 2020
We can get the file content by using some basic angular functions and other details like the name and size of the file in AngularJS. To understand it look into the below example where both HTML and JS files are implemented.
Note: Consider below two files are of same component in angular.
app.module.html:
<!-- Script for display data in particular format --> <!DOCTYPE html> <html><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script> <body ng-app="myApp"> <div ng-controller="MyCtrl"> <input type="file" id="myFileInput" /> <button ng-click="submit()"> Submit</button> <br /><br /> <h1> Filename: {{ fileName }} </h1> <h2> File size: {{ fileSize }} Bytes </h2> <h2> File Content: {{ fileContent }} </h2> </div></body></html>
Output:
In the above HTML file we have simply made a structure to how it should be looked on the webpage. For that, we have used some angular stuff like ‘ng-controller’ and also doubly curly brackets which we will implement in the below javascript code.
app.module.ts:
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { MatInputModule } from '@angular/material/input'; import { MatDialogModule } from '@angular/material/dialog'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatIconModule } from '@angular/material/icon'; @NgModule({ declarations: [ AppComponent, ], imports: [ BrowserModule, FormsModule, BrowserAnimationsModule, MatInputModule, MatFormFieldModule, MatIconModule, MatDialogModule, ], bootstrap: [AppComponent] }) export class AppModule { }
app.component.ts:
// Code to get file content// and other dataimport { Component, OnInit } from '@angular/core'; // Imports import { FormGroup, FormControl, } from '@angular/forms'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent implements OnInit { constructor() { } ngOnInit() { } var myApp = angular.module('myApp', []); myApp.controller('MyCtrl', function ($scope) { // Intially declaring empty string // and assigning size to zero $scope.fileContent = ''; $scope.fileSize = 0; $scope.fileName = ''; // Implementing submit function $scope.submit = function () { var file = document.getElementById("myFileInput") .files[0]; if(file) { var Reader = new FileReader(); Reader.readAsText(file, "UTF-8"); Reader.onload = function (evt) { // Getting required result // of the file $scope.fileContent = Reader.result; $scope.fileName = document.getElementById( "myFileInput").files[0].name; $scope.fileSize = document.getElementById( "myFileInput").files[0].size;; } // Printing error if data //is not proper Reader.onerror = function (evt) { $scope.fileContent = "error"; } } } }});
Output:
AngularJS-Misc
Picked
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Auth Guards in Angular 9/10/11
Routing in Angular 9/10
How to bundle an Angular app for production?
What is AOT and JIT Compiler in Angular ?
Angular PrimeNG Dropdown Component
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n14 Aug, 2020"
},
{
"code": null,
"e": 276,
"s": 52,
"text": "We can get the file content by using some basic angular functions and other details like the name and size of the file in AngularJS. To understand it look into the below example where both HTML and JS files are implemented."
},
{
"code": null,
"e": 341,
"s": 276,
"text": "Note: Consider below two files are of same component in angular."
},
{
"code": null,
"e": 358,
"s": 341,
"text": "app.module.html:"
},
{
"code": "<!-- Script for display data in particular format --> <!DOCTYPE html> <html><script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script> <body ng-app=\"myApp\"> <div ng-controller=\"MyCtrl\"> <input type=\"file\" id=\"myFileInput\" /> <button ng-click=\"submit()\"> Submit</button> <br /><br /> <h1> Filename: {{ fileName }} </h1> <h2> File size: {{ fileSize }} Bytes </h2> <h2> File Content: {{ fileContent }} </h2> </div></body></html>",
"e": 923,
"s": 358,
"text": null
},
{
"code": null,
"e": 931,
"s": 923,
"text": "Output:"
},
{
"code": null,
"e": 1177,
"s": 931,
"text": "In the above HTML file we have simply made a structure to how it should be looked on the webpage. For that, we have used some angular stuff like ‘ng-controller’ and also doubly curly brackets which we will implement in the below javascript code."
},
{
"code": null,
"e": 1192,
"s": 1177,
"text": "app.module.ts:"
},
{
"code": "import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { MatInputModule } from '@angular/material/input'; import { MatDialogModule } from '@angular/material/dialog'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatIconModule } from '@angular/material/icon'; @NgModule({ declarations: [ AppComponent, ], imports: [ BrowserModule, FormsModule, BrowserAnimationsModule, MatInputModule, MatFormFieldModule, MatIconModule, MatDialogModule, ], bootstrap: [AppComponent] }) export class AppModule { } ",
"e": 2108,
"s": 1192,
"text": null
},
{
"code": null,
"e": 2126,
"s": 2108,
"text": "app.component.ts:"
},
{
"code": "// Code to get file content// and other dataimport { Component, OnInit } from '@angular/core'; // Imports import { FormGroup, FormControl, } from '@angular/forms'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent implements OnInit { constructor() { } ngOnInit() { } var myApp = angular.module('myApp', []); myApp.controller('MyCtrl', function ($scope) { // Intially declaring empty string // and assigning size to zero $scope.fileContent = ''; $scope.fileSize = 0; $scope.fileName = ''; // Implementing submit function $scope.submit = function () { var file = document.getElementById(\"myFileInput\") .files[0]; if(file) { var Reader = new FileReader(); Reader.readAsText(file, \"UTF-8\"); Reader.onload = function (evt) { // Getting required result // of the file $scope.fileContent = Reader.result; $scope.fileName = document.getElementById( \"myFileInput\").files[0].name; $scope.fileSize = document.getElementById( \"myFileInput\").files[0].size;; } // Printing error if data //is not proper Reader.onerror = function (evt) { $scope.fileContent = \"error\"; } } } }});",
"e": 3771,
"s": 2126,
"text": null
},
{
"code": null,
"e": 3779,
"s": 3771,
"text": "Output:"
},
{
"code": null,
"e": 3794,
"s": 3779,
"text": "AngularJS-Misc"
},
{
"code": null,
"e": 3801,
"s": 3794,
"text": "Picked"
},
{
"code": null,
"e": 3811,
"s": 3801,
"text": "AngularJS"
},
{
"code": null,
"e": 3828,
"s": 3811,
"text": "Web Technologies"
},
{
"code": null,
"e": 3926,
"s": 3828,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3957,
"s": 3926,
"text": "Auth Guards in Angular 9/10/11"
},
{
"code": null,
"e": 3981,
"s": 3957,
"text": "Routing in Angular 9/10"
},
{
"code": null,
"e": 4026,
"s": 3981,
"text": "How to bundle an Angular app for production?"
},
{
"code": null,
"e": 4068,
"s": 4026,
"text": "What is AOT and JIT Compiler in Angular ?"
},
{
"code": null,
"e": 4103,
"s": 4068,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 4136,
"s": 4103,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 4198,
"s": 4136,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 4259,
"s": 4198,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4309,
"s": 4259,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Program to find correlation coefficient | 20 Jul, 2021
Given two array elements and we have to find the correlation coefficient between two arrays. The correlation coefficient is an equation that is used to determine the strength of the relation between two variables. The correlation coefficient is sometimes called as cross-correlation coefficient. Correlation coefficient always lies between -1 to +1 where -1 represents X and Y are negatively correlated and +1 represents X and Y are positively correlated.
Where r is correlation coefficient.
Correlation coefficient
= (5 * 3000 - 105 * 140)
/ sqrt((5 * 2295 - 1052)*(5*3964 - 1402))
= 300 / sqrt(450 * 220) = 0.953463
Examples :
Input : X[] = {43, 21, 25, 42, 57, 59}
Y[] = {99, 65, 79, 75, 87, 81}
Output : 0.529809
Input : X[] = {15, 18, 21, 24, 27};
Y[] = {25, 25, 27, 31, 32}
Output : 0.953463
C++
Java
Python
C#
PHP
Javascript
// Program to find correlation coefficient#include<bits/stdc++.h> using namespace std; // function that returns correlation coefficient.float correlationCoefficient(int X[], int Y[], int n){ int sum_X = 0, sum_Y = 0, sum_XY = 0; int squareSum_X = 0, squareSum_Y = 0; for (int i = 0; i < n; i++) { // sum of elements of array X. sum_X = sum_X + X[i]; // sum of elements of array Y. sum_Y = sum_Y + Y[i]; // sum of X[i] * Y[i]. sum_XY = sum_XY + X[i] * Y[i]; // sum of square of array elements. squareSum_X = squareSum_X + X[i] * X[i]; squareSum_Y = squareSum_Y + Y[i] * Y[i]; } // use formula for calculating correlation coefficient. float corr = (float)(n * sum_XY - sum_X * sum_Y) / sqrt((n * squareSum_X - sum_X * sum_X) * (n * squareSum_Y - sum_Y * sum_Y)); return corr;} // Driver functionint main(){ int X[] = {15, 18, 21, 24, 27}; int Y[] = {25, 25, 27, 31, 32}; //Find the size of array. int n = sizeof(X)/sizeof(X[0]); //Function call to correlationCoefficient. cout<<correlationCoefficient(X, Y, n); return 0;}
// JAVA Program to find correlation coefficientimport java.math.*; class GFG { // function that returns correlation coefficient. static float correlationCoefficient(int X[], int Y[], int n) { int sum_X = 0, sum_Y = 0, sum_XY = 0; int squareSum_X = 0, squareSum_Y = 0; for (int i = 0; i < n; i++) { // sum of elements of array X. sum_X = sum_X + X[i]; // sum of elements of array Y. sum_Y = sum_Y + Y[i]; // sum of X[i] * Y[i]. sum_XY = sum_XY + X[i] * Y[i]; // sum of square of array elements. squareSum_X = squareSum_X + X[i] * X[i]; squareSum_Y = squareSum_Y + Y[i] * Y[i]; } // use formula for calculating correlation // coefficient. float corr = (float)(n * sum_XY - sum_X * sum_Y)/ (float)(Math.sqrt((n * squareSum_X - sum_X * sum_X) * (n * squareSum_Y - sum_Y * sum_Y))); return corr; } // Driver function public static void main(String args[]) { int X[] = {15, 18, 21, 24, 27}; int Y[] = {25, 25, 27, 31, 32}; // Find the size of array. int n = X.length; // Function call to correlationCoefficient. System.out.printf("%6f", correlationCoefficient(X, Y, n)); }} /*This code is contributed by Nikita Tiwari.*/
# Python Program to find correlation coefficient.import math # function that returns correlation coefficient.def correlationCoefficient(X, Y, n) : sum_X = 0 sum_Y = 0 sum_XY = 0 squareSum_X = 0 squareSum_Y = 0 i = 0 while i < n : # sum of elements of array X. sum_X = sum_X + X[i] # sum of elements of array Y. sum_Y = sum_Y + Y[i] # sum of X[i] * Y[i]. sum_XY = sum_XY + X[i] * Y[i] # sum of square of array elements. squareSum_X = squareSum_X + X[i] * X[i] squareSum_Y = squareSum_Y + Y[i] * Y[i] i = i + 1 # use formula for calculating correlation # coefficient. corr = (float)(n * sum_XY - sum_X * sum_Y)/ (float)(math.sqrt((n * squareSum_X - sum_X * sum_X)* (n * squareSum_Y - sum_Y * sum_Y))) return corr # Driver functionX = [15, 18, 21, 24, 27]Y = [25, 25, 27, 31, 32] # Find the size of array.n = len(X) # Function call to correlationCoefficient.print ('{0:.6f}'.format(correlationCoefficient(X, Y, n))) # This code is contributed by Nikita Tiwari.
// C# Program to find correlation coefficientusing System; class GFG { // function that returns correlation coefficient. static float correlationCoefficient(int []X, int []Y, int n) { int sum_X = 0, sum_Y = 0, sum_XY = 0; int squareSum_X = 0, squareSum_Y = 0; for (int i = 0; i < n; i++) { // sum of elements of array X. sum_X = sum_X + X[i]; // sum of elements of array Y. sum_Y = sum_Y + Y[i]; // sum of X[i] * Y[i]. sum_XY = sum_XY + X[i] * Y[i]; // sum of square of array elements. squareSum_X = squareSum_X + X[i] * X[i]; squareSum_Y = squareSum_Y + Y[i] * Y[i]; } // use formula for calculating correlation // coefficient. float corr = (float)(n * sum_XY - sum_X * sum_Y)/ (float)(Math.Sqrt((n * squareSum_X - sum_X * sum_X) * (n * squareSum_Y - sum_Y * sum_Y))); return corr; } // Driver function public static void Main() { int []X = {15, 18, 21, 24, 27}; int []Y = {25, 25, 27, 31, 32}; // Find the size of array. int n = X.Length; // Function call to correlationCoefficient. Console.Write(Math.Round(correlationCoefficient(X, Y, n) * 1000000.0)/1000000.0); }} //This code is contributed by Anant Agarwal.
<?php// PHP Program to find// correlation coefficient // function that returns // correlation coefficient.function correlationCoefficient($X, $Y, $n){ $sum_X = 0;$sum_Y = 0; $sum_XY = 0; $squareSum_X = 0; $squareSum_Y = 0; for ($i = 0; $i < $n; $i++) { // sum of elements of array X. $sum_X = $sum_X + $X[$i]; // sum of elements of array Y. $sum_Y = $sum_Y + $Y[$i]; // sum of X[i] * Y[i]. $sum_XY = $sum_XY + $X[$i] * $Y[$i]; // sum of square of array elements. $squareSum_X = $squareSum_X + $X[$i] * $X[$i]; $squareSum_Y = $squareSum_Y + $Y[$i] * $Y[$i]; } // use formula for calculating // correlation coefficient. $corr = (float)($n * $sum_XY - $sum_X * $sum_Y) / sqrt(($n * $squareSum_X - $sum_X * $sum_X) * ($n * $squareSum_Y - $sum_Y * $sum_Y)); return $corr;} // Driver Code$X = array (15, 18, 21, 24, 27);$Y = array (25, 25, 27, 31, 32); //Find the size of array.$n = sizeof($X); //Function call to // correlationCoefficient.echo correlationCoefficient($X, $Y, $n); // This code is contributed by aj_36?>
<script> // Javascript program to find correlation coefficient // Function that returns correlation coefficient.function correlationCoefficient(X, Y, n){ let sum_X = 0, sum_Y = 0, sum_XY = 0; let squareSum_X = 0, squareSum_Y = 0; for(let i = 0; i < n; i++) { // Sum of elements of array X. sum_X = sum_X + X[i]; // Sum of elements of array Y. sum_Y = sum_Y + Y[i]; // Sum of X[i] * Y[i]. sum_XY = sum_XY + X[i] * Y[i]; // Sum of square of array elements. squareSum_X = squareSum_X + X[i] * X[i]; squareSum_Y = squareSum_Y + Y[i] * Y[i]; } // Use formula for calculating correlation // coefficient. let corr = (n * sum_XY - sum_X * sum_Y)/ (Math.sqrt((n * squareSum_X - sum_X * sum_X) * (n * squareSum_Y - sum_Y * sum_Y))); return corr;} // Driver codelet X = [ 15, 18, 21, 24, 27 ];let Y = [ 25, 25, 27, 31, 32 ]; // Find the size of array.let n = X.length; // Function call to correlationCoefficient.document.write( correlationCoefficient(X, Y, n)); // This code is contributed by susmitakundugoaldanga </script>
Output :
0.953463
jit_t
susmitakundugoaldanga
ML-Statistics
statistical-algorithms
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Prime Numbers
Program to find GCD or HCF of two numbers
Sieve of Eratosthenes
Find minimum number of coins that make a given value
Minimum number of jumps to reach end
Algorithm to solve Rubik's Cube
Modulo 10^9+7 (1000000007)
The Knight's tour problem | Backtracking-1 | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n20 Jul, 2021"
},
{
"code": null,
"e": 511,
"s": 54,
"text": "Given two array elements and we have to find the correlation coefficient between two arrays. The correlation coefficient is an equation that is used to determine the strength of the relation between two variables. The correlation coefficient is sometimes called as cross-correlation coefficient. Correlation coefficient always lies between -1 to +1 where -1 represents X and Y are negatively correlated and +1 represents X and Y are positively correlated. "
},
{
"code": null,
"e": 547,
"s": 511,
"text": "Where r is correlation coefficient."
},
{
"code": null,
"e": 682,
"s": 549,
"text": "Correlation coefficient \n= (5 * 3000 - 105 * 140) \n / sqrt((5 * 2295 - 1052)*(5*3964 - 1402))\n= 300 / sqrt(450 * 220) = 0.953463"
},
{
"code": null,
"e": 693,
"s": 682,
"text": "Examples :"
},
{
"code": null,
"e": 879,
"s": 693,
"text": "Input : X[] = {43, 21, 25, 42, 57, 59}\n Y[] = {99, 65, 79, 75, 87, 81}\nOutput : 0.529809\n\nInput : X[] = {15, 18, 21, 24, 27};\n Y[] = {25, 25, 27, 31, 32}\nOutput : 0.953463"
},
{
"code": null,
"e": 883,
"s": 879,
"text": "C++"
},
{
"code": null,
"e": 888,
"s": 883,
"text": "Java"
},
{
"code": null,
"e": 895,
"s": 888,
"text": "Python"
},
{
"code": null,
"e": 898,
"s": 895,
"text": "C#"
},
{
"code": null,
"e": 902,
"s": 898,
"text": "PHP"
},
{
"code": null,
"e": 913,
"s": 902,
"text": "Javascript"
},
{
"code": "// Program to find correlation coefficient#include<bits/stdc++.h> using namespace std; // function that returns correlation coefficient.float correlationCoefficient(int X[], int Y[], int n){ int sum_X = 0, sum_Y = 0, sum_XY = 0; int squareSum_X = 0, squareSum_Y = 0; for (int i = 0; i < n; i++) { // sum of elements of array X. sum_X = sum_X + X[i]; // sum of elements of array Y. sum_Y = sum_Y + Y[i]; // sum of X[i] * Y[i]. sum_XY = sum_XY + X[i] * Y[i]; // sum of square of array elements. squareSum_X = squareSum_X + X[i] * X[i]; squareSum_Y = squareSum_Y + Y[i] * Y[i]; } // use formula for calculating correlation coefficient. float corr = (float)(n * sum_XY - sum_X * sum_Y) / sqrt((n * squareSum_X - sum_X * sum_X) * (n * squareSum_Y - sum_Y * sum_Y)); return corr;} // Driver functionint main(){ int X[] = {15, 18, 21, 24, 27}; int Y[] = {25, 25, 27, 31, 32}; //Find the size of array. int n = sizeof(X)/sizeof(X[0]); //Function call to correlationCoefficient. cout<<correlationCoefficient(X, Y, n); return 0;}",
"e": 2106,
"s": 913,
"text": null
},
{
"code": "// JAVA Program to find correlation coefficientimport java.math.*; class GFG { // function that returns correlation coefficient. static float correlationCoefficient(int X[], int Y[], int n) { int sum_X = 0, sum_Y = 0, sum_XY = 0; int squareSum_X = 0, squareSum_Y = 0; for (int i = 0; i < n; i++) { // sum of elements of array X. sum_X = sum_X + X[i]; // sum of elements of array Y. sum_Y = sum_Y + Y[i]; // sum of X[i] * Y[i]. sum_XY = sum_XY + X[i] * Y[i]; // sum of square of array elements. squareSum_X = squareSum_X + X[i] * X[i]; squareSum_Y = squareSum_Y + Y[i] * Y[i]; } // use formula for calculating correlation // coefficient. float corr = (float)(n * sum_XY - sum_X * sum_Y)/ (float)(Math.sqrt((n * squareSum_X - sum_X * sum_X) * (n * squareSum_Y - sum_Y * sum_Y))); return corr; } // Driver function public static void main(String args[]) { int X[] = {15, 18, 21, 24, 27}; int Y[] = {25, 25, 27, 31, 32}; // Find the size of array. int n = X.length; // Function call to correlationCoefficient. System.out.printf(\"%6f\", correlationCoefficient(X, Y, n)); }} /*This code is contributed by Nikita Tiwari.*/",
"e": 3660,
"s": 2106,
"text": null
},
{
"code": "# Python Program to find correlation coefficient.import math # function that returns correlation coefficient.def correlationCoefficient(X, Y, n) : sum_X = 0 sum_Y = 0 sum_XY = 0 squareSum_X = 0 squareSum_Y = 0 i = 0 while i < n : # sum of elements of array X. sum_X = sum_X + X[i] # sum of elements of array Y. sum_Y = sum_Y + Y[i] # sum of X[i] * Y[i]. sum_XY = sum_XY + X[i] * Y[i] # sum of square of array elements. squareSum_X = squareSum_X + X[i] * X[i] squareSum_Y = squareSum_Y + Y[i] * Y[i] i = i + 1 # use formula for calculating correlation # coefficient. corr = (float)(n * sum_XY - sum_X * sum_Y)/ (float)(math.sqrt((n * squareSum_X - sum_X * sum_X)* (n * squareSum_Y - sum_Y * sum_Y))) return corr # Driver functionX = [15, 18, 21, 24, 27]Y = [25, 25, 27, 31, 32] # Find the size of array.n = len(X) # Function call to correlationCoefficient.print ('{0:.6f}'.format(correlationCoefficient(X, Y, n))) # This code is contributed by Nikita Tiwari.",
"e": 4827,
"s": 3660,
"text": null
},
{
"code": "// C# Program to find correlation coefficientusing System; class GFG { // function that returns correlation coefficient. static float correlationCoefficient(int []X, int []Y, int n) { int sum_X = 0, sum_Y = 0, sum_XY = 0; int squareSum_X = 0, squareSum_Y = 0; for (int i = 0; i < n; i++) { // sum of elements of array X. sum_X = sum_X + X[i]; // sum of elements of array Y. sum_Y = sum_Y + Y[i]; // sum of X[i] * Y[i]. sum_XY = sum_XY + X[i] * Y[i]; // sum of square of array elements. squareSum_X = squareSum_X + X[i] * X[i]; squareSum_Y = squareSum_Y + Y[i] * Y[i]; } // use formula for calculating correlation // coefficient. float corr = (float)(n * sum_XY - sum_X * sum_Y)/ (float)(Math.Sqrt((n * squareSum_X - sum_X * sum_X) * (n * squareSum_Y - sum_Y * sum_Y))); return corr; } // Driver function public static void Main() { int []X = {15, 18, 21, 24, 27}; int []Y = {25, 25, 27, 31, 32}; // Find the size of array. int n = X.Length; // Function call to correlationCoefficient. Console.Write(Math.Round(correlationCoefficient(X, Y, n) * 1000000.0)/1000000.0); }} //This code is contributed by Anant Agarwal.",
"e": 6430,
"s": 4827,
"text": null
},
{
"code": "<?php// PHP Program to find// correlation coefficient // function that returns // correlation coefficient.function correlationCoefficient($X, $Y, $n){ $sum_X = 0;$sum_Y = 0; $sum_XY = 0; $squareSum_X = 0; $squareSum_Y = 0; for ($i = 0; $i < $n; $i++) { // sum of elements of array X. $sum_X = $sum_X + $X[$i]; // sum of elements of array Y. $sum_Y = $sum_Y + $Y[$i]; // sum of X[i] * Y[i]. $sum_XY = $sum_XY + $X[$i] * $Y[$i]; // sum of square of array elements. $squareSum_X = $squareSum_X + $X[$i] * $X[$i]; $squareSum_Y = $squareSum_Y + $Y[$i] * $Y[$i]; } // use formula for calculating // correlation coefficient. $corr = (float)($n * $sum_XY - $sum_X * $sum_Y) / sqrt(($n * $squareSum_X - $sum_X * $sum_X) * ($n * $squareSum_Y - $sum_Y * $sum_Y)); return $corr;} // Driver Code$X = array (15, 18, 21, 24, 27);$Y = array (25, 25, 27, 31, 32); //Find the size of array.$n = sizeof($X); //Function call to // correlationCoefficient.echo correlationCoefficient($X, $Y, $n); // This code is contributed by aj_36?>",
"e": 7620,
"s": 6430,
"text": null
},
{
"code": "<script> // Javascript program to find correlation coefficient // Function that returns correlation coefficient.function correlationCoefficient(X, Y, n){ let sum_X = 0, sum_Y = 0, sum_XY = 0; let squareSum_X = 0, squareSum_Y = 0; for(let i = 0; i < n; i++) { // Sum of elements of array X. sum_X = sum_X + X[i]; // Sum of elements of array Y. sum_Y = sum_Y + Y[i]; // Sum of X[i] * Y[i]. sum_XY = sum_XY + X[i] * Y[i]; // Sum of square of array elements. squareSum_X = squareSum_X + X[i] * X[i]; squareSum_Y = squareSum_Y + Y[i] * Y[i]; } // Use formula for calculating correlation // coefficient. let corr = (n * sum_XY - sum_X * sum_Y)/ (Math.sqrt((n * squareSum_X - sum_X * sum_X) * (n * squareSum_Y - sum_Y * sum_Y))); return corr;} // Driver codelet X = [ 15, 18, 21, 24, 27 ];let Y = [ 25, 25, 27, 31, 32 ]; // Find the size of array.let n = X.length; // Function call to correlationCoefficient.document.write( correlationCoefficient(X, Y, n)); // This code is contributed by susmitakundugoaldanga </script>",
"e": 8882,
"s": 7620,
"text": null
},
{
"code": null,
"e": 8892,
"s": 8882,
"text": "Output : "
},
{
"code": null,
"e": 8901,
"s": 8892,
"text": "0.953463"
},
{
"code": null,
"e": 8907,
"s": 8901,
"text": "jit_t"
},
{
"code": null,
"e": 8929,
"s": 8907,
"text": "susmitakundugoaldanga"
},
{
"code": null,
"e": 8943,
"s": 8929,
"text": "ML-Statistics"
},
{
"code": null,
"e": 8966,
"s": 8943,
"text": "statistical-algorithms"
},
{
"code": null,
"e": 8979,
"s": 8966,
"text": "Mathematical"
},
{
"code": null,
"e": 8992,
"s": 8979,
"text": "Mathematical"
},
{
"code": null,
"e": 9090,
"s": 8992,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9114,
"s": 9090,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 9135,
"s": 9114,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 9149,
"s": 9135,
"text": "Prime Numbers"
},
{
"code": null,
"e": 9191,
"s": 9149,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 9213,
"s": 9191,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 9266,
"s": 9213,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 9303,
"s": 9266,
"text": "Minimum number of jumps to reach end"
},
{
"code": null,
"e": 9335,
"s": 9303,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 9362,
"s": 9335,
"text": "Modulo 10^9+7 (1000000007)"
}
] |
Distributing M items in a circle of size N starting from K-th position | 31 Jan, 2022
M items are to be delivered in a circle of size N. Find the position where the M-th item will be delivered if we start from a given position K. Note that items are distributed at adjacent positions starting from K.Examples :
Input : N = 5 // Size of circle
M = 2 // Number of items
K = 1 // Starting position
Output : 2
The first item will be given to 1st
position. Second (or last) item will
be delivered to 2nd position
Input : N = 5
M = 8
K = 2
Output : 4
The last item will be delivered to
4th position
We check if the number of items to be distributed is greater than our remaining positions in current cycle of circle or not. If yes, then we simply return m + k – 1 (We distribute items in same cycle starting from k). Else we compute number of remaining items after completing current cycle and return mod of remaining items.Below is the implementation of the above idea
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find the position where// last item is delivered.#include <bits/stdc++.h>using namespace std; // n ==> Size of circle// m ==> Number of items// k ==> Initial positionint lastPosition(int n, int m, int k){ // n - k + 1 is number of positions // before we reach beginning of circle // If m is less than this value, then // we can simply return (m-1)th position if (m <= n - k + 1) return m + k - 1; // Let us compute remaining items before // we reach beginning. m = m - (n - k + 1); // We compute m % n to skip all complete // rounds. If we reach end, we return n // else we return m % n return (m % n == 0) ? n : (m % n);} // Driver codeint main(){ int n = 5; int m = 8; int k = 2; cout << lastPosition(n, m, k); return 0;}
// Java program to find the position where// last item is delivered.class GFG { // n ==> Size of circle // m ==> Number of items // k ==> Initial position static int lastPosition(int n, int m, int k) { // n - k + 1 is number of positions // before we reach beginning of circle // If m is less than this value, then // we can simply return (m-1)th position if (m <= n - k + 1) return m + k - 1; // Let us compute remaining items before // we reach beginning. m = m - (n - k + 1); // We compute m % n to skip all complete // rounds. If we reach end, we return n // else we return m % n return (m % n == 0) ? n : (m % n); } // Driver Program to test above function public static void main(String arg[]) { int n = 5; int m = 8; int k = 2; System.out.print(lastPosition(n, m, k)); }} // This code is contributed by Anant Agarwal.
# Python program to find the position where# last item is delivered. # n ==> Size of circle# m ==> Number of items# k ==> Initial positiondef lastPosition(n, m, k): # n - k + 1 is number of positions # before we reach beginning of circle # If m is less than this value, then # we can simply return (m-1)th position if (m <= n - k + 1): return m + k - 1 # Let us compute remaining items before # we reach beginning. m = m - (n - k + 1) # We compute m % n to skip all complete # rounds. If we reach end, we return n # else we return m % n if(m % n == 0): return n else: return m % n # Driver coden = 5m = 8k = 2print(lastPosition(n, m, k)) # This code is contributed by Sachin Bisht
// C# program to find the position where// last item is delivered.using System; class GFG { // n ==> Size of circle // m ==> Number of items // k ==> Initial position static int lastPosition(int n, int m, int k) { // n - k + 1 is number of positions // before we reach beginning of circle // If m is less than this value, then // we can simply return (m-1)th position if (m <= n - k + 1) return m + k - 1; // Let us compute remaining items before // we reach beginning. m = m - (n - k + 1); // We compute m % n to skip all complete // rounds. If we reach end, we return n // else we return m % n return (m % n == 0) ? n : (m % n); } // Driver Program to test above function public static void Main() { int n = 5; int m = 8; int k = 2; Console.WriteLine(lastPosition(n, m, k)); }} // This code is contributed by vt_m.
<?php// PHP program to find the// position where last item// is delivered. // n ==> Size of circle// m ==> Number of items// k ==> Initial position function lastPosition($n, $m, $k){ // n - k + 1 is number of // positions before we reach // beginning of circle. // If m is less than this value, // then we can simply return // (m-1)th position if ($m <= $n - $k + 1) return $m + $k - 1; // Let us compute remaining items // before we reach beginning. $m = $m - ($n - $k + 1); // We compute m % n to skip // all complete rounds. If we // reach end, we return n // else we return m % n return ($m % $n == 0) ? $n : ($m % $n);} // Driver code$n = 5;$m = 8;$k = 2;echo lastPosition($n, $m, $k); // This code is contributed by ajit?>
<script>// Javascript program to find the// position where last item// is delivered. // n ==> Size of circle// m ==> Number of items// k ==> Initial position function lastPosition(n, m, k){ // n - k + 1 is number of // positions before we reach // beginning of circle. // If m is less than this value, // then we can simply return // (m-1)th position if (m <= n - k + 1) return m + k - 1; // Let us compute remaining items // before we reach beginning. m = m - (n - k + 1); // We compute m % n to skip // all complete rounds. If we // reach end, we return n // else we return m % n return (m % n == 0) ? n : (m % n);} // Driver codelet n = 5;let m = 8;let k = 2;document.write(lastPosition(n, m, k)); // This code is contributed by _saurabh_jaiswal</script>
Output :
4
Time Complexity : O(1)This article is contributed by Sarthak Kohli. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [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.
vt_m
jit_t
ishitas0301
_saurabh_jaiswal
amartyaghoshgfg
Modular Arithmetic
Mathematical
Mathematical
Modular Arithmetic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Merge two sorted arrays with O(1) extra space
Program to print prime numbers from 1 to N.
Find next greater number with same set of digits
Segment Tree | Set 1 (Sum of given range)
Check if a number is Palindrome
Count ways to reach the n'th stair
Fizz Buzz Implementation
Count all possible paths from top left to bottom right of a mXn matrix
Product of Array except itself | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n31 Jan, 2022"
},
{
"code": null,
"e": 279,
"s": 52,
"text": "M items are to be delivered in a circle of size N. Find the position where the M-th item will be delivered if we start from a given position K. Note that items are distributed at adjacent positions starting from K.Examples : "
},
{
"code": null,
"e": 599,
"s": 279,
"text": "Input : N = 5 // Size of circle\n M = 2 // Number of items\n K = 1 // Starting position\nOutput : 2\nThe first item will be given to 1st \nposition. Second (or last) item will \nbe delivered to 2nd position\n\nInput : N = 5 \n M = 8 \n K = 2\nOutput : 4\nThe last item will be delivered to \n4th position"
},
{
"code": null,
"e": 974,
"s": 601,
"text": "We check if the number of items to be distributed is greater than our remaining positions in current cycle of circle or not. If yes, then we simply return m + k – 1 (We distribute items in same cycle starting from k). Else we compute number of remaining items after completing current cycle and return mod of remaining items.Below is the implementation of the above idea "
},
{
"code": null,
"e": 978,
"s": 974,
"text": "C++"
},
{
"code": null,
"e": 983,
"s": 978,
"text": "Java"
},
{
"code": null,
"e": 991,
"s": 983,
"text": "Python3"
},
{
"code": null,
"e": 994,
"s": 991,
"text": "C#"
},
{
"code": null,
"e": 998,
"s": 994,
"text": "PHP"
},
{
"code": null,
"e": 1009,
"s": 998,
"text": "Javascript"
},
{
"code": "// C++ program to find the position where// last item is delivered.#include <bits/stdc++.h>using namespace std; // n ==> Size of circle// m ==> Number of items// k ==> Initial positionint lastPosition(int n, int m, int k){ // n - k + 1 is number of positions // before we reach beginning of circle // If m is less than this value, then // we can simply return (m-1)th position if (m <= n - k + 1) return m + k - 1; // Let us compute remaining items before // we reach beginning. m = m - (n - k + 1); // We compute m % n to skip all complete // rounds. If we reach end, we return n // else we return m % n return (m % n == 0) ? n : (m % n);} // Driver codeint main(){ int n = 5; int m = 8; int k = 2; cout << lastPosition(n, m, k); return 0;}",
"e": 1811,
"s": 1009,
"text": null
},
{
"code": "// Java program to find the position where// last item is delivered.class GFG { // n ==> Size of circle // m ==> Number of items // k ==> Initial position static int lastPosition(int n, int m, int k) { // n - k + 1 is number of positions // before we reach beginning of circle // If m is less than this value, then // we can simply return (m-1)th position if (m <= n - k + 1) return m + k - 1; // Let us compute remaining items before // we reach beginning. m = m - (n - k + 1); // We compute m % n to skip all complete // rounds. If we reach end, we return n // else we return m % n return (m % n == 0) ? n : (m % n); } // Driver Program to test above function public static void main(String arg[]) { int n = 5; int m = 8; int k = 2; System.out.print(lastPosition(n, m, k)); }} // This code is contributed by Anant Agarwal.",
"e": 2794,
"s": 1811,
"text": null
},
{
"code": "# Python program to find the position where# last item is delivered. # n ==> Size of circle# m ==> Number of items# k ==> Initial positiondef lastPosition(n, m, k): # n - k + 1 is number of positions # before we reach beginning of circle # If m is less than this value, then # we can simply return (m-1)th position if (m <= n - k + 1): return m + k - 1 # Let us compute remaining items before # we reach beginning. m = m - (n - k + 1) # We compute m % n to skip all complete # rounds. If we reach end, we return n # else we return m % n if(m % n == 0): return n else: return m % n # Driver coden = 5m = 8k = 2print(lastPosition(n, m, k)) # This code is contributed by Sachin Bisht",
"e": 3544,
"s": 2794,
"text": null
},
{
"code": "// C# program to find the position where// last item is delivered.using System; class GFG { // n ==> Size of circle // m ==> Number of items // k ==> Initial position static int lastPosition(int n, int m, int k) { // n - k + 1 is number of positions // before we reach beginning of circle // If m is less than this value, then // we can simply return (m-1)th position if (m <= n - k + 1) return m + k - 1; // Let us compute remaining items before // we reach beginning. m = m - (n - k + 1); // We compute m % n to skip all complete // rounds. If we reach end, we return n // else we return m % n return (m % n == 0) ? n : (m % n); } // Driver Program to test above function public static void Main() { int n = 5; int m = 8; int k = 2; Console.WriteLine(lastPosition(n, m, k)); }} // This code is contributed by vt_m.",
"e": 4520,
"s": 3544,
"text": null
},
{
"code": "<?php// PHP program to find the// position where last item// is delivered. // n ==> Size of circle// m ==> Number of items// k ==> Initial position function lastPosition($n, $m, $k){ // n - k + 1 is number of // positions before we reach // beginning of circle. // If m is less than this value, // then we can simply return // (m-1)th position if ($m <= $n - $k + 1) return $m + $k - 1; // Let us compute remaining items // before we reach beginning. $m = $m - ($n - $k + 1); // We compute m % n to skip // all complete rounds. If we // reach end, we return n // else we return m % n return ($m % $n == 0) ? $n : ($m % $n);} // Driver code$n = 5;$m = 8;$k = 2;echo lastPosition($n, $m, $k); // This code is contributed by ajit?>",
"e": 5299,
"s": 4520,
"text": null
},
{
"code": "<script>// Javascript program to find the// position where last item// is delivered. // n ==> Size of circle// m ==> Number of items// k ==> Initial position function lastPosition(n, m, k){ // n - k + 1 is number of // positions before we reach // beginning of circle. // If m is less than this value, // then we can simply return // (m-1)th position if (m <= n - k + 1) return m + k - 1; // Let us compute remaining items // before we reach beginning. m = m - (n - k + 1); // We compute m % n to skip // all complete rounds. If we // reach end, we return n // else we return m % n return (m % n == 0) ? n : (m % n);} // Driver codelet n = 5;let m = 8;let k = 2;document.write(lastPosition(n, m, k)); // This code is contributed by _saurabh_jaiswal</script>",
"e": 6108,
"s": 5299,
"text": null
},
{
"code": null,
"e": 6119,
"s": 6108,
"text": "Output : "
},
{
"code": null,
"e": 6121,
"s": 6119,
"text": "4"
},
{
"code": null,
"e": 6565,
"s": 6121,
"text": "Time Complexity : O(1)This article is contributed by Sarthak Kohli. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [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": 6570,
"s": 6565,
"text": "vt_m"
},
{
"code": null,
"e": 6576,
"s": 6570,
"text": "jit_t"
},
{
"code": null,
"e": 6588,
"s": 6576,
"text": "ishitas0301"
},
{
"code": null,
"e": 6605,
"s": 6588,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 6621,
"s": 6605,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 6640,
"s": 6621,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 6653,
"s": 6640,
"text": "Mathematical"
},
{
"code": null,
"e": 6666,
"s": 6653,
"text": "Mathematical"
},
{
"code": null,
"e": 6685,
"s": 6666,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 6783,
"s": 6685,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6815,
"s": 6783,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 6861,
"s": 6815,
"text": "Merge two sorted arrays with O(1) extra space"
},
{
"code": null,
"e": 6905,
"s": 6861,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 6954,
"s": 6905,
"text": "Find next greater number with same set of digits"
},
{
"code": null,
"e": 6996,
"s": 6954,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 7028,
"s": 6996,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 7063,
"s": 7028,
"text": "Count ways to reach the n'th stair"
},
{
"code": null,
"e": 7088,
"s": 7063,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 7159,
"s": 7088,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
}
] |
Print all possible consecutive numbers with sum N | 13 May, 2022
Given a number N. The task is to print all possible consecutive numbers that add up to N.
Examples :
Input: N = 100
Output:
9 10 11 12 13 14 15 16
18 19 20 21 22
Input: N = 125
Output:
8 9 10 11 12 13 14 15 16 17
23 24 25 26 27
62 63
One important fact is we can not find consecutive numbers above N/2 that adds up to N, because N/2 + (N/2 + 1) would be more than N. So we start from start = 1 till end = N/2 and check for every consecutive sequence whether it adds up to N or not. If it is then we print that sequence and start looking for the next sequence by incrementing start point.
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to print consecutive sequences// that add to a given value#include<bits/stdc++.h>using namespace std; void findConsecutive(int N){ // Note that we don't ever have to sum // numbers > ceil(N/2) int start = 1, end = (N+1)/2; // Repeat the loop from bottom to half while (start < end) { // Check if there exist any sequence // from bottom to half which adds up to N int sum = 0; for (int i = start; i <= end; i++) { sum = sum + i; // If sum = N, this means consecutive // sequence exists if (sum == N) { // found consecutive numbers! print them for (int j = start; j <= i; j++) cout <<" "<< j; cout <<"\n"; break; } // if sum increases N then it can not exist // in the consecutive sequence starting from // bottom if (sum > N) break; } sum = 0; start++; }} // Driver codeint main(void){ int N = 125; findConsecutive(N); return 0;} // This code is contributed by shivanisinghss2110
// C++ program to print consecutive sequences// that add to a given value#include<stdio.h> void findConsecutive(int N){ // Note that we don't ever have to sum // numbers > ceil(N/2) int start = 1, end = (N+1)/2; // Repeat the loop from bottom to half while (start < end) { // Check if there exist any sequence // from bottom to half which adds up to N int sum = 0; for (int i = start; i <= end; i++) { sum = sum + i; // If sum = N, this means consecutive // sequence exists if (sum == N) { // found consecutive numbers! print them for (int j = start; j <= i; j++) printf("%d ", j); printf("\n"); break; } // if sum increases N then it can not exist // in the consecutive sequence starting from // bottom if (sum > N) break; } sum = 0; start++; }} // Driver codeint main(void){ int N = 125; findConsecutive(N); return 0;}
// Java program to print// consecutive sequences// that add to a given valueimport java.io.*; class GFG{static void findConsecutive(int N){ // Note that we don't // ever have to sum // numbers > ceil(N/2) int start = 1; int end = (N + 1) / 2; // Repeat the loop // from bottom to half while (start < end) { // Check if there exist // any sequence from // bottom to half which // adds up to N int sum = 0; for (int i = start; i <= end; i++) { sum = sum + i; // If sum = N, this means // consecutive sequence exists if (sum == N) { // found consecutive // numbers! print them for (int j = start; j <= i; j++) System.out.print(j + " "); System.out.println(); break; } // if sum increases N then // it can not exist in the // consecutive sequence // starting from bottom if (sum > N) break; } sum = 0; start++; }} // Driver codepublic static void main (String[] args){ int N = 125; findConsecutive(N);}} // This code is contributed by m_kit
# Python3 program to print consecutive# sequences that add to a given valuedef findConsecutive(N): # Note that we don't ever have to # Sum numbers > ceil(N/2) start = 1 end = (N + 1) // 2 # Repeat the loop from bottom to half while (start < end): # Check if there exist any sequence # from bottom to half which adds up to N Sum = 0 for i in range(start, end + 1): Sum = Sum + i # If Sum = N, this means consecutive # sequence exists if (Sum == N): # found consecutive numbers! print them for j in range(start, i + 1): print(j, end = " ") print() break # if Sum increases N then it can not # exist in the consecutive sequence # starting from bottom if (Sum > N): break Sum = 0 start += 1 # Driver codeN = 125findConsecutive(N) # This code is contributed by Mohit kumar 29
// C# program to print// consecutive sequences// that add to a given valueusing System; class GFG{static void findConsecutive(int N){ // Note that we don't // ever have to sum // numbers > ceil(N/2) int start = 1; int end = (N + 1) / 2; // Repeat the loop // from bottom to half while (start < end) { // Check if there exist // any sequence from // bottom to half which // adds up to N int sum = 0; for (int i = start; i <= end; i++) { sum = sum + i; // If sum = N, this means // consecutive sequence exists if (sum == N) { // found consecutive // numbers! print them for (int j = start; j <= i; j++) Console.Write(j + " "); Console.WriteLine(); break; } // if sum increases N then // it can not exist in the // consecutive sequence // starting from bottom if (sum > N) break; } sum = 0; start++; }} // Driver codestatic public void Main (){ int N = 125; findConsecutive(N);}} // This code is contributed by ajit
<?php// PHP program to print consecutive// sequences that add to a given value function findConsecutive($N){ // Note that we don't ever have // to sum numbers > ceil(N/2) $start = 1; $end = ($N + 1) / 2; // Repeat the loop from // bottom to half while ($start < $end) { // Check if there exist any // sequence from bottom to // half which adds up to N $sum = 0; for ($i = $start; $i <= $end; $i++) { $sum = $sum + $i; // If sum = N, this means // consecutive sequence exists if ($sum == $N) { // found consecutive // numbers! print them for ($j = $start; $j <= $i; $j++) echo $j ," "; echo "\n"; break; } // if sum increases N then it // can not exist in the consecutive // sequence starting from bottom if ($sum > $N) break; } $sum = 0; $start++; }} // Driver code$N = 125;findConsecutive($N); // This code is contributed by ajit?>
<script> // Javascript program to print consecutive sequences// that add to a given value function findConsecutive( N){ // Note that we don't ever have to sum // numbers > ceil(N/2) let start = 1, end = Math.trunc((N+1)/2); // Repeat the loop from bottom to half while (start < end) { // Check if there exist any sequence // from bottom to half which adds up to N let sum = 0; for (let i = start; i <= end; i++) { sum = sum + i; // If sum = N, this means consecutive // sequence exists if (sum == N) { // found consecutive numbers! print them for (let j = start; j <= i; j++) document.write(j+" "); document.write("<br/>"); break; } // if sum increases N then it can not exist // in the consecutive sequence starting from // bottom if (sum > N) break; } sum = 0; start++; }} // Driver program let N = 125; findConsecutive(N); </script>
Output :
8 9 10 11 12 13 14 15 16 17
23 24 25 26 27
62 63
Optimized Solution: In the above solution, we keep recalculating sums from start to end, which results in O(N^2) worst-case time complexity. This can be avoided by using a precomputed array of sums, or better yet – just keeping track of the sum you have so far and adjusting it depending on how it compares to the desired sum.Time complexity of below code is O(N).
C++
C
Java
Python3
C#
PHP
Javascript
// Optimized C++ program to find sequences of all consecutive// numbers with sum equal to N#include <bits/stdc++.h>using namespace std; void printSums(int N){ int start = 1, end = 1; int sum = 1; while (start <= N/2) { if (sum < N) { end += 1; sum += end; } else if (sum > N) { sum -= start; start += 1; } else if (sum == N) { for (int i = start; i <= end; ++i) cout <<" "<< i; cout <<"\n"; sum -= start; start += 1; } }} // Driver Codeint main(){ printSums(125); return 0;} // this code is contributed by shivanisinghss2110
// Optimized C program to find sequences of all consecutive// numbers with sum equal to N#include <stdio.h> void printSums(int N){ int start = 1, end = 1; int sum = 1; while (start <= N/2) { if (sum < N) { end += 1; sum += end; } else if (sum > N) { sum -= start; start += 1; } else if (sum == N) { for (int i = start; i <= end; ++i) printf("%d ", i); printf("\n"); sum -= start; start += 1; } }} // Driver Codeint main(){ printSums(125); return 0;}
// Optimized Java program to find// sequences of all consecutive// numbers with sum equal to Nimport java.io.*; class GFG { static void printSums(int N) { int start = 1, end = 1; int sum = 1; while (start <= N/2) { if (sum < N) { end += 1; sum += end; } else if (sum > N) { sum -= start; start += 1; } else if (sum == N) { for (int i = start; i <= end; ++i) System.out.print(i + " "); System.out.println(); sum -= start; start += 1; } } } // Driver Code public static void main (String[] args) { printSums(125); }} // This code is contributed by anuj_67.
# Optimized Python3 program to find sequences of all consecutive# numbers with sum equal to Ndef findConsecutive(N): start = 1 end = 1 sum = 1 while start <= N/2: if sum < N: end += 1 sum += end if sum > N: sum -= start start += 1 if sum == N: for i in range(start, end + 1): print(i, end=' ') print( ) sum -= start start += 1 # Driver codeN = 125findConsecutive(N) # This code is contributed by Sanskriti Agrawal
// Optimized C# program to find// sequences of all consecutive// numbers with sum equal to Nusing System; class GFG { static void printSums(int N) { int start = 1, end = 1; int sum = 1; while (start <= N/2) { if (sum < N) { end += 1; sum += end; } else if (sum > N) { sum -= start; start += 1; } else if (sum == N) { for (int i = start; i <= end; ++i) Console.Write(i + " "); Console.WriteLine(); sum -= start; start += 1; } } } // Driver Code public static void Main () { printSums(125); }} // This code is contributed by anuj_67.
<?php// Optimized PHP program to find// sequences of all consecutive// numbers with sum equal to N function printSums($N){ $start = 1; $end = 1; $sum = 1; while ($start <= $N / 2) { if ($sum < $N) { $end += 1; $sum += $end; } else if ($sum > $N) { $sum -= $start; $start += 1; } else if ($sum == $N) { for ($i = $start; $i <= $end; ++$i) echo $i," "; echo "\n"; $sum -= $start; $start += 1; } }} // Driver Code printSums(125); // This code is contributed by jit_t?>
<script> // Javascript program to find// sequences of all consecutive// numbers with sum equal to Nfunction printSums(N){ let start = 1, end = 1; let sum = 1; while (start <= N / 2) { if (sum < N) { end += 1; sum += end; } else if (sum > N) { sum -= start; start += 1; } else if (sum == N) { for(let i = start; i <= end; ++i) document.write(i + " "); document.write("<br/>"); sum -= start; start += 1; } }} // Driver code printSums(125); // This code is contributed by splevel62 </script>
Output :
8 9 10 11 12 13 14 15 16 17
23 24 25 26 27
62 63
Reference : https://www.careercup.com/page?pid=microsoft-interview-questions&n=2This article is contributed by Niteesh Kumar. 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.
vt_m
jit_t
mohit kumar 29
Stark17
splevel62
jana_sayantan
shivanisinghss2110
simmytarika5
varshagumber28
Binary Search
Searching
Searching
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Search, insert and delete in an unsorted array
Median of two sorted arrays of different sizes
k largest(or smallest) elements in an array
Two Pointers Technique
Search, insert and delete in a sorted array
Find the index of an array element in Java
Find a peak element
Most frequent element in an array
Median of two sorted arrays of same size | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n13 May, 2022"
},
{
"code": null,
"e": 142,
"s": 52,
"text": "Given a number N. The task is to print all possible consecutive numbers that add up to N."
},
{
"code": null,
"e": 154,
"s": 142,
"text": "Examples : "
},
{
"code": null,
"e": 293,
"s": 154,
"text": "Input: N = 100\nOutput:\n9 10 11 12 13 14 15 16 \n18 19 20 21 22 \n\nInput: N = 125\nOutput:\n8 9 10 11 12 13 14 15 16 17 \n23 24 25 26 27 \n62 63 "
},
{
"code": null,
"e": 648,
"s": 293,
"text": "One important fact is we can not find consecutive numbers above N/2 that adds up to N, because N/2 + (N/2 + 1) would be more than N. So we start from start = 1 till end = N/2 and check for every consecutive sequence whether it adds up to N or not. If it is then we print that sequence and start looking for the next sequence by incrementing start point. "
},
{
"code": null,
"e": 652,
"s": 648,
"text": "C++"
},
{
"code": null,
"e": 654,
"s": 652,
"text": "C"
},
{
"code": null,
"e": 659,
"s": 654,
"text": "Java"
},
{
"code": null,
"e": 667,
"s": 659,
"text": "Python3"
},
{
"code": null,
"e": 670,
"s": 667,
"text": "C#"
},
{
"code": null,
"e": 674,
"s": 670,
"text": "PHP"
},
{
"code": null,
"e": 685,
"s": 674,
"text": "Javascript"
},
{
"code": "// C++ program to print consecutive sequences// that add to a given value#include<bits/stdc++.h>using namespace std; void findConsecutive(int N){ // Note that we don't ever have to sum // numbers > ceil(N/2) int start = 1, end = (N+1)/2; // Repeat the loop from bottom to half while (start < end) { // Check if there exist any sequence // from bottom to half which adds up to N int sum = 0; for (int i = start; i <= end; i++) { sum = sum + i; // If sum = N, this means consecutive // sequence exists if (sum == N) { // found consecutive numbers! print them for (int j = start; j <= i; j++) cout <<\" \"<< j; cout <<\"\\n\"; break; } // if sum increases N then it can not exist // in the consecutive sequence starting from // bottom if (sum > N) break; } sum = 0; start++; }} // Driver codeint main(void){ int N = 125; findConsecutive(N); return 0;} // This code is contributed by shivanisinghss2110",
"e": 1898,
"s": 685,
"text": null
},
{
"code": "// C++ program to print consecutive sequences// that add to a given value#include<stdio.h> void findConsecutive(int N){ // Note that we don't ever have to sum // numbers > ceil(N/2) int start = 1, end = (N+1)/2; // Repeat the loop from bottom to half while (start < end) { // Check if there exist any sequence // from bottom to half which adds up to N int sum = 0; for (int i = start; i <= end; i++) { sum = sum + i; // If sum = N, this means consecutive // sequence exists if (sum == N) { // found consecutive numbers! print them for (int j = start; j <= i; j++) printf(\"%d \", j); printf(\"\\n\"); break; } // if sum increases N then it can not exist // in the consecutive sequence starting from // bottom if (sum > N) break; } sum = 0; start++; }} // Driver codeint main(void){ int N = 125; findConsecutive(N); return 0;}",
"e": 3013,
"s": 1898,
"text": null
},
{
"code": "// Java program to print// consecutive sequences// that add to a given valueimport java.io.*; class GFG{static void findConsecutive(int N){ // Note that we don't // ever have to sum // numbers > ceil(N/2) int start = 1; int end = (N + 1) / 2; // Repeat the loop // from bottom to half while (start < end) { // Check if there exist // any sequence from // bottom to half which // adds up to N int sum = 0; for (int i = start; i <= end; i++) { sum = sum + i; // If sum = N, this means // consecutive sequence exists if (sum == N) { // found consecutive // numbers! print them for (int j = start; j <= i; j++) System.out.print(j + \" \"); System.out.println(); break; } // if sum increases N then // it can not exist in the // consecutive sequence // starting from bottom if (sum > N) break; } sum = 0; start++; }} // Driver codepublic static void main (String[] args){ int N = 125; findConsecutive(N);}} // This code is contributed by m_kit",
"e": 4314,
"s": 3013,
"text": null
},
{
"code": "# Python3 program to print consecutive# sequences that add to a given valuedef findConsecutive(N): # Note that we don't ever have to # Sum numbers > ceil(N/2) start = 1 end = (N + 1) // 2 # Repeat the loop from bottom to half while (start < end): # Check if there exist any sequence # from bottom to half which adds up to N Sum = 0 for i in range(start, end + 1): Sum = Sum + i # If Sum = N, this means consecutive # sequence exists if (Sum == N): # found consecutive numbers! print them for j in range(start, i + 1): print(j, end = \" \") print() break # if Sum increases N then it can not # exist in the consecutive sequence # starting from bottom if (Sum > N): break Sum = 0 start += 1 # Driver codeN = 125findConsecutive(N) # This code is contributed by Mohit kumar 29",
"e": 5372,
"s": 4314,
"text": null
},
{
"code": "// C# program to print// consecutive sequences// that add to a given valueusing System; class GFG{static void findConsecutive(int N){ // Note that we don't // ever have to sum // numbers > ceil(N/2) int start = 1; int end = (N + 1) / 2; // Repeat the loop // from bottom to half while (start < end) { // Check if there exist // any sequence from // bottom to half which // adds up to N int sum = 0; for (int i = start; i <= end; i++) { sum = sum + i; // If sum = N, this means // consecutive sequence exists if (sum == N) { // found consecutive // numbers! print them for (int j = start; j <= i; j++) Console.Write(j + \" \"); Console.WriteLine(); break; } // if sum increases N then // it can not exist in the // consecutive sequence // starting from bottom if (sum > N) break; } sum = 0; start++; }} // Driver codestatic public void Main (){ int N = 125; findConsecutive(N);}} // This code is contributed by ajit",
"e": 6649,
"s": 5372,
"text": null
},
{
"code": "<?php// PHP program to print consecutive// sequences that add to a given value function findConsecutive($N){ // Note that we don't ever have // to sum numbers > ceil(N/2) $start = 1; $end = ($N + 1) / 2; // Repeat the loop from // bottom to half while ($start < $end) { // Check if there exist any // sequence from bottom to // half which adds up to N $sum = 0; for ($i = $start; $i <= $end; $i++) { $sum = $sum + $i; // If sum = N, this means // consecutive sequence exists if ($sum == $N) { // found consecutive // numbers! print them for ($j = $start; $j <= $i; $j++) echo $j ,\" \"; echo \"\\n\"; break; } // if sum increases N then it // can not exist in the consecutive // sequence starting from bottom if ($sum > $N) break; } $sum = 0; $start++; }} // Driver code$N = 125;findConsecutive($N); // This code is contributed by ajit?>",
"e": 7795,
"s": 6649,
"text": null
},
{
"code": "<script> // Javascript program to print consecutive sequences// that add to a given value function findConsecutive( N){ // Note that we don't ever have to sum // numbers > ceil(N/2) let start = 1, end = Math.trunc((N+1)/2); // Repeat the loop from bottom to half while (start < end) { // Check if there exist any sequence // from bottom to half which adds up to N let sum = 0; for (let i = start; i <= end; i++) { sum = sum + i; // If sum = N, this means consecutive // sequence exists if (sum == N) { // found consecutive numbers! print them for (let j = start; j <= i; j++) document.write(j+\" \"); document.write(\"<br/>\"); break; } // if sum increases N then it can not exist // in the consecutive sequence starting from // bottom if (sum > N) break; } sum = 0; start++; }} // Driver program let N = 125; findConsecutive(N); </script>",
"e": 8942,
"s": 7795,
"text": null
},
{
"code": null,
"e": 8952,
"s": 8942,
"text": "Output : "
},
{
"code": null,
"e": 9004,
"s": 8952,
"text": "8 9 10 11 12 13 14 15 16 17 \n23 24 25 26 27 \n62 63 "
},
{
"code": null,
"e": 9370,
"s": 9004,
"text": "Optimized Solution: In the above solution, we keep recalculating sums from start to end, which results in O(N^2) worst-case time complexity. This can be avoided by using a precomputed array of sums, or better yet – just keeping track of the sum you have so far and adjusting it depending on how it compares to the desired sum.Time complexity of below code is O(N). "
},
{
"code": null,
"e": 9374,
"s": 9370,
"text": "C++"
},
{
"code": null,
"e": 9376,
"s": 9374,
"text": "C"
},
{
"code": null,
"e": 9381,
"s": 9376,
"text": "Java"
},
{
"code": null,
"e": 9389,
"s": 9381,
"text": "Python3"
},
{
"code": null,
"e": 9392,
"s": 9389,
"text": "C#"
},
{
"code": null,
"e": 9396,
"s": 9392,
"text": "PHP"
},
{
"code": null,
"e": 9407,
"s": 9396,
"text": "Javascript"
},
{
"code": "// Optimized C++ program to find sequences of all consecutive// numbers with sum equal to N#include <bits/stdc++.h>using namespace std; void printSums(int N){ int start = 1, end = 1; int sum = 1; while (start <= N/2) { if (sum < N) { end += 1; sum += end; } else if (sum > N) { sum -= start; start += 1; } else if (sum == N) { for (int i = start; i <= end; ++i) cout <<\" \"<< i; cout <<\"\\n\"; sum -= start; start += 1; } }} // Driver Codeint main(){ printSums(125); return 0;} // this code is contributed by shivanisinghss2110",
"e": 10121,
"s": 9407,
"text": null
},
{
"code": "// Optimized C program to find sequences of all consecutive// numbers with sum equal to N#include <stdio.h> void printSums(int N){ int start = 1, end = 1; int sum = 1; while (start <= N/2) { if (sum < N) { end += 1; sum += end; } else if (sum > N) { sum -= start; start += 1; } else if (sum == N) { for (int i = start; i <= end; ++i) printf(\"%d \", i); printf(\"\\n\"); sum -= start; start += 1; } }} // Driver Codeint main(){ printSums(125); return 0;}",
"e": 10760,
"s": 10121,
"text": null
},
{
"code": "// Optimized Java program to find// sequences of all consecutive// numbers with sum equal to Nimport java.io.*; class GFG { static void printSums(int N) { int start = 1, end = 1; int sum = 1; while (start <= N/2) { if (sum < N) { end += 1; sum += end; } else if (sum > N) { sum -= start; start += 1; } else if (sum == N) { for (int i = start; i <= end; ++i) System.out.print(i + \" \"); System.out.println(); sum -= start; start += 1; } } } // Driver Code public static void main (String[] args) { printSums(125); }} // This code is contributed by anuj_67.",
"e": 11717,
"s": 10760,
"text": null
},
{
"code": "# Optimized Python3 program to find sequences of all consecutive# numbers with sum equal to Ndef findConsecutive(N): start = 1 end = 1 sum = 1 while start <= N/2: if sum < N: end += 1 sum += end if sum > N: sum -= start start += 1 if sum == N: for i in range(start, end + 1): print(i, end=' ') print( ) sum -= start start += 1 # Driver codeN = 125findConsecutive(N) # This code is contributed by Sanskriti Agrawal",
"e": 12317,
"s": 11717,
"text": null
},
{
"code": "// Optimized C# program to find// sequences of all consecutive// numbers with sum equal to Nusing System; class GFG { static void printSums(int N) { int start = 1, end = 1; int sum = 1; while (start <= N/2) { if (sum < N) { end += 1; sum += end; } else if (sum > N) { sum -= start; start += 1; } else if (sum == N) { for (int i = start; i <= end; ++i) Console.Write(i + \" \"); Console.WriteLine(); sum -= start; start += 1; } } } // Driver Code public static void Main () { printSums(125); }} // This code is contributed by anuj_67.",
"e": 13249,
"s": 12317,
"text": null
},
{
"code": "<?php// Optimized PHP program to find// sequences of all consecutive// numbers with sum equal to N function printSums($N){ $start = 1; $end = 1; $sum = 1; while ($start <= $N / 2) { if ($sum < $N) { $end += 1; $sum += $end; } else if ($sum > $N) { $sum -= $start; $start += 1; } else if ($sum == $N) { for ($i = $start; $i <= $end; ++$i) echo $i,\" \"; echo \"\\n\"; $sum -= $start; $start += 1; } }} // Driver Code printSums(125); // This code is contributed by jit_t?>",
"e": 13904,
"s": 13249,
"text": null
},
{
"code": "<script> // Javascript program to find// sequences of all consecutive// numbers with sum equal to Nfunction printSums(N){ let start = 1, end = 1; let sum = 1; while (start <= N / 2) { if (sum < N) { end += 1; sum += end; } else if (sum > N) { sum -= start; start += 1; } else if (sum == N) { for(let i = start; i <= end; ++i) document.write(i + \" \"); document.write(\"<br/>\"); sum -= start; start += 1; } }} // Driver code printSums(125); // This code is contributed by splevel62 </script>",
"e": 14604,
"s": 13904,
"text": null
},
{
"code": null,
"e": 14614,
"s": 14604,
"text": "Output : "
},
{
"code": null,
"e": 14666,
"s": 14614,
"text": "8 9 10 11 12 13 14 15 16 17 \n23 24 25 26 27 \n62 63 "
},
{
"code": null,
"e": 15168,
"s": 14666,
"text": "Reference : https://www.careercup.com/page?pid=microsoft-interview-questions&n=2This article is contributed by Niteesh Kumar. 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": 15173,
"s": 15168,
"text": "vt_m"
},
{
"code": null,
"e": 15179,
"s": 15173,
"text": "jit_t"
},
{
"code": null,
"e": 15194,
"s": 15179,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 15202,
"s": 15194,
"text": "Stark17"
},
{
"code": null,
"e": 15212,
"s": 15202,
"text": "splevel62"
},
{
"code": null,
"e": 15226,
"s": 15212,
"text": "jana_sayantan"
},
{
"code": null,
"e": 15245,
"s": 15226,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 15258,
"s": 15245,
"text": "simmytarika5"
},
{
"code": null,
"e": 15273,
"s": 15258,
"text": "varshagumber28"
},
{
"code": null,
"e": 15287,
"s": 15273,
"text": "Binary Search"
},
{
"code": null,
"e": 15297,
"s": 15287,
"text": "Searching"
},
{
"code": null,
"e": 15307,
"s": 15297,
"text": "Searching"
},
{
"code": null,
"e": 15321,
"s": 15307,
"text": "Binary Search"
},
{
"code": null,
"e": 15419,
"s": 15321,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 15466,
"s": 15419,
"text": "Search, insert and delete in an unsorted array"
},
{
"code": null,
"e": 15513,
"s": 15466,
"text": "Median of two sorted arrays of different sizes"
},
{
"code": null,
"e": 15557,
"s": 15513,
"text": "k largest(or smallest) elements in an array"
},
{
"code": null,
"e": 15580,
"s": 15557,
"text": "Two Pointers Technique"
},
{
"code": null,
"e": 15624,
"s": 15580,
"text": "Search, insert and delete in a sorted array"
},
{
"code": null,
"e": 15667,
"s": 15624,
"text": "Find the index of an array element in Java"
},
{
"code": null,
"e": 15687,
"s": 15667,
"text": "Find a peak element"
},
{
"code": null,
"e": 15721,
"s": 15687,
"text": "Most frequent element in an array"
}
] |
Method Overriding in Scala | 25 Apr, 2019
Method Overriding in Scala is identical to the method overriding in Java but in Scala, the overriding features are further elaborated as here, both methods as well as var or val can be overridden. If a subclass has the method name identical to the method name defined in the parent class then it is known to be Method Overriding i.e, the sub-classes which are inherited by the declared super class, overrides the method defined in the super class utilizing the override keyword.
Lets, see the flow chart of the method overriding in order to visualize it explicitly.Here, in the diagram stated above School is the super-class which has a method defined in it which is named as NumberOfStudents() and this method is overridden by the sub-classes i.e, class 1, class 2, class 3. so, all the sub-classes has the same named method as defined in the super-class.
when a subclass wishes to impart a particular implementation for the method defined in the parent class then that subclass overrides the defined method from the parent class. When we wish to reconstruct the method defined in the super class then we can apply method overriding.Let’s see an example which is related to the diagram mentioned above of the method overriding.
Example :
// Scala program of method overriding // Creating a super classclass School{ // Method defined def NumberOfStudents()= { 0 // Utilized for returning an Integer } } // Creating a subclass class class_1 extends School{ // Using Override keyword override def NumberOfStudents()= { 30 } } // Creating a subclass class class_2 extends School{ // Using override keyword override def NumberOfStudents()= { 32 } } // Creating a subclassclass class_3 extends School{ // Using override keyword override def NumberOfStudents()= { 29 } } // Creating object object GfG{ // Main method def main(args:Array[String]) { // Creating instances of all // the sub-classes var x=new class_1() var y=new class_2() var z=new class_3() // Displays number of students in class_1 println("Number of students in class 1 : " + x.NumberOfStudents()) // Displays number of students in class_2 println("Number of students in class 2 : " + y.NumberOfStudents()) // Displays number of students in class_3 println("Number of students in class 3 : " + z.NumberOfStudents()) } }
Number of students in class 1 : 30
Number of students in class 2 : 32
Number of students in class 3 : 29
In the above example, we have a class named School which defines a method NumberOfStudents() and we have three classes i.e, class_1, class_2 and class_3 which inherit from the super-class School and these sub-classes overrides the method defined in the super-class.
Example :
// Scala program of method overriding // Creating a super classclass Shapes{ // Method defined with parameters def Area(l:Double, b:Double, r:Double)= { 0.0 // Utilized for returning double } } // Creating a subclass class Rectangle extends Shapes{ // Overriding method to find // area of the rectangle override def Area(l:Double, b:Double, r:Double)= { (l * b) } } // Creating a subclass class Circle extends Shapes{ // Overriding method to find // area of the circle override def Area(l:Double, b:Double, r:Double)= { ((3.14)* r * r) } } // Creating object object GfG{ // Main method def main(args:Array[String]) { // Creating instances of all // the sub-classes var rectangle = new Rectangle() var circle = new Circle() // Displays area of the rectangle println(rectangle.Area(3, 11, 4)) // Displays area of the circle println(circle.Area(1, 7, 10)) } }
33.0
314.0
In the above example, Area is a method of the super-class which is to be overridden by the methods defined in the sub-classes. Here, we are finding the area but for different shapes using the same method name i.e, Area thus, we can say that this method overriding can be applied for same kind of operations but for different categories and it is worth noting that the methods must have same data types and same number of parameters as defined in the super class otherwise the compiler will throw an error. Though the order of the parameters in the method defined can be altered in the sub-classes when the method is overridden.
There are a few restrictions that we need to follow for method overriding, these are as follows:
For method overriding, one of the crucial rule is that the class which is overriding needs to utilize the modifier override or override annotation.
Auxiliary constructors are not able to call the super-class constructors immediately. They can hardly call the primary constructors which in reversal will call the super-class constructor.
In Method Overriding, we won’t be able to override a var with a def or val, otherwise it throws an error.
Here, we won’t be able to override a val in the super-class by a var or def in the subclass, and if the var in the super-class is abstract then we can override it in the subclass.
If a field is stated var then it can override the def which is defined in the super-class. The var can only override a getter or setter combination in the super-class.
Note:
Auxiliary Constructors are defined like methods utilizing def and this keywords, where this is the name of the constructor.Primary Constructors begins from the beginning of the class definition and stretches the whole body of the class.
Auxiliary Constructors are defined like methods utilizing def and this keywords, where this is the name of the constructor.
Primary Constructors begins from the beginning of the class definition and stretches the whole body of the class.
Lets see some examples now.
Example :
// Scala program of method // Overriding // Creating a classclass Animal{ // Defining a method def number() { println("We have two animals") } } // Extending the class Animalclass Dog extends Animal{ // using override keyword override def number() { // Displays output println("We have two dogs") } } // Creating object object GfG{ // Main method def main(args:Array[String]) { // Creating object of the subclass // Dog var x = new Dog() // Calling overridden method x.number() } }
We have two dogs
Here, we have overridden the method utilizing the keyword override. In the above example, the super class Animal has a method named number which is overridden in the subclass Dog. So, the overridden method can be called by creating the object of the subclass.
Example :
// Scala program of method // overriding // Creating super-classclass Students(var rank:Int, var name:String){ // overriding a method 'toString()' override def toString():String = { " The rank of "+name+" is : "+rank }} // Creating a subclass of Studentsclass newStudents(rank:Int, name:String) extends Students(rank, name){} // Inheriting main method of // the trait 'App' object GfG extends App{ // Creating object of the super-class val students = new Students(1, "Geeta Sharma") // Displays output println(students) // Creating object of the subclass val newstudents = new newStudents(3, "Priti Singh") // Displays output println(newstudents) }
The rank of Geeta Sharma is : 1
The rank of Priti Singh is : 3
Here, the constructor of the super-class i.e, Students is called from the primary constructor of the subclass i.e, newStudents so, the super-class constructor is called utilizing the keyword extends.Note: The AnyRef class has a toString() method defined in it and as we know that every class is subclass of AnyRef class so, the method toString() is overridden using the keyword override.
In Scala, method overloading supplies us with a property which permits us to define methods of identical name but they have different parameters or data types whereas, method overriding permits us to redefine method body of the super class in the subclass of same name and same parameters or data types in order to alter the performance of the method.
In Scala, method overriding uses override modifier in order to override a method defined in the super class whereas, method overloading does not requires any keyword or modifier, we just need to change, the order of the parameters used or the number of the parameters of the method or the data types of the parameters for method overloading.
In order to redefine a single method in different ways, we can do method overriding which helps us to do different operations with same method name. Like, in the diagram shown above has a super-class School which has a method named NumberOfStudents() which is overridden by the sub-classes to perform different actions.
Picked
Scala
Scala-OOPS
Scala
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
For Loop in Scala
Scala | map() method
Scala | flatMap Method
String concatenation in Scala
Scala | reduce() Function
Type Casting in Scala
Scala List filter() method with example
Scala Tutorial – Learn Scala with Step By Step Guide
Scala String substring() method with example
How to Install Scala with VSCode? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Apr, 2019"
},
{
"code": null,
"e": 507,
"s": 28,
"text": "Method Overriding in Scala is identical to the method overriding in Java but in Scala, the overriding features are further elaborated as here, both methods as well as var or val can be overridden. If a subclass has the method name identical to the method name defined in the parent class then it is known to be Method Overriding i.e, the sub-classes which are inherited by the declared super class, overrides the method defined in the super class utilizing the override keyword."
},
{
"code": null,
"e": 885,
"s": 507,
"text": "Lets, see the flow chart of the method overriding in order to visualize it explicitly.Here, in the diagram stated above School is the super-class which has a method defined in it which is named as NumberOfStudents() and this method is overridden by the sub-classes i.e, class 1, class 2, class 3. so, all the sub-classes has the same named method as defined in the super-class."
},
{
"code": null,
"e": 1257,
"s": 885,
"text": "when a subclass wishes to impart a particular implementation for the method defined in the parent class then that subclass overrides the defined method from the parent class. When we wish to reconstruct the method defined in the super class then we can apply method overriding.Let’s see an example which is related to the diagram mentioned above of the method overriding."
},
{
"code": null,
"e": 1267,
"s": 1257,
"text": "Example :"
},
{
"code": "// Scala program of method overriding // Creating a super classclass School{ // Method defined def NumberOfStudents()= { 0 // Utilized for returning an Integer } } // Creating a subclass class class_1 extends School{ // Using Override keyword override def NumberOfStudents()= { 30 } } // Creating a subclass class class_2 extends School{ // Using override keyword override def NumberOfStudents()= { 32 } } // Creating a subclassclass class_3 extends School{ // Using override keyword override def NumberOfStudents()= { 29 } } // Creating object object GfG{ // Main method def main(args:Array[String]) { // Creating instances of all // the sub-classes var x=new class_1() var y=new class_2() var z=new class_3() // Displays number of students in class_1 println(\"Number of students in class 1 : \" + x.NumberOfStudents()) // Displays number of students in class_2 println(\"Number of students in class 2 : \" + y.NumberOfStudents()) // Displays number of students in class_3 println(\"Number of students in class 3 : \" + z.NumberOfStudents()) } } ",
"e": 2661,
"s": 1267,
"text": null
},
{
"code": null,
"e": 2767,
"s": 2661,
"text": "Number of students in class 1 : 30\nNumber of students in class 2 : 32\nNumber of students in class 3 : 29\n"
},
{
"code": null,
"e": 3033,
"s": 2767,
"text": "In the above example, we have a class named School which defines a method NumberOfStudents() and we have three classes i.e, class_1, class_2 and class_3 which inherit from the super-class School and these sub-classes overrides the method defined in the super-class."
},
{
"code": null,
"e": 3043,
"s": 3033,
"text": "Example :"
},
{
"code": "// Scala program of method overriding // Creating a super classclass Shapes{ // Method defined with parameters def Area(l:Double, b:Double, r:Double)= { 0.0 // Utilized for returning double } } // Creating a subclass class Rectangle extends Shapes{ // Overriding method to find // area of the rectangle override def Area(l:Double, b:Double, r:Double)= { (l * b) } } // Creating a subclass class Circle extends Shapes{ // Overriding method to find // area of the circle override def Area(l:Double, b:Double, r:Double)= { ((3.14)* r * r) } } // Creating object object GfG{ // Main method def main(args:Array[String]) { // Creating instances of all // the sub-classes var rectangle = new Rectangle() var circle = new Circle() // Displays area of the rectangle println(rectangle.Area(3, 11, 4)) // Displays area of the circle println(circle.Area(1, 7, 10)) } } ",
"e": 4125,
"s": 3043,
"text": null
},
{
"code": null,
"e": 4137,
"s": 4125,
"text": "33.0\n314.0\n"
},
{
"code": null,
"e": 4765,
"s": 4137,
"text": "In the above example, Area is a method of the super-class which is to be overridden by the methods defined in the sub-classes. Here, we are finding the area but for different shapes using the same method name i.e, Area thus, we can say that this method overriding can be applied for same kind of operations but for different categories and it is worth noting that the methods must have same data types and same number of parameters as defined in the super class otherwise the compiler will throw an error. Though the order of the parameters in the method defined can be altered in the sub-classes when the method is overridden."
},
{
"code": null,
"e": 4862,
"s": 4765,
"text": "There are a few restrictions that we need to follow for method overriding, these are as follows:"
},
{
"code": null,
"e": 5010,
"s": 4862,
"text": "For method overriding, one of the crucial rule is that the class which is overriding needs to utilize the modifier override or override annotation."
},
{
"code": null,
"e": 5199,
"s": 5010,
"text": "Auxiliary constructors are not able to call the super-class constructors immediately. They can hardly call the primary constructors which in reversal will call the super-class constructor."
},
{
"code": null,
"e": 5305,
"s": 5199,
"text": "In Method Overriding, we won’t be able to override a var with a def or val, otherwise it throws an error."
},
{
"code": null,
"e": 5485,
"s": 5305,
"text": "Here, we won’t be able to override a val in the super-class by a var or def in the subclass, and if the var in the super-class is abstract then we can override it in the subclass."
},
{
"code": null,
"e": 5653,
"s": 5485,
"text": "If a field is stated var then it can override the def which is defined in the super-class. The var can only override a getter or setter combination in the super-class."
},
{
"code": null,
"e": 5659,
"s": 5653,
"text": "Note:"
},
{
"code": null,
"e": 5896,
"s": 5659,
"text": "Auxiliary Constructors are defined like methods utilizing def and this keywords, where this is the name of the constructor.Primary Constructors begins from the beginning of the class definition and stretches the whole body of the class."
},
{
"code": null,
"e": 6020,
"s": 5896,
"text": "Auxiliary Constructors are defined like methods utilizing def and this keywords, where this is the name of the constructor."
},
{
"code": null,
"e": 6134,
"s": 6020,
"text": "Primary Constructors begins from the beginning of the class definition and stretches the whole body of the class."
},
{
"code": null,
"e": 6162,
"s": 6134,
"text": "Lets see some examples now."
},
{
"code": null,
"e": 6172,
"s": 6162,
"text": "Example :"
},
{
"code": "// Scala program of method // Overriding // Creating a classclass Animal{ // Defining a method def number() { println(\"We have two animals\") } } // Extending the class Animalclass Dog extends Animal{ // using override keyword override def number() { // Displays output println(\"We have two dogs\") } } // Creating object object GfG{ // Main method def main(args:Array[String]) { // Creating object of the subclass // Dog var x = new Dog() // Calling overridden method x.number() } } ",
"e": 6821,
"s": 6172,
"text": null
},
{
"code": null,
"e": 6839,
"s": 6821,
"text": "We have two dogs\n"
},
{
"code": null,
"e": 7099,
"s": 6839,
"text": "Here, we have overridden the method utilizing the keyword override. In the above example, the super class Animal has a method named number which is overridden in the subclass Dog. So, the overridden method can be called by creating the object of the subclass."
},
{
"code": null,
"e": 7109,
"s": 7099,
"text": "Example :"
},
{
"code": "// Scala program of method // overriding // Creating super-classclass Students(var rank:Int, var name:String){ // overriding a method 'toString()' override def toString():String = { \" The rank of \"+name+\" is : \"+rank }} // Creating a subclass of Studentsclass newStudents(rank:Int, name:String) extends Students(rank, name){} // Inheriting main method of // the trait 'App' object GfG extends App{ // Creating object of the super-class val students = new Students(1, \"Geeta Sharma\") // Displays output println(students) // Creating object of the subclass val newstudents = new newStudents(3, \"Priti Singh\") // Displays output println(newstudents) }",
"e": 7842,
"s": 7109,
"text": null
},
{
"code": null,
"e": 7906,
"s": 7842,
"text": "The rank of Geeta Sharma is : 1\nThe rank of Priti Singh is : 3\n"
},
{
"code": null,
"e": 8294,
"s": 7906,
"text": "Here, the constructor of the super-class i.e, Students is called from the primary constructor of the subclass i.e, newStudents so, the super-class constructor is called utilizing the keyword extends.Note: The AnyRef class has a toString() method defined in it and as we know that every class is subclass of AnyRef class so, the method toString() is overridden using the keyword override."
},
{
"code": null,
"e": 8646,
"s": 8294,
"text": "In Scala, method overloading supplies us with a property which permits us to define methods of identical name but they have different parameters or data types whereas, method overriding permits us to redefine method body of the super class in the subclass of same name and same parameters or data types in order to alter the performance of the method."
},
{
"code": null,
"e": 8988,
"s": 8646,
"text": "In Scala, method overriding uses override modifier in order to override a method defined in the super class whereas, method overloading does not requires any keyword or modifier, we just need to change, the order of the parameters used or the number of the parameters of the method or the data types of the parameters for method overloading."
},
{
"code": null,
"e": 9308,
"s": 8988,
"text": "In order to redefine a single method in different ways, we can do method overriding which helps us to do different operations with same method name. Like, in the diagram shown above has a super-class School which has a method named NumberOfStudents() which is overridden by the sub-classes to perform different actions."
},
{
"code": null,
"e": 9315,
"s": 9308,
"text": "Picked"
},
{
"code": null,
"e": 9321,
"s": 9315,
"text": "Scala"
},
{
"code": null,
"e": 9332,
"s": 9321,
"text": "Scala-OOPS"
},
{
"code": null,
"e": 9338,
"s": 9332,
"text": "Scala"
},
{
"code": null,
"e": 9357,
"s": 9338,
"text": "Technical Scripter"
},
{
"code": null,
"e": 9455,
"s": 9357,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9473,
"s": 9455,
"text": "For Loop in Scala"
},
{
"code": null,
"e": 9494,
"s": 9473,
"text": "Scala | map() method"
},
{
"code": null,
"e": 9517,
"s": 9494,
"text": "Scala | flatMap Method"
},
{
"code": null,
"e": 9547,
"s": 9517,
"text": "String concatenation in Scala"
},
{
"code": null,
"e": 9573,
"s": 9547,
"text": "Scala | reduce() Function"
},
{
"code": null,
"e": 9595,
"s": 9573,
"text": "Type Casting in Scala"
},
{
"code": null,
"e": 9635,
"s": 9595,
"text": "Scala List filter() method with example"
},
{
"code": null,
"e": 9688,
"s": 9635,
"text": "Scala Tutorial – Learn Scala with Step By Step Guide"
},
{
"code": null,
"e": 9733,
"s": 9688,
"text": "Scala String substring() method with example"
}
] |
How to customize links for pagination in Bootstrap ? | 24 Sep, 2021
In many websites, we notice that when we search for something then all the related content is shown but if the number of content is large then it will make the website longer.
To solve this, there is pagination in the webpage i.e, the contents are divided into many pages and on clicking the user can navigate through the related contents.
Note: Pagination is used to manage a series of related content existing across multiple pages.
Approach: The pagination class is used to display the pagination on the website. Use a wrapping <nav> element to identify it as a navigation section to screen readers. Use the unordered list to create the list of pages with links.
Below is the procedure to implement simple pagination with customizing in Bootstrap.
Step 1: Include Bootstrap and jQuery CDN into the <head> tag before all other stylesheets to load our CSS.
<link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css”><script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js”></script><script src=”https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js”></script><script src=”https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js”></script>
Step 2:
Add pagination class with <ul> tag for unordered list. Add the list items with class name page-items.
In addition, as pages likely have more than one such navigation section, So provide a descriptive aria-label for the <nav> to reflect its purpose.
To customize the links for each page, just remove “#” and add the desired link.
For aligning it to center, use class justify-content-center in <ul>.
HTML
<nav aria-label="Page navigation example"> <ul class="pagination justify-content-center"> <li class="page-item"> <a class="page-link" href="#">Previous</a> </li> <li class="page-item"> <a class="page-link" href="#">1</a> </li> <li class="page-item"> <a class="page-link" href="#">2</a> </li> <li class="page-item"> <a class="page-link" href="#">3</a> </li> <li class="page-item"> <a class="page-link" href="#">Next</a> </li> </ul></nav>
Add pagination to each of the pages to make sure the link to the previous page is one less than the current page and the user can move around the pages easily.
Example:
HTML
<!DOCTYPE html><html> <head> <meta charset="utf-8" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"> </script></head> <body style="text-align: center;"> <h2>GeeksforGeeks</h2><br><br> <h3>Contents of Page 3</h3> <br><br><br><br> <nav aria-label="Page navigation example"> <ul class="pagination justify-content-center"> <li class="page-item"> <a class="page-link" href="Page2.html">Previous</a> </li> <li class="page-item"> <a class="page-link" href="Page1.html">1</a> </li> <li class="page-item"> <a class="page-link" href="Page2.html">2</a> </li> <li class="page-item"> <a class="page-link" href="Page3.html">3</a> </li> </ul> </nav></body> </html>
Page1.html: If the user is on page 1, “next page” contains a link to page 2. The following are the codes for the contents “Page1.html”, “Page2.html”, and “Page3.html”
HTML
<!DOCTYPE html><html> <head> <meta charset="utf-8" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"> </script></head> <body style="text-align: center;"> <h2>GeeksForGeeks</h2><br><br> <h3>Contents of Page 1</h3> <br><br><br><br> <nav aria-label="Page navigation example"> <ul class="pagination justify-content-center"> <li class="page-item"> <a class="page-link" href="Page1.html">1</a> </li> <li class="page-item"> <a class="page-link" href="Page2.html">2</a> </li> <li class="page-item"> <a class="page-link" href="Page3.html">3</a> </li> <li class="page-item"> <a class="page-link" href="Page2.html">Next</a> </li> </ul> </nav></body> </html>
Page2.html: If the user is on page 2, the “Previous” page contains a link to page 1, and the “next page” contains a link to page 3.
HTML
<!DOCTYPE html><html> <head> <meta charset="utf-8" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"> </script></head> <body style="text-align:center;"> <h2>GeeksforGeeks</h2><br><br> <h3>Contents of Page 2</h3> <br><br><br><br> <nav aria-label="Page navigation example"> <ul class="pagination justify-content-center"> <li class="page-item"> <a class="page-link" href="Page1.html"> Previous </a> </li> <li class="page-item"> <a class="page-link" href="Page1.html">1</a> </li> <li class="page-item"> <a class="page-link" href="Page2.html">2</a> </li> <li class="page-item"> <a class="page-link" href="Page3.html">3</a> </li> <li class="page-item"> <a class="page-link" href="Page3.html"> Next </a> </li> </ul> </nav></body> </html>
Page3.html: If the user is on page 3, the “Previous” page contains a link to page 2.
HTML
<!DOCTYPE html><html> <head> <meta charset="utf-8" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"> </script></head> <body style="text-align:center;"> <h2>GeeksforGeeks</h2><br><br> <h3>Contents of Page 3</h3> <br><br><br><br> <nav aria-label="Page navigation example"> <ul class="pagination justify-content-center"> <li class="page-item"> <a class="page-link" href="Page2.html"> Previous </a> </li> <li class="page-item"> <a class="page-link" href="Page1.html">1</a> </li> <li class="page-item"> <a class="page-link" href="Page2.html">2</a> </li> <li class="page-item"> <a class="page-link" href="Page3.html">3</a> </li> </ul> </nav></body> </html>
Output:
Blogathon-2021
Bootstrap-Questions
HTML-Questions
Picked
Blogathon
Bootstrap
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n24 Sep, 2021"
},
{
"code": null,
"e": 229,
"s": 52,
"text": "In many websites, we notice that when we search for something then all the related content is shown but if the number of content is large then it will make the website longer. "
},
{
"code": null,
"e": 394,
"s": 229,
"text": "To solve this, there is pagination in the webpage i.e, the contents are divided into many pages and on clicking the user can navigate through the related contents. "
},
{
"code": null,
"e": 490,
"s": 394,
"text": "Note: Pagination is used to manage a series of related content existing across multiple pages. "
},
{
"code": null,
"e": 721,
"s": 490,
"text": "Approach: The pagination class is used to display the pagination on the website. Use a wrapping <nav> element to identify it as a navigation section to screen readers. Use the unordered list to create the list of pages with links."
},
{
"code": null,
"e": 806,
"s": 721,
"text": "Below is the procedure to implement simple pagination with customizing in Bootstrap."
},
{
"code": null,
"e": 913,
"s": 806,
"text": "Step 1: Include Bootstrap and jQuery CDN into the <head> tag before all other stylesheets to load our CSS."
},
{
"code": null,
"e": 1290,
"s": 913,
"text": "<link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css”><script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js”></script><script src=”https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js”></script><script src=”https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js”></script>"
},
{
"code": null,
"e": 1299,
"s": 1290,
"text": "Step 2: "
},
{
"code": null,
"e": 1401,
"s": 1299,
"text": "Add pagination class with <ul> tag for unordered list. Add the list items with class name page-items."
},
{
"code": null,
"e": 1548,
"s": 1401,
"text": "In addition, as pages likely have more than one such navigation section, So provide a descriptive aria-label for the <nav> to reflect its purpose."
},
{
"code": null,
"e": 1628,
"s": 1548,
"text": "To customize the links for each page, just remove “#” and add the desired link."
},
{
"code": null,
"e": 1697,
"s": 1628,
"text": "For aligning it to center, use class justify-content-center in <ul>."
},
{
"code": null,
"e": 1702,
"s": 1697,
"text": "HTML"
},
{
"code": "<nav aria-label=\"Page navigation example\"> <ul class=\"pagination justify-content-center\"> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">Previous</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">1</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">2</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">3</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">Next</a> </li> </ul></nav>",
"e": 2310,
"s": 1702,
"text": null
},
{
"code": null,
"e": 2470,
"s": 2310,
"text": "Add pagination to each of the pages to make sure the link to the previous page is one less than the current page and the user can move around the pages easily."
},
{
"code": null,
"e": 2479,
"s": 2470,
"text": "Example:"
},
{
"code": null,
"e": 2484,
"s": 2479,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <meta charset=\"utf-8\" /> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" /> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js\"> </script></head> <body style=\"text-align: center;\"> <h2>GeeksforGeeks</h2><br><br> <h3>Contents of Page 3</h3> <br><br><br><br> <nav aria-label=\"Page navigation example\"> <ul class=\"pagination justify-content-center\"> <li class=\"page-item\"> <a class=\"page-link\" href=\"Page2.html\">Previous</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"Page1.html\">1</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"Page2.html\">2</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"Page3.html\">3</a> </li> </ul> </nav></body> </html>",
"e": 3561,
"s": 2484,
"text": null
},
{
"code": null,
"e": 3731,
"s": 3563,
"text": "Page1.html: If the user is on page 1, “next page” contains a link to page 2. The following are the codes for the contents “Page1.html”, “Page2.html”, and “Page3.html”"
},
{
"code": null,
"e": 3736,
"s": 3731,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <meta charset=\"utf-8\" /> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" /> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js\"> </script></head> <body style=\"text-align: center;\"> <h2>GeeksForGeeks</h2><br><br> <h3>Contents of Page 1</h3> <br><br><br><br> <nav aria-label=\"Page navigation example\"> <ul class=\"pagination justify-content-center\"> <li class=\"page-item\"> <a class=\"page-link\" href=\"Page1.html\">1</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"Page2.html\">2</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"Page3.html\">3</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"Page2.html\">Next</a> </li> </ul> </nav></body> </html>",
"e": 4809,
"s": 3736,
"text": null
},
{
"code": null,
"e": 4942,
"s": 4809,
"text": "Page2.html: If the user is on page 2, the “Previous” page contains a link to page 1, and the “next page” contains a link to page 3."
},
{
"code": null,
"e": 4947,
"s": 4942,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <meta charset=\"utf-8\" /> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" /> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js\"> </script></head> <body style=\"text-align:center;\"> <h2>GeeksforGeeks</h2><br><br> <h3>Contents of Page 2</h3> <br><br><br><br> <nav aria-label=\"Page navigation example\"> <ul class=\"pagination justify-content-center\"> <li class=\"page-item\"> <a class=\"page-link\" href=\"Page1.html\"> Previous </a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"Page1.html\">1</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"Page2.html\">2</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"Page3.html\">3</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"Page3.html\"> Next </a> </li> </ul> </nav></body> </html>",
"e": 6209,
"s": 4947,
"text": null
},
{
"code": null,
"e": 6294,
"s": 6209,
"text": "Page3.html: If the user is on page 3, the “Previous” page contains a link to page 2."
},
{
"code": null,
"e": 6299,
"s": 6294,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <meta charset=\"utf-8\" /> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" /> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js\"> </script></head> <body style=\"text-align:center;\"> <h2>GeeksforGeeks</h2><br><br> <h3>Contents of Page 3</h3> <br><br><br><br> <nav aria-label=\"Page navigation example\"> <ul class=\"pagination justify-content-center\"> <li class=\"page-item\"> <a class=\"page-link\" href=\"Page2.html\"> Previous </a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"Page1.html\">1</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"Page2.html\">2</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"Page3.html\">3</a> </li> </ul> </nav></body> </html>",
"e": 7411,
"s": 6299,
"text": null
},
{
"code": null,
"e": 7419,
"s": 7411,
"text": "Output:"
},
{
"code": null,
"e": 7434,
"s": 7419,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 7454,
"s": 7434,
"text": "Bootstrap-Questions"
},
{
"code": null,
"e": 7469,
"s": 7454,
"text": "HTML-Questions"
},
{
"code": null,
"e": 7476,
"s": 7469,
"text": "Picked"
},
{
"code": null,
"e": 7486,
"s": 7476,
"text": "Blogathon"
},
{
"code": null,
"e": 7496,
"s": 7486,
"text": "Bootstrap"
},
{
"code": null,
"e": 7501,
"s": 7496,
"text": "HTML"
},
{
"code": null,
"e": 7518,
"s": 7501,
"text": "Web Technologies"
},
{
"code": null,
"e": 7523,
"s": 7518,
"text": "HTML"
}
] |
C function argument and return values | 30 May, 2022
Prerequisite: Functions in C/C++ A function in C can be called either with arguments or without arguments. These functions may or may not return values to the calling functions. All C functions can be called either with arguments or without arguments in a C program. Also, they may or may not return any values. Hence the function prototype of a function in C is as below: |
Function with no argument and no return value: When a function has no arguments, it does not receive any data from the calling function. Similarly, when it does not return a value, the calling function does not receive any data from the called function. Syntax :
Function with no argument and no return value: When a function has no arguments, it does not receive any data from the calling function. Similarly, when it does not return a value, the calling function does not receive any data from the called function. Syntax :
Function declaration : void function();
Function call : function();
Function definition :
void function()
{
statements;
}
C
// C code for function with no// arguments and no return value #include <stdio.h>void value(void);void main(){ value();}void value(void){ float year = 1, period = 5, amount = 5000, inrate = 0.12; float sum; sum = amount; while (year <= period) { sum = sum * (1 + inrate); year = year + 1; } printf(" The total amount is %f:", sum);}
The total amount is 8811.708984:
Function with arguments but no return value: When a function has arguments, it receives any data from the calling function but it returns no values. Syntax :
Function with arguments but no return value: When a function has arguments, it receives any data from the calling function but it returns no values. Syntax :
Function declaration : void function ( int );
Function call : function( x );
Function definition:
void function( int x )
{
statements;
}
C
// C code for function// with argument but no return value#include <stdio.h> void function(int, int[], char[]);int main(){ int a = 20; int ar[5] = { 10, 20, 30, 40, 50 }; char str[30] = "geeksforgeeks"; function(a, &ar[0], &str[0]); return 0;} void function(int a, int* ar, char* str){ int i; printf("value of a is %d\n\n", a); for (i = 0; i < 5; i++) { printf("value of ar[%d] is %d\n", i, ar[i]); } printf("\nvalue of str is %s\n", str);}
value of a is 20
value of ar[0] is 10
value of ar[1] is 20
value of ar[2] is 30
value of ar[3] is 40
value of ar[4] is 50
value of str is geeksforgeeks
Function with no arguments but returns a value: There could be occasions where we may need to design functions that may not take any arguments but returns a value to the calling function. An example of this is getchar function it has no parameters but it returns an integer and integer type data that represents a character. Syntax :
Function with no arguments but returns a value: There could be occasions where we may need to design functions that may not take any arguments but returns a value to the calling function. An example of this is getchar function it has no parameters but it returns an integer and integer type data that represents a character. Syntax :
Function declaration : int function();
Function call : function();
Function definition :
int function()
{
statements;
return x;
}
C
// C code for function with no arguments// but have return value#include <math.h>#include <stdio.h> int sum();int main(){ int num; num = sum(); printf("\nSum of two given values = %d", num); return 0;} int sum(){ int a = 50, b = 80, sum; sum = sqrt(a) + sqrt(b); return sum;}
Sum of two given values = 16
Function with arguments and return value Syntax :
Function with arguments and return value Syntax :
Function declaration : int function ( int );
Function call : function( x );
Function definition:
int function( int x )
{
statements;
return x;
}
C
// C code for function with arguments// and with return value #include <stdio.h>#include <string.h>int function(int, int[]); int main(){ int i, a = 20; int arr[5] = { 10, 20, 30, 40, 50 }; a = function(a, &arr[0]); printf("value of a is %d\n", a); for (i = 0; i < 5; i++) { printf("value of arr[%d] is %d\n", i, arr[i]); } return 0;} int function(int a, int* arr){ int i; a = a + 20; arr[0] = arr[0] + 50; arr[1] = arr[1] + 50; arr[2] = arr[2] + 50; arr[3] = arr[3] + 50; arr[4] = arr[4] + 50; return a;}
value of a is 40
value of arr[0] is 60
value of arr[1] is 70
value of arr[2] is 80
value of arr[3] is 90
value of arr[4] is 100
touristeye
harendrakumar123
C-Functions
CBSE - Class 11
school-programming
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n30 May, 2022"
},
{
"code": null,
"e": 427,
"s": 52,
"text": "Prerequisite: Functions in C/C++ A function in C can be called either with arguments or without arguments. These functions may or may not return values to the calling functions. All C functions can be called either with arguments or without arguments in a C program. Also, they may or may not return any values. Hence the function prototype of a function in C is as below: |"
},
{
"code": null,
"e": 690,
"s": 427,
"text": "Function with no argument and no return value: When a function has no arguments, it does not receive any data from the calling function. Similarly, when it does not return a value, the calling function does not receive any data from the called function. Syntax :"
},
{
"code": null,
"e": 953,
"s": 690,
"text": "Function with no argument and no return value: When a function has no arguments, it does not receive any data from the calling function. Similarly, when it does not return a value, the calling function does not receive any data from the called function. Syntax :"
},
{
"code": null,
"e": 1165,
"s": 953,
"text": "Function declaration : void function();\nFunction call : function();\nFunction definition :\n void function()\n {\n statements;\n }"
},
{
"code": null,
"e": 1167,
"s": 1165,
"text": "C"
},
{
"code": "// C code for function with no// arguments and no return value #include <stdio.h>void value(void);void main(){ value();}void value(void){ float year = 1, period = 5, amount = 5000, inrate = 0.12; float sum; sum = amount; while (year <= period) { sum = sum * (1 + inrate); year = year + 1; } printf(\" The total amount is %f:\", sum);}",
"e": 1535,
"s": 1167,
"text": null
},
{
"code": null,
"e": 1569,
"s": 1535,
"text": " The total amount is 8811.708984:"
},
{
"code": null,
"e": 1727,
"s": 1569,
"text": "Function with arguments but no return value: When a function has arguments, it receives any data from the calling function but it returns no values. Syntax :"
},
{
"code": null,
"e": 1885,
"s": 1727,
"text": "Function with arguments but no return value: When a function has arguments, it receives any data from the calling function but it returns no values. Syntax :"
},
{
"code": null,
"e": 2076,
"s": 1885,
"text": "Function declaration : void function ( int );\nFunction call : function( x );\nFunction definition:\n void function( int x )\n {\n statements;\n }"
},
{
"code": null,
"e": 2078,
"s": 2076,
"text": "C"
},
{
"code": "// C code for function// with argument but no return value#include <stdio.h> void function(int, int[], char[]);int main(){ int a = 20; int ar[5] = { 10, 20, 30, 40, 50 }; char str[30] = \"geeksforgeeks\"; function(a, &ar[0], &str[0]); return 0;} void function(int a, int* ar, char* str){ int i; printf(\"value of a is %d\\n\\n\", a); for (i = 0; i < 5; i++) { printf(\"value of ar[%d] is %d\\n\", i, ar[i]); } printf(\"\\nvalue of str is %s\\n\", str);}",
"e": 2556,
"s": 2078,
"text": null
},
{
"code": null,
"e": 2711,
"s": 2556,
"text": "value of a is 20\n\nvalue of ar[0] is 10\nvalue of ar[1] is 20\nvalue of ar[2] is 30\nvalue of ar[3] is 40\nvalue of ar[4] is 50\n\nvalue of str is geeksforgeeks\n"
},
{
"code": null,
"e": 3045,
"s": 2711,
"text": "Function with no arguments but returns a value: There could be occasions where we may need to design functions that may not take any arguments but returns a value to the calling function. An example of this is getchar function it has no parameters but it returns an integer and integer type data that represents a character. Syntax :"
},
{
"code": null,
"e": 3379,
"s": 3045,
"text": "Function with no arguments but returns a value: There could be occasions where we may need to design functions that may not take any arguments but returns a value to the calling function. An example of this is getchar function it has no parameters but it returns an integer and integer type data that represents a character. Syntax :"
},
{
"code": null,
"e": 3609,
"s": 3379,
"text": "Function declaration : int function();\nFunction call : function();\nFunction definition :\n int function()\n {\n statements;\n return x;\n }\n "
},
{
"code": null,
"e": 3611,
"s": 3609,
"text": "C"
},
{
"code": "// C code for function with no arguments// but have return value#include <math.h>#include <stdio.h> int sum();int main(){ int num; num = sum(); printf(\"\\nSum of two given values = %d\", num); return 0;} int sum(){ int a = 50, b = 80, sum; sum = sqrt(a) + sqrt(b); return sum;}",
"e": 3908,
"s": 3611,
"text": null
},
{
"code": null,
"e": 3937,
"s": 3908,
"text": "Sum of two given values = 16"
},
{
"code": null,
"e": 3987,
"s": 3937,
"text": "Function with arguments and return value Syntax :"
},
{
"code": null,
"e": 4037,
"s": 3987,
"text": "Function with arguments and return value Syntax :"
},
{
"code": null,
"e": 4251,
"s": 4037,
"text": "Function declaration : int function ( int );\nFunction call : function( x );\nFunction definition:\n int function( int x )\n {\n statements;\n return x;\n }"
},
{
"code": null,
"e": 4253,
"s": 4251,
"text": "C"
},
{
"code": "// C code for function with arguments// and with return value #include <stdio.h>#include <string.h>int function(int, int[]); int main(){ int i, a = 20; int arr[5] = { 10, 20, 30, 40, 50 }; a = function(a, &arr[0]); printf(\"value of a is %d\\n\", a); for (i = 0; i < 5; i++) { printf(\"value of arr[%d] is %d\\n\", i, arr[i]); } return 0;} int function(int a, int* arr){ int i; a = a + 20; arr[0] = arr[0] + 50; arr[1] = arr[1] + 50; arr[2] = arr[2] + 50; arr[3] = arr[3] + 50; arr[4] = arr[4] + 50; return a;}",
"e": 4810,
"s": 4253,
"text": null
},
{
"code": null,
"e": 4939,
"s": 4810,
"text": "value of a is 40\nvalue of arr[0] is 60\nvalue of arr[1] is 70\nvalue of arr[2] is 80\nvalue of arr[3] is 90\nvalue of arr[4] is 100\n"
},
{
"code": null,
"e": 4950,
"s": 4939,
"text": "touristeye"
},
{
"code": null,
"e": 4967,
"s": 4950,
"text": "harendrakumar123"
},
{
"code": null,
"e": 4979,
"s": 4967,
"text": "C-Functions"
},
{
"code": null,
"e": 4995,
"s": 4979,
"text": "CBSE - Class 11"
},
{
"code": null,
"e": 5014,
"s": 4995,
"text": "school-programming"
},
{
"code": null,
"e": 5025,
"s": 5014,
"text": "C Language"
},
{
"code": null,
"e": 5029,
"s": 5025,
"text": "C++"
},
{
"code": null,
"e": 5033,
"s": 5029,
"text": "CPP"
}
] |
How to Create a Database Connection? | 15 Dec, 2021
Java Database Connectivity is a standard API or we can say an application interface present between the Java programming language and the various databases like Oracle, SQL, PostgreSQL, MongoDB, etc. It basically connects the front end(for interacting with the users) with the backend for storing data entered by the users in the table details. JDBC or Java Database Connection creates a database by following the following steps:
Import the database
Load and register drivers
Create a connection
Create a statement
Execute the query
Process the results
Close the connection
Step 1: Import the database
Java consists of many packages that ease the need to hardcode every logic. It has an inbuilt package of SQL that is needed for JDBC connection.
Syntax:
import java.sql* ;
Step 2: Load and register drivers
This is done by JVC(Java Virtual Machines) that loads certain driver files into secondary memory that are essential to the working of JDBC.
Syntax:
forName(com.mysql.jdbc.xyz);
class.forname() method is the most common approach to register drivers. It dynamically loads the driver file into the memory.
Example:
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch(ClassNotFoundException e) {
System.out.println("cant load driver class!");
System.Exit(1);
}
Here, the oracle database is used. Now let us considered a random example of hotel database management systems. Now applying SQL commands over it naming this database as ‘sample’. Now suppose the user starts inserting tables inside it be named as “sample1” and “sample2“.
Java
// Connections class // Importing all SQL classesimport java.sql.*; public class connection{ // Object of Connection class// initially assigned NULLConnection con = null; public static Connection connectDB(){ try { // Step 2: involve among 7 in Connection // class i.e Load and register drivers // 2(a) Loading drivers using forName() method // Here, the name of the database is mysql Class.forName("com.mysql.jdbc.Driver"); // 2(b) Registering drivers using DriverManager Connection con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/database", "root", "1234"); // Root is the username, and // 1234 is the password // Here, the object of Connection class is return // which further used in main class return con; } // Here, the exceptions is handle by Catch block catch (SQLException | ClassNotFoundException e) { // Print the exceptions System.out.println(e); return null; }}}
Step 3: Create a connection
Creating a connection is accomplished by the getconnection() method of DriverManager class, it contains the database URL, username, and password as a parameter.
Syntax:
public static Connection getConnection(String URL, String Username, String password)
throws SQLException
Example:
String URL = "jdbc:oracle:thin:@amrood:1241:EMP";
String USERNAME = "geekygirl";
String PASSWORD = "geekss"
Connection conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
Here,
The database URL looks like- jdbc:oracle:thin:@amrood:1221:EMPThe username be-“geekygirl”The passwords be-“geekss”
Step 4: Create a statement
Query statement is created to interact with the database by following the proper syntax. Before writing the query, we must connect the database using connect() method. For example:
conn = connection.connectDB();
String sql = "select * from customer";
This statement basically shows the contents of the customers’ table. We can also create a statement using the createStatement() method of the Connection interface. Here, the object of the statement is mainly responsible to execute queries.
Syntax:
public Statement createStatement()throws SQLException
Example:
Statement s = conn.createStatement();
Step 5: Execute the query
For executing the query (written above), we need to convert the query in JDBC readable format, for that we use the preparedstatement() function and for executing the converted query, we use the executequery() function of the Statement interface. It returns the object of “rs” which is used to find all the table records.
Syntax:
public rs executeQuery(String sql)throws SQLException
Example:
p = conn.prepareStatement(sql);
rs = p.executeQuery();
Step 6: Process the results
Now we check if rs.next() method is not null, then we display the details of that particular customer present in the “customer” table.next() function basically checks if there’s any record that satisfies the query, if no record satisfies the condition, then it returns null. Below is the sample code:
while (rs.next())
{
int id = rs.getInt("cusid");
String name = rs.getString("cusname");
String email = rs.getString("email");
System.out.println(id + "\t\t" + name +
"\t\t" + email);
}
Step 7: Close the connection
After all the operations are performed it’s necessary to close the JDBC connection after the database session is no longer needed. If not explicitly done, then the java garbage collector does the job for us. However being a good programmer, let us learn how to close the connection of JDBC. So to close the JDBC connection close() method is used, this method close all the JDBC connection.
Syntax:
public void close()throws SQLException
Example:
conn.close();
Sample code is illustrated above:
Java
// Importing SQL libraries to create databaseimport java.sql.*; class GFG{ // Step 1: Main driver methodpublic static void main(String[] args){ // Step 2: Creating connection using // Connection type and inbuilt function Connection con = null; PreparedStatement p = null; ResultSet rs = null; con = connection.connectDB(); // Here, try block is used to catch exceptions try { // Here, the SQL command is used to store // String datatype String sql = "select * from customer"; p = con.prepareStatement(sql); rs = p.executeQuery(); // Here, print the ID, name, email // of the customers System.out.println("id\t\tname\t\temail"); // Check condition while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); String email = rs.getString("email"); System.out.println(id + "\t\t" + name + "\t\t" + email); } } // Catch block is used for exception catch (SQLException e) { // Print exception pop-up on the screen System.out.println(e); }}}
Output:
sweetyty
Picked
Class 12
School Learning
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Dec, 2021"
},
{
"code": null,
"e": 459,
"s": 28,
"text": "Java Database Connectivity is a standard API or we can say an application interface present between the Java programming language and the various databases like Oracle, SQL, PostgreSQL, MongoDB, etc. It basically connects the front end(for interacting with the users) with the backend for storing data entered by the users in the table details. JDBC or Java Database Connection creates a database by following the following steps:"
},
{
"code": null,
"e": 479,
"s": 459,
"text": "Import the database"
},
{
"code": null,
"e": 505,
"s": 479,
"text": "Load and register drivers"
},
{
"code": null,
"e": 525,
"s": 505,
"text": "Create a connection"
},
{
"code": null,
"e": 544,
"s": 525,
"text": "Create a statement"
},
{
"code": null,
"e": 562,
"s": 544,
"text": "Execute the query"
},
{
"code": null,
"e": 582,
"s": 562,
"text": "Process the results"
},
{
"code": null,
"e": 603,
"s": 582,
"text": "Close the connection"
},
{
"code": null,
"e": 631,
"s": 603,
"text": "Step 1: Import the database"
},
{
"code": null,
"e": 776,
"s": 631,
"text": "Java consists of many packages that ease the need to hardcode every logic. It has an inbuilt package of SQL that is needed for JDBC connection. "
},
{
"code": null,
"e": 784,
"s": 776,
"text": "Syntax:"
},
{
"code": null,
"e": 803,
"s": 784,
"text": "import java.sql* ;"
},
{
"code": null,
"e": 837,
"s": 803,
"text": "Step 2: Load and register drivers"
},
{
"code": null,
"e": 977,
"s": 837,
"text": "This is done by JVC(Java Virtual Machines) that loads certain driver files into secondary memory that are essential to the working of JDBC."
},
{
"code": null,
"e": 985,
"s": 977,
"text": "Syntax:"
},
{
"code": null,
"e": 1014,
"s": 985,
"text": "forName(com.mysql.jdbc.xyz);"
},
{
"code": null,
"e": 1141,
"s": 1014,
"text": "class.forname() method is the most common approach to register drivers. It dynamically loads the driver file into the memory. "
},
{
"code": null,
"e": 1150,
"s": 1141,
"text": "Example:"
},
{
"code": null,
"e": 1316,
"s": 1150,
"text": "try {\n Class.forName(\"oracle.jdbc.driver.OracleDriver\");\n}\ncatch(ClassNotFoundException e) {\n System.out.println(\"cant load driver class!\");\n System.Exit(1);\n}"
},
{
"code": null,
"e": 1588,
"s": 1316,
"text": "Here, the oracle database is used. Now let us considered a random example of hotel database management systems. Now applying SQL commands over it naming this database as ‘sample’. Now suppose the user starts inserting tables inside it be named as “sample1” and “sample2“."
},
{
"code": null,
"e": 1593,
"s": 1588,
"text": "Java"
},
{
"code": "// Connections class // Importing all SQL classesimport java.sql.*; public class connection{ // Object of Connection class// initially assigned NULLConnection con = null; public static Connection connectDB(){ try { // Step 2: involve among 7 in Connection // class i.e Load and register drivers // 2(a) Loading drivers using forName() method // Here, the name of the database is mysql Class.forName(\"com.mysql.jdbc.Driver\"); // 2(b) Registering drivers using DriverManager Connection con = DriverManager.getConnection( \"jdbc:mysql://localhost:3306/database\", \"root\", \"1234\"); // Root is the username, and // 1234 is the password // Here, the object of Connection class is return // which further used in main class return con; } // Here, the exceptions is handle by Catch block catch (SQLException | ClassNotFoundException e) { // Print the exceptions System.out.println(e); return null; }}}",
"e": 2671,
"s": 1593,
"text": null
},
{
"code": null,
"e": 2699,
"s": 2671,
"text": "Step 3: Create a connection"
},
{
"code": null,
"e": 2861,
"s": 2699,
"text": "Creating a connection is accomplished by the getconnection() method of DriverManager class, it contains the database URL, username, and password as a parameter. "
},
{
"code": null,
"e": 2869,
"s": 2861,
"text": "Syntax:"
},
{
"code": null,
"e": 2978,
"s": 2869,
"text": "public static Connection getConnection(String URL, String Username, String password) \nthrows SQLException "
},
{
"code": null,
"e": 2987,
"s": 2978,
"text": "Example:"
},
{
"code": null,
"e": 3167,
"s": 2987,
"text": "String URL = \"jdbc:oracle:thin:@amrood:1241:EMP\";\nString USERNAME = \"geekygirl\";\nString PASSWORD = \"geekss\"\nConnection conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);"
},
{
"code": null,
"e": 3174,
"s": 3167,
"text": "Here, "
},
{
"code": null,
"e": 3289,
"s": 3174,
"text": "The database URL looks like- jdbc:oracle:thin:@amrood:1221:EMPThe username be-“geekygirl”The passwords be-“geekss”"
},
{
"code": null,
"e": 3316,
"s": 3289,
"text": "Step 4: Create a statement"
},
{
"code": null,
"e": 3497,
"s": 3316,
"text": "Query statement is created to interact with the database by following the proper syntax. Before writing the query, we must connect the database using connect() method. For example:"
},
{
"code": null,
"e": 3567,
"s": 3497,
"text": "conn = connection.connectDB();\nString sql = \"select * from customer\";"
},
{
"code": null,
"e": 3807,
"s": 3567,
"text": "This statement basically shows the contents of the customers’ table. We can also create a statement using the createStatement() method of the Connection interface. Here, the object of the statement is mainly responsible to execute queries."
},
{
"code": null,
"e": 3815,
"s": 3807,
"text": "Syntax:"
},
{
"code": null,
"e": 3870,
"s": 3815,
"text": "public Statement createStatement()throws SQLException "
},
{
"code": null,
"e": 3879,
"s": 3870,
"text": "Example:"
},
{
"code": null,
"e": 3917,
"s": 3879,
"text": "Statement s = conn.createStatement();"
},
{
"code": null,
"e": 3943,
"s": 3917,
"text": "Step 5: Execute the query"
},
{
"code": null,
"e": 4264,
"s": 3943,
"text": "For executing the query (written above), we need to convert the query in JDBC readable format, for that we use the preparedstatement() function and for executing the converted query, we use the executequery() function of the Statement interface. It returns the object of “rs” which is used to find all the table records."
},
{
"code": null,
"e": 4272,
"s": 4264,
"text": "Syntax:"
},
{
"code": null,
"e": 4328,
"s": 4272,
"text": "public rs executeQuery(String sql)throws SQLException "
},
{
"code": null,
"e": 4337,
"s": 4328,
"text": "Example:"
},
{
"code": null,
"e": 4392,
"s": 4337,
"text": "p = conn.prepareStatement(sql);\nrs = p.executeQuery();"
},
{
"code": null,
"e": 4420,
"s": 4392,
"text": "Step 6: Process the results"
},
{
"code": null,
"e": 4722,
"s": 4420,
"text": "Now we check if rs.next() method is not null, then we display the details of that particular customer present in the “customer” table.next() function basically checks if there’s any record that satisfies the query, if no record satisfies the condition, then it returns null. Below is the sample code: "
},
{
"code": null,
"e": 4954,
"s": 4722,
"text": "while (rs.next())\n{ \n int id = rs.getInt(\"cusid\");\n String name = rs.getString(\"cusname\");\n String email = rs.getString(\"email\");\n System.out.println(id + \"\\t\\t\" + name + \n \"\\t\\t\" + email);\n}"
},
{
"code": null,
"e": 4983,
"s": 4954,
"text": "Step 7: Close the connection"
},
{
"code": null,
"e": 5374,
"s": 4983,
"text": "After all the operations are performed it’s necessary to close the JDBC connection after the database session is no longer needed. If not explicitly done, then the java garbage collector does the job for us. However being a good programmer, let us learn how to close the connection of JDBC. So to close the JDBC connection close() method is used, this method close all the JDBC connection. "
},
{
"code": null,
"e": 5382,
"s": 5374,
"text": "Syntax:"
},
{
"code": null,
"e": 5423,
"s": 5382,
"text": "public void close()throws SQLException "
},
{
"code": null,
"e": 5432,
"s": 5423,
"text": "Example:"
},
{
"code": null,
"e": 5446,
"s": 5432,
"text": "conn.close();"
},
{
"code": null,
"e": 5480,
"s": 5446,
"text": "Sample code is illustrated above:"
},
{
"code": null,
"e": 5485,
"s": 5480,
"text": "Java"
},
{
"code": "// Importing SQL libraries to create databaseimport java.sql.*; class GFG{ // Step 1: Main driver methodpublic static void main(String[] args){ // Step 2: Creating connection using // Connection type and inbuilt function Connection con = null; PreparedStatement p = null; ResultSet rs = null; con = connection.connectDB(); // Here, try block is used to catch exceptions try { // Here, the SQL command is used to store // String datatype String sql = \"select * from customer\"; p = con.prepareStatement(sql); rs = p.executeQuery(); // Here, print the ID, name, email // of the customers System.out.println(\"id\\t\\tname\\t\\temail\"); // Check condition while (rs.next()) { int id = rs.getInt(\"id\"); String name = rs.getString(\"name\"); String email = rs.getString(\"email\"); System.out.println(id + \"\\t\\t\" + name + \"\\t\\t\" + email); } } // Catch block is used for exception catch (SQLException e) { // Print exception pop-up on the screen System.out.println(e); }}}",
"e": 6693,
"s": 5485,
"text": null
},
{
"code": null,
"e": 6701,
"s": 6693,
"text": "Output:"
},
{
"code": null,
"e": 6710,
"s": 6701,
"text": "sweetyty"
},
{
"code": null,
"e": 6717,
"s": 6710,
"text": "Picked"
},
{
"code": null,
"e": 6726,
"s": 6717,
"text": "Class 12"
},
{
"code": null,
"e": 6742,
"s": 6726,
"text": "School Learning"
},
{
"code": null,
"e": 6761,
"s": 6742,
"text": "School Programming"
}
] |
How we can import Python modules without installing? | Yes there are ways to import Python modules without installing. If you are not able to install modules on a machine(due to not having enough permissions), you could use either virtualenv or save the module files in another directory and use the following code to allow Python to search for modules in the given module:
>>> import os, sys
>>> file_path = 'AdditionalModules/'
>>> sys.path.append(os.path.dirname(file_path))
>>> # Now python also searches AdditionalModules folder for importing modules as we have set it on the PYTHONPATH.
You can also use virtualenv to create an isolated local Python environment. The basic problem being addressed is one of dependencies and versions, and indirectly permissions. Imagine you have an application that needs version 1 of LibFoo, but another application requires version 2. How can you use both these applications? If you install everything into /usr/lib/python2.7/site-packages (or whatever your platform’s standard location is), it’s easy to end up in a situation where you unintentionally upgrade an application that shouldn’t be upgraded. This can also be used in our use case where we cannot install the package on the machine as we dont have the permissions. For more info on virtual env, read the docs: https://virtualenv.pypa.io/en/stable/ | [
{
"code": null,
"e": 1381,
"s": 1062,
"text": "Yes there are ways to import Python modules without installing. If you are not able to install modules on a machine(due to not having enough permissions), you could use either virtualenv or save the module files in another directory and use the following code to allow Python to search for modules in the given module:"
},
{
"code": null,
"e": 1600,
"s": 1381,
"text": ">>> import os, sys\n>>> file_path = 'AdditionalModules/'\n>>> sys.path.append(os.path.dirname(file_path))\n>>> # Now python also searches AdditionalModules folder for importing modules as we have set it on the PYTHONPATH."
},
{
"code": null,
"e": 2357,
"s": 1600,
"text": "You can also use virtualenv to create an isolated local Python environment. The basic problem being addressed is one of dependencies and versions, and indirectly permissions. Imagine you have an application that needs version 1 of LibFoo, but another application requires version 2. How can you use both these applications? If you install everything into /usr/lib/python2.7/site-packages (or whatever your platform’s standard location is), it’s easy to end up in a situation where you unintentionally upgrade an application that shouldn’t be upgraded. This can also be used in our use case where we cannot install the package on the machine as we dont have the permissions. For more info on virtual env, read the docs: https://virtualenv.pypa.io/en/stable/"
}
] |
How to draw a violin plot in R? | A violin plot is similar to a boxplot but looks like a violin and shows the distribution of the data for different categories. It shows the density of the data values at different points. In R, we can draw a violin plot with the help of ggplot2 package as it has a function called geom_violin for this purpose.
Consider the below data frame −
set.seed(1)
x <-rep(c("S1","S2","S3","S4","S5"),each=50)
set.seed(1)
x <-rep(c("S1","S2","S3","S4","S5"),each=100)
y <-rnorm(500)
grp <-rep(c("A","B"),times=250)
df <-data.frame(x,y,grp)
head(df,20)
x y grp
1 S1 -0.62645381 A
2 S1 0.18364332 B
3 S1 -0.83562861 A
4 S1 1.59528080 B
5 S1 0.32950777 A
6 S1 -0.82046838 B
7 S1 0.48742905 A
8 S1 0.73832471 B
9 S1 0.57578135 A
10 S1 -0.30538839 B
11 S1 1.51178117 A
12 S1 0.38984324 B
13 S1 -0.62124058 A
14 S1 -2.21469989 B
15 S1 1.12493092 A
16 S1 -0.04493361 B
17 S1 -0.01619026 A
18 S1 0.94383621 B
19 S1 0.82122120 A
20 S1 0.59390132 B
Creating violin plot by filling colors with x variable −
ggplot(df,aes(grp,y,fill=x))+geom_violin()
Creating violin plot by filling colors with grp variable −
ggplot(df,aes(x,y,fill=grp))+geom_violin() | [
{
"code": null,
"e": 1373,
"s": 1062,
"text": "A violin plot is similar to a boxplot but looks like a violin and shows the distribution of the data for different categories. It shows the density of the data values at different points. In R, we can draw a violin plot with the help of ggplot2 package as it has a function called geom_violin for this purpose."
},
{
"code": null,
"e": 1405,
"s": 1373,
"text": "Consider the below data frame −"
},
{
"code": null,
"e": 1604,
"s": 1405,
"text": "set.seed(1)\nx <-rep(c(\"S1\",\"S2\",\"S3\",\"S4\",\"S5\"),each=50)\nset.seed(1)\nx <-rep(c(\"S1\",\"S2\",\"S3\",\"S4\",\"S5\"),each=100)\ny <-rnorm(500)\ngrp <-rep(c(\"A\",\"B\"),times=250)\ndf <-data.frame(x,y,grp)\nhead(df,20)"
},
{
"code": null,
"e": 2000,
"s": 1604,
"text": " x y grp\n1 S1 -0.62645381 A\n2 S1 0.18364332 B\n3 S1 -0.83562861 A\n4 S1 1.59528080 B\n5 S1 0.32950777 A\n6 S1 -0.82046838 B\n7 S1 0.48742905 A\n8 S1 0.73832471 B\n9 S1 0.57578135 A\n10 S1 -0.30538839 B\n11 S1 1.51178117 A\n12 S1 0.38984324 B\n13 S1 -0.62124058 A\n14 S1 -2.21469989 B\n15 S1 1.12493092 A\n16 S1 -0.04493361 B\n17 S1 -0.01619026 A\n18 S1 0.94383621 B\n19 S1 0.82122120 A\n20 S1 0.59390132 B"
},
{
"code": null,
"e": 2057,
"s": 2000,
"text": "Creating violin plot by filling colors with x variable −"
},
{
"code": null,
"e": 2100,
"s": 2057,
"text": "ggplot(df,aes(grp,y,fill=x))+geom_violin()"
},
{
"code": null,
"e": 2159,
"s": 2100,
"text": "Creating violin plot by filling colors with grp variable −"
},
{
"code": null,
"e": 2202,
"s": 2159,
"text": "ggplot(df,aes(x,y,fill=grp))+geom_violin()"
}
] |
ES6 - Collections Set Method add() | This method appends a new element with the given value to the Set object.
mySet.add(value);
Value − item to add to the list.
Value − item to add to the list.
Set Object.
var set = new Set();
set.add(10);
set.add(10); // duplicate not added
set.add(10); // duplicate not added
set.add(20);
set.add(30);
console.log(set.size);
3
32 Lectures
3.5 hours
Sharad Kumar
40 Lectures
5 hours
Richa Maheshwari
16 Lectures
1 hours
Anadi Sharma
50 Lectures
6.5 hours
Gowthami Swarna
14 Lectures
1 hours
Deepti Trivedi
31 Lectures
1.5 hours
Shweta
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2351,
"s": 2277,
"text": "This method appends a new element with the given value to the Set object."
},
{
"code": null,
"e": 2370,
"s": 2351,
"text": "mySet.add(value);\n"
},
{
"code": null,
"e": 2403,
"s": 2370,
"text": "Value − item to add to the list."
},
{
"code": null,
"e": 2436,
"s": 2403,
"text": "Value − item to add to the list."
},
{
"code": null,
"e": 2448,
"s": 2436,
"text": "Set Object."
},
{
"code": null,
"e": 2609,
"s": 2448,
"text": "var set = new Set(); \nset.add(10); \nset.add(10); // duplicate not added \nset.add(10); // duplicate not added \nset.add(20); \nset.add(30); \nconsole.log(set.size);"
},
{
"code": null,
"e": 2612,
"s": 2609,
"text": "3\n"
},
{
"code": null,
"e": 2647,
"s": 2612,
"text": "\n 32 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 2661,
"s": 2647,
"text": " Sharad Kumar"
},
{
"code": null,
"e": 2694,
"s": 2661,
"text": "\n 40 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 2712,
"s": 2694,
"text": " Richa Maheshwari"
},
{
"code": null,
"e": 2745,
"s": 2712,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 2759,
"s": 2745,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 2794,
"s": 2759,
"text": "\n 50 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 2811,
"s": 2794,
"text": " Gowthami Swarna"
},
{
"code": null,
"e": 2844,
"s": 2811,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 2860,
"s": 2844,
"text": " Deepti Trivedi"
},
{
"code": null,
"e": 2895,
"s": 2860,
"text": "\n 31 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 2903,
"s": 2895,
"text": " Shweta"
},
{
"code": null,
"e": 2910,
"s": 2903,
"text": " Print"
},
{
"code": null,
"e": 2921,
"s": 2910,
"text": " Add Notes"
}
] |
Array in Python | Set 2 (Important Functions) - GeeksforGeeks | 13 May, 2020
Array in Python | Set 1 (Introduction and Functions)
Below are some more functions.
1. typecode :- This function returns the data type by which array is initialised.
2. itemsize :- This function returns size in bytes of a single array element.
3. buffer_info() :- Returns a tuple representing the address in which array is stored and number of elements in it.
# Python code to demonstrate the working of # typecode, itemsize, buffer_info() # importing "array" for array operationsimport array # initializing array with array values# initializes array with signed integersarr= array.array('i',[1, 2, 3, 1, 2, 5]) # using typecode to print datatype of arrayprint ("The datatype of array is : ")print (arr.typecode) # using itemsize to print itemsize of arrayprint ("The itemsize of array is : ")print (arr.itemsize) # using buffer_info() to print buffer info. of arrayprint ("The buffer info. of array is : ")print (arr.buffer_info())
The datatype of array is :
i
The itemsize of array is :
4
The buffer info. of array is :
(29784224, 6)
Instead of import array, we can also use * to import array.
# importing "array" using * for array operationsfrom array import * # initializing array with array values# initializes array with signed integersarr = array('i',[1, 2, 3, 1, 2, 5]) print(arr)
array('i', [1, 2, 3, 1, 2, 5])
4. count() :- This function counts the number of occurrences of argument mentioned in array.
5. extend(arr) :- This function appends a whole array mentioned in its arguments to the specified array.
# Python code to demonstrate the working of # count() and extend() # importing "array" for array operationsimport array # initializing array 1 with array values# initializes array with signed integersarr1 = array.array('i',[1, 2, 3, 1, 2, 5]) # initializing array 2 with array values# initializes array with signed integersarr2 = array.array('i',[1, 2, 3]) # using count() to count occurrences of 1 in arrayprint ("The occurrences of 1 in array is : ")print (arr1.count(1)) # using extend() to add array 2 elements to array 1 arr1.extend(arr2) print ("The modified array is : ")for i in range (0,9): print (arr1[i])
The occurrences of 1 in array is :
2
The modified array is :
1
2
3
1
2
5
1
2
3
6. fromlist(list) :- This function is used to append a list mentioned in its argument to end of array.
7. tolist() :- This function is used to transform an array into a list.
# Python code to demonstrate the working of # fromlist() and tolist() # importing "array" for array operationsimport array # initializing array with array values# initializes array with signed integersarr = array.array('i',[1, 2, 3, 1, 2, 5]) # initializing listli = [1, 2, 3] # using fromlist() to append list at end of arrayarr.fromlist(li) # printing the modified arrayprint ("The modified array is : ",end="")for i in range (0,9): print (arr[i],end=" ") # using tolist() to convert array into listli2 = arr.tolist() print ("\r") # printing the new listprint ("The new list created is : ",end="")for i in range (0,len(li2)): print (li2[i],end=" ")
The modified array is : 1 2 3 1 2 5 1 2 3
The new list created is : 1 2 3 1 2 5 1 2 3
YouTubeGeeksforGeeks507K subscribersPython Programming Tutorial | Arrays - Part 2 | 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:42•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=21dgNSzG2Iw" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Manjeet Singh. 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.
utkarsh_malik31
Python
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python Dictionary
Inheritance in C++
Reverse a string in Java
C++ Classes and Objects
Interfaces in Java | [
{
"code": null,
"e": 25691,
"s": 25663,
"text": "\n13 May, 2020"
},
{
"code": null,
"e": 25744,
"s": 25691,
"text": "Array in Python | Set 1 (Introduction and Functions)"
},
{
"code": null,
"e": 25775,
"s": 25744,
"text": "Below are some more functions."
},
{
"code": null,
"e": 25857,
"s": 25775,
"text": "1. typecode :- This function returns the data type by which array is initialised."
},
{
"code": null,
"e": 25935,
"s": 25857,
"text": "2. itemsize :- This function returns size in bytes of a single array element."
},
{
"code": null,
"e": 26051,
"s": 25935,
"text": "3. buffer_info() :- Returns a tuple representing the address in which array is stored and number of elements in it."
},
{
"code": "# Python code to demonstrate the working of # typecode, itemsize, buffer_info() # importing \"array\" for array operationsimport array # initializing array with array values# initializes array with signed integersarr= array.array('i',[1, 2, 3, 1, 2, 5]) # using typecode to print datatype of arrayprint (\"The datatype of array is : \")print (arr.typecode) # using itemsize to print itemsize of arrayprint (\"The itemsize of array is : \")print (arr.itemsize) # using buffer_info() to print buffer info. of arrayprint (\"The buffer info. of array is : \")print (arr.buffer_info())",
"e": 26632,
"s": 26051,
"text": null
},
{
"code": null,
"e": 26739,
"s": 26632,
"text": "The datatype of array is : \ni\nThe itemsize of array is : \n4\nThe buffer info. of array is : \n(29784224, 6)\n"
},
{
"code": null,
"e": 26799,
"s": 26739,
"text": "Instead of import array, we can also use * to import array."
},
{
"code": "# importing \"array\" using * for array operationsfrom array import * # initializing array with array values# initializes array with signed integersarr = array('i',[1, 2, 3, 1, 2, 5]) print(arr)",
"e": 26996,
"s": 26799,
"text": null
},
{
"code": null,
"e": 27028,
"s": 26996,
"text": "array('i', [1, 2, 3, 1, 2, 5])\n"
},
{
"code": null,
"e": 27121,
"s": 27028,
"text": "4. count() :- This function counts the number of occurrences of argument mentioned in array."
},
{
"code": null,
"e": 27226,
"s": 27121,
"text": "5. extend(arr) :- This function appends a whole array mentioned in its arguments to the specified array."
},
{
"code": "# Python code to demonstrate the working of # count() and extend() # importing \"array\" for array operationsimport array # initializing array 1 with array values# initializes array with signed integersarr1 = array.array('i',[1, 2, 3, 1, 2, 5]) # initializing array 2 with array values# initializes array with signed integersarr2 = array.array('i',[1, 2, 3]) # using count() to count occurrences of 1 in arrayprint (\"The occurrences of 1 in array is : \")print (arr1.count(1)) # using extend() to add array 2 elements to array 1 arr1.extend(arr2) print (\"The modified array is : \")for i in range (0,9): print (arr1[i])",
"e": 27855,
"s": 27226,
"text": null
},
{
"code": null,
"e": 27937,
"s": 27855,
"text": "The occurrences of 1 in array is : \n2\nThe modified array is : \n1\n2\n3\n1\n2\n5\n1\n2\n3\n"
},
{
"code": null,
"e": 28040,
"s": 27937,
"text": "6. fromlist(list) :- This function is used to append a list mentioned in its argument to end of array."
},
{
"code": null,
"e": 28112,
"s": 28040,
"text": "7. tolist() :- This function is used to transform an array into a list."
},
{
"code": "# Python code to demonstrate the working of # fromlist() and tolist() # importing \"array\" for array operationsimport array # initializing array with array values# initializes array with signed integersarr = array.array('i',[1, 2, 3, 1, 2, 5]) # initializing listli = [1, 2, 3] # using fromlist() to append list at end of arrayarr.fromlist(li) # printing the modified arrayprint (\"The modified array is : \",end=\"\")for i in range (0,9): print (arr[i],end=\" \") # using tolist() to convert array into listli2 = arr.tolist() print (\"\\r\") # printing the new listprint (\"The new list created is : \",end=\"\")for i in range (0,len(li2)): print (li2[i],end=\" \")",
"e": 28780,
"s": 28112,
"text": null
},
{
"code": null,
"e": 28868,
"s": 28780,
"text": "The modified array is : 1 2 3 1 2 5 1 2 3 \nThe new list created is : 1 2 3 1 2 5 1 2 3\n"
},
{
"code": null,
"e": 29712,
"s": 28868,
"text": "YouTubeGeeksforGeeks507K subscribersPython Programming Tutorial | Arrays - Part 2 | 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:42•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=21dgNSzG2Iw\" 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": 30013,
"s": 29712,
"text": "This article is contributed by Manjeet Singh. 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": 30138,
"s": 30013,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 30154,
"s": 30138,
"text": "utkarsh_malik31"
},
{
"code": null,
"e": 30161,
"s": 30154,
"text": "Python"
},
{
"code": null,
"e": 30180,
"s": 30161,
"text": "School Programming"
},
{
"code": null,
"e": 30278,
"s": 30180,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30296,
"s": 30278,
"text": "Python Dictionary"
},
{
"code": null,
"e": 30331,
"s": 30296,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 30363,
"s": 30331,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 30385,
"s": 30363,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 30427,
"s": 30385,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 30445,
"s": 30427,
"text": "Python Dictionary"
},
{
"code": null,
"e": 30464,
"s": 30445,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 30489,
"s": 30464,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 30513,
"s": 30489,
"text": "C++ Classes and Objects"
}
] |
Python | Matrix Product - GeeksforGeeks | 30 Dec, 2020
Getting the product of list is quite common problem and has been dealt with and discussed many times, but sometimes, we require to better it and total product, i.e. including those of nested list as well. Let’s try and get the total product and solve this particular problem.
Method #1 : Using list comprehension + loopWe can solve this problem using the list comprehension as a potential shorthand to the conventional loops that we may use to perform this particular task. We just iterate and product the nested list and at end return the cumulative product using function.
# Python3 code to demonstrate# Matrix Product# Using list comprehension + loop # getting Productdef prod(val) : res = 1 for ele in val: res *= ele return res # initializing listtest_list = [[1, 4, 5], [7, 3], [4], [46, 7, 3]] # printing original listprint("The original list : " + str(test_list)) # using list comprehension + loop# Matrix Productres = prod([ele for sub in test_list for ele in sub]) # print resultprint("The total element product in lists is : " + str(res))
The original list : [[1, 4, 5], [7, 3], [4], [46, 7, 3]]
The total element product in lists is : 1622880
Method #2 : Using chain() + loopThis particular problem can also be solved using the chain function instead of list comprehension in which we use the conventional function to perform product.
# Python3 code to demonstrate# Matrix Product# Using chain() + loopfrom itertools import chain # getting Productdef prod(val) : res = 1 for ele in val: res *= ele return res # initializing listtest_list = [[1, 4, 5], [7, 3], [4], [46, 7, 3]] # printing original listprint("The original list : " + str(test_list)) # using chain() + loop# Matrix Productres = prod(list(chain(*test_list))) # print resultprint("The total element product in lists is : " + str(res))
The original list : [[1, 4, 5], [7, 3], [4], [46, 7, 3]]
The total element product in lists is : 1622880
Python list-programs
Python matrix-program
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python? | [
{
"code": null,
"e": 25561,
"s": 25533,
"text": "\n30 Dec, 2020"
},
{
"code": null,
"e": 25837,
"s": 25561,
"text": "Getting the product of list is quite common problem and has been dealt with and discussed many times, but sometimes, we require to better it and total product, i.e. including those of nested list as well. Let’s try and get the total product and solve this particular problem."
},
{
"code": null,
"e": 26136,
"s": 25837,
"text": "Method #1 : Using list comprehension + loopWe can solve this problem using the list comprehension as a potential shorthand to the conventional loops that we may use to perform this particular task. We just iterate and product the nested list and at end return the cumulative product using function."
},
{
"code": "# Python3 code to demonstrate# Matrix Product# Using list comprehension + loop # getting Productdef prod(val) : res = 1 for ele in val: res *= ele return res # initializing listtest_list = [[1, 4, 5], [7, 3], [4], [46, 7, 3]] # printing original listprint(\"The original list : \" + str(test_list)) # using list comprehension + loop# Matrix Productres = prod([ele for sub in test_list for ele in sub]) # print resultprint(\"The total element product in lists is : \" + str(res))",
"e": 26634,
"s": 26136,
"text": null
},
{
"code": null,
"e": 26740,
"s": 26634,
"text": "The original list : [[1, 4, 5], [7, 3], [4], [46, 7, 3]]\nThe total element product in lists is : 1622880\n"
},
{
"code": null,
"e": 26934,
"s": 26742,
"text": "Method #2 : Using chain() + loopThis particular problem can also be solved using the chain function instead of list comprehension in which we use the conventional function to perform product."
},
{
"code": "# Python3 code to demonstrate# Matrix Product# Using chain() + loopfrom itertools import chain # getting Productdef prod(val) : res = 1 for ele in val: res *= ele return res # initializing listtest_list = [[1, 4, 5], [7, 3], [4], [46, 7, 3]] # printing original listprint(\"The original list : \" + str(test_list)) # using chain() + loop# Matrix Productres = prod(list(chain(*test_list))) # print resultprint(\"The total element product in lists is : \" + str(res))",
"e": 27419,
"s": 26934,
"text": null
},
{
"code": null,
"e": 27525,
"s": 27419,
"text": "The original list : [[1, 4, 5], [7, 3], [4], [46, 7, 3]]\nThe total element product in lists is : 1622880\n"
},
{
"code": null,
"e": 27546,
"s": 27525,
"text": "Python list-programs"
},
{
"code": null,
"e": 27568,
"s": 27546,
"text": "Python matrix-program"
},
{
"code": null,
"e": 27575,
"s": 27568,
"text": "Python"
},
{
"code": null,
"e": 27591,
"s": 27575,
"text": "Python Programs"
},
{
"code": null,
"e": 27689,
"s": 27591,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27721,
"s": 27689,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27763,
"s": 27721,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27805,
"s": 27763,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27861,
"s": 27805,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27888,
"s": 27861,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27910,
"s": 27888,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27949,
"s": 27910,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 27995,
"s": 27949,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 28033,
"s": 27995,
"text": "Python | Convert a list to dictionary"
}
] |
Merge Two Binary Trees by doing Node Sum (Recursive and Iterative) - GeeksforGeeks | 17 Apr, 2022
Given two binary trees. We need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the non-null node will be used as the node of new tree.
Example:
Input:
Tree 1 Tree 2
2 3
/ \ / \
1 4 6 1
/ \ \
5 2 7
Output: Merged tree:
5
/ \
7 5
/ \ \
5 2 7
Note: The merging process must start from the root nodes of both trees.
Recursive Algorithm:
Traverse the tree in Pre-order fashionCheck if both the tree nodes are NULL If not, then update the valueRecur for left subtreesRecur for right subtreesReturn root of updated Tree
Traverse the tree in Pre-order fashion
Check if both the tree nodes are NULL If not, then update the value
If not, then update the value
If not, then update the value
Recur for left subtrees
Recur for right subtrees
Return root of updated Tree
C++
C
Java
Python3
C#
Javascript
// C++ program to Merge Two Binary Trees#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */struct Node{ int data; struct Node *left, *right;}; /* Helper function that allocates a new node with the given data and NULL left and right pointers. */Node *newNode(int data){ Node *new_node = new Node; new_node->data = data; new_node->left = new_node->right = NULL; return new_node;} /* Given a binary tree, print its nodes in inorder*/void inorder(Node * node){ if (!node) return; /* first recur on left child */ inorder(node->left); /* then print the data of node */ cout<<node->data<<" "; /* now recur on right child */ inorder(node->right);} /* Function to merge given two binary trees*/Node *MergeTrees(Node * t1, Node * t2){ if (!t1) return t2; if (!t2) return t1; t1->data += t2->data; t1->left = MergeTrees(t1->left, t2->left); t1->right = MergeTrees(t1->right, t2->right); return t1;} // Driver codeint main(){ /* Let us construct the first Binary Tree 1 / \ 2 3 / \ \ 4 5 6 */ Node *root1 = newNode(1); root1->left = newNode(2); root1->right = newNode(3); root1->left->left = newNode(4); root1->left->right = newNode(5); root1->right->right = newNode(6); /* Let us construct the second Binary Tree 4 / \ 1 7 / / \ 3 2 6 */ Node *root2 = newNode(4); root2->left = newNode(1); root2->right = newNode(7); root2->left->left = newNode(3); root2->right->left = newNode(2); root2->right->right = newNode(6); Node *root3 = MergeTrees(root1, root2); printf("The Merged Binary Tree is:\n"); inorder(root3); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// C program to Merge Two Binary Trees #include<stdio.h>#include<stdlib.h> /* A binary tree node has data, pointer to left child and a pointer to right child */typedef struct Node{ int data; struct Node *left, *right;}Node; /* Helper function that allocates a new node with the given data and NULL left and right pointers. */Node *newNode(int data){ Node *new_node = (Node *)malloc(sizeof(Node)); new_node->data = data; new_node->left = new_node->right = NULL; return new_node;} /* Given a binary tree, print its nodes in inorder*/void inorder(Node * node){ if (!node) return; /* first recur on left child */ inorder(node->left); /* then print the data of node */ printf("%d ", node->data); /* now recur on right child */ inorder(node->right);} /* Function to merge given two binary trees*/Node *MergeTrees(Node * t1, Node * t2){ if (!t1) return t2; if (!t2) return t1; t1->data += t2->data; t1->left = MergeTrees(t1->left, t2->left); t1->right = MergeTrees(t1->right, t2->right); return t1;} // Driver codeint main(){ /* Let us construct the first Binary Tree 1 / \ 2 3 / \ \ 4 5 6 */ Node *root1 = newNode(1); root1->left = newNode(2); root1->right = newNode(3); root1->left->left = newNode(4); root1->left->right = newNode(5); root1->right->right = newNode(6); /* Let us construct the second Binary Tree 4 / \ 1 7 / / \ 3 2 6 */ Node *root2 = newNode(4); root2->left = newNode(1); root2->right = newNode(7); root2->left->left = newNode(3); root2->right->left = newNode(2); root2->right->right = newNode(6); Node *root3 = MergeTrees(root1, root2); printf("The Merged Binary Tree is:\n"); inorder(root3); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// Java program to Merge Two Binary Trees /* A binary tree node has data, pointer to left child and a pointer to right child */class Node{ int data; Node left, right; public Node(int data, Node left, Node right) { this.data = data; this.left = left; this.right = right; } /* Helper method that allocates a new node with the given data and NULL left and right pointers. */ static Node newNode(int data) { return new Node(data, null, null); } /* Given a binary tree, print its nodes in inorder*/ static void inorder(Node node) { if (node == null) return; /* first recur on left child */ inorder(node.left); /* then print the data of node */ System.out.printf("%d ", node.data); /* now recur on right child */ inorder(node.right); } /* Method to merge given two binary trees*/ static Node MergeTrees(Node t1, Node t2) { if (t1 == null) return t2; if (t2 == null) return t1; t1.data += t2.data; t1.left = MergeTrees(t1.left, t2.left); t1.right = MergeTrees(t1.right, t2.right); return t1; } // Driver method public static void main(String[] args) { /* Let us construct the first Binary Tree 1 / \ 2 3 / \ \ 4 5 6 */ Node root1 = newNode(1); root1.left = newNode(2); root1.right = newNode(3); root1.left.left = newNode(4); root1.left.right = newNode(5); root1.right.right = newNode(6); /* Let us construct the second Binary Tree 4 / \ 1 7 / / \ 3 2 6 */ Node root2 = newNode(4); root2.left = newNode(1); root2.right = newNode(7); root2.left.left = newNode(3); root2.right.left = newNode(2); root2.right.right = newNode(6); Node root3 = MergeTrees(root1, root2); System.out.printf("The Merged Binary Tree is:\n"); inorder(root3); }}// This code is contributed by Gaurav Miglani
# Python3 program to Merge Two Binary Trees # Helper class that allocates a new node# with the given data and None left and# right pointers.class newNode: def __init__(self, data): self.data = data self.left = self.right = None # Given a binary tree, prints nodes# in inorderdef inorder(node): if (not node): return # first recur on left child inorder(node.left) # then print the data of node print(node.data, end = " ") # now recur on right child inorder(node.right) # Function to merge given two# binary treesdef MergeTrees(t1, t2): if (not t1): return t2 if (not t2): return t1 t1.data += t2.data t1.left = MergeTrees(t1.left, t2.left) t1.right = MergeTrees(t1.right, t2.right) return t1 # Driver codeif __name__ == '__main__': # Let us construct the first Binary Tree # 1 # / \ # 2 3 # / \ \ # 4 5 6 root1 = newNode(1) root1.left = newNode(2) root1.right = newNode(3) root1.left.left = newNode(4) root1.left.right = newNode(5) root1.right.right = newNode(6) # Let us construct the second Binary Tree # 4 # / \ # 1 7 # / / \ # 3 2 6 root2 = newNode(4) root2.left = newNode(1) root2.right = newNode(7) root2.left.left = newNode(3) root2.right.left = newNode(2) root2.right.right = newNode(6) root3 = MergeTrees(root1, root2) print("The Merged Binary Tree is:") inorder(root3) # This code is contributed by PranchalK
// C# program to Merge Two Binary Treesusing System; /* A binary tree node has data, pointerto left child and a pointer to right child */public class Node{public int data;public Node left, right; public Node(int data, Node left, Node right){ this.data = data; this.left = left; this.right = right;} /* Helper method that allocates a newnode with the given data and NULL leftand right pointers. */public static Node newNode(int data){ return new Node(data, null, null);} /* Given a binary tree, print its nodes in inorder*/public static void preorder(Node node){ if (node == null) { return; } /* then print the data of node */ Console.Write("{0:D} ", node.data); /* first recur on left child */ inorder(node.left); /* now recur on right child */ inorder(node.right);} /* Method to merge given two binary trees*/public static Node MergeTrees(Node t1, Node t2){ if (t1 == null) { return t2; } if (t2 == null) { return t1; } t1.data += t2.data; t1.left = MergeTrees(t1.left, t2.left); t1.right = MergeTrees(t1.right, t2.right); return t1;} // Driver Codepublic static void Main(string[] args){ /* Let us construct the first Binary Tree 1 / \ 2 3 / \ \ 4 5 6 */ Node root1 = newNode(1); root1.left = newNode(2); root1.right = newNode(3); root1.left.left = newNode(4); root1.left.right = newNode(5); root1.right.right = newNode(6); /* Let us construct the second Binary Tree 4 / \ 1 7 / / \ 3 2 6 */ Node root2 = newNode(4); root2.left = newNode(1); root2.right = newNode(7); root2.left.left = newNode(3); root2.right.left = newNode(2); root2.right.right = newNode(6); Node root3 = MergeTrees(root1, root2); Console.Write("The Merged Binary Tree is:\n"); preorder(root3);}} // This code is contributed by Shrikant13
<script> // Javascript program to Merge Two Binary Treesclass Node{ constructor(data) { this.left = null; this.right = null; this.data = data; }} // Helper method that allocates a new// node with the given data and NULL// left and right pointers.function newNode(data){ return new Node(data);} // Given a binary tree, print its// nodes in inorderfunction inorder(node){ if (node == null) return; // First recur on left child inorder(node.left); // Then print the data of node document.write(node.data + " "); // Now recur on right child inorder(node.right);} // Method to merge given two binary treesfunction MergeTrees(t1, t2){ if (t1 == null) return t2; if (t2 == null) return t1; t1.data += t2.data; t1.left = MergeTrees(t1.left, t2.left); t1.right = MergeTrees(t1.right, t2.right); return t1;} // Driver code/* Let us construct the first Binary Tree 1 / \ 2 3 / \ \ 4 5 6 */let root1 = newNode(1);root1.left = newNode(2);root1.right = newNode(3);root1.left.left = newNode(4);root1.left.right = newNode(5);root1.right.right = newNode(6); /* Let us construct the second Binary Tree 4 / \ 1 7 / / \ 3 2 6 */let root2 = newNode(4);root2.left = newNode(1);root2.right = newNode(7);root2.left.left = newNode(3);root2.right.left = newNode(2);root2.right.right = newNode(6); let root3 = MergeTrees(root1, root2);document.write("The Merged Binary Tree is:" + "</br>");inorder(root3); // This code is contributed by divyeshrabadiya07 </script>
Output:
The Merged Binary Tree is:
7 3 5 5 2 10 12
Complexity Analysis:
Time complexity : O(n) A total of n nodes need to be traversed. Here, n represents the minimum number of nodes from the two given trees.
Auxiliary Space : O(n) The depth of the recursion tree can go upto n in case of a skewed tree. In average case, depth will be O(logn).
Iterative Algorithm:
Create a stackPush the root nodes of both the trees onto the stack.While the stack is not empty, perform following steps : Pop a node pair from the top of the stackFor every node pair removed, add the values corresponding to the two nodes and update the value of the corresponding node in the first treeIf the left child of the first tree exists, push the left child(pair) of both the trees onto the stack.If the left child of the first tree doesn’t exist, append the left child of the second tree to the current node of the first treeDo same for right child pair as well.If both the current nodes are NULL, continue with popping the next nodes from the stack.Return root of updated Tree
Create a stack
Push the root nodes of both the trees onto the stack.
While the stack is not empty, perform following steps : Pop a node pair from the top of the stackFor every node pair removed, add the values corresponding to the two nodes and update the value of the corresponding node in the first treeIf the left child of the first tree exists, push the left child(pair) of both the trees onto the stack.If the left child of the first tree doesn’t exist, append the left child of the second tree to the current node of the first treeDo same for right child pair as well.If both the current nodes are NULL, continue with popping the next nodes from the stack.
Pop a node pair from the top of the stackFor every node pair removed, add the values corresponding to the two nodes and update the value of the corresponding node in the first treeIf the left child of the first tree exists, push the left child(pair) of both the trees onto the stack.If the left child of the first tree doesn’t exist, append the left child of the second tree to the current node of the first treeDo same for right child pair as well.If both the current nodes are NULL, continue with popping the next nodes from the stack.
Pop a node pair from the top of the stack
For every node pair removed, add the values corresponding to the two nodes and update the value of the corresponding node in the first tree
If the left child of the first tree exists, push the left child(pair) of both the trees onto the stack.
If the left child of the first tree doesn’t exist, append the left child of the second tree to the current node of the first tree
Do same for right child pair as well.
If both the current nodes are NULL, continue with popping the next nodes from the stack.
Return root of updated Tree
C++
Java
Python3
C#
Javascript
// C++ program to Merge Two Binary Trees#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left childand a pointer to right child */struct Node{ int data; struct Node *left, *right;}; // Structure to store node pair onto stackstruct snode{ Node *l, *r;}; /* Helper function that allocates a new node with thegiven data and NULL left and right pointers. */Node *newNode(int data){ Node *new_node = new Node; new_node->data = data; new_node->left = new_node->right = NULL; return new_node;} /* Given a binary tree, print its nodes in inorder*/void inorder(Node * node){ if (! node) return; /* first recur on left child */ inorder(node->left); /* then print the data of node */ printf("%d ", node->data); /* now recur on right child */ inorder(node->right);} /* Function to merge given two binary trees*/ Node* MergeTrees(Node* t1, Node* t2){ if (! t1) return t2; if (! t2) return t1; stack<snode> s; snode temp; temp.l = t1; temp.r = t2; s.push(temp); snode n; while (! s.empty()) { n = s.top(); s.pop(); if (n.l == NULL|| n.r == NULL) continue; n.l->data += n.r->data; if (n.l->left == NULL) n.l->left = n.r->left; else { snode t; t.l = n.l->left; t.r = n.r->left; s.push(t); } if (n.l->right == NULL) n.l->right = n.r->right; else { snode t; t.l = n.l->right; t.r = n.r->right; s.push(t); } } return t1;} // Driver codeint main(){ /* Let us construct the first Binary Tree 1 / \ 2 3 / \ \ 4 5 6 */ Node *root1 = newNode(1); root1->left = newNode(2); root1->right = newNode(3); root1->left->left = newNode(4); root1->left->right = newNode(5); root1->right->right = newNode(6); /* Let us construct the second Binary Tree 4 / \ 1 7 / / \ 3 2 6 */ Node *root2 = newNode(4); root2->left = newNode(1); root2->right = newNode(7); root2->left->left = newNode(3); root2->right->left = newNode(2); root2->right->right = newNode(6); Node *root3 = MergeTrees(root1, root2); printf("The Merged Binary Tree is:\n"); inorder(root3); return 0;}
// Java program to Merge Two Binary Treesimport java.util.*; class GFG{ /* A binary tree node has data, pointer to left childand a pointer to right child */static class Node{ int data; Node left, right;}; // Structure to store node pair onto stackstatic class snode{ Node l, r;}; /* Helper function that allocates a new node with thegiven data and null left and right pointers. */static Node newNode(int data){ Node new_node = new Node(); new_node.data = data; new_node.left = new_node.right = null; return new_node;} /* Given a binary tree, print its nodes in inorder*/static void inorder(Node node){ if (node == null) return; /* first recur on left child */ inorder(node.left); /* then print the data of node */ System.out.printf("%d ", node.data); /* now recur on right child */ inorder(node.right);} /* Function to merge given two binary trees*/ static Node MergeTrees(Node t1, Node t2){ if ( t1 == null) return t2; if ( t2 == null) return t1; Stack<snode> s = new Stack<>(); snode temp = new snode(); temp.l = t1; temp.r = t2; s.add(temp); snode n; while (! s.isEmpty()) { n = s.peek(); s.pop(); if (n.l == null|| n.r == null) continue; n.l.data += n.r.data; if (n.l.left == null) n.l.left = n.r.left; else { snode t = new snode(); t.l = n.l.left; t.r = n.r.left; s.add(t); } if (n.l.right == null) n.l.right = n.r.right; else { snode t = new snode(); t.l = n.l.right; t.r = n.r.right; s.add(t); } } return t1;} // Driver codepublic static void main(String[] args){ /* Let us construct the first Binary Tree 1 / \ 2 3 / \ \ 4 5 6 */ Node root1 = newNode(1); root1.left = newNode(2); root1.right = newNode(3); root1.left.left = newNode(4); root1.left.right = newNode(5); root1.right.right = newNode(6); /* Let us construct the second Binary Tree 4 / \ 1 7 / / \ 3 2 6 */ Node root2 = newNode(4); root2.left = newNode(1); root2.right = newNode(7); root2.left.left = newNode(3); root2.right.left = newNode(2); root2.right.right = newNode(6); Node root3 = MergeTrees(root1, root2); System.out.printf("The Merged Binary Tree is:\n"); inorder(root3);}} // This code is contributed by gauravrajput1
# Python3 program to Merge Two Binary Trees ''' A binary tree node has data, pointer to left childand a pointer to right child '''class Node: def __init__(self, data): self.data = data self.left = None self.right = None # Structure to store node pair onto stackclass snode: def __init__(self, l, r): self.l = l self.r = r ''' Helper function that allocates a new node with thegiven data and None left and right pointers. '''def newNode(data): new_node = Node(data) return new_node ''' Given a binary tree, print its nodes in inorder'''def inorder(node): if (not node): return; ''' first recur on left child ''' inorder(node.left); ''' then print the data of node ''' print(node.data, end=' '); ''' now recur on right child ''' inorder(node.right); ''' Function to merge given two binary trees''' def MergeTrees(t1, t2): if (not t1): return t2; if (not t2): return t1; s = [] temp = snode(t1, t2) s.append(temp); n = None while (len(s) != 0): n = s[-1] s.pop(); if (n.l == None or n.r == None): continue; n.l.data += n.r.data; if (n.l.left == None): n.l.left = n.r.left; else: t=snode(n.l.left, n.r.left) s.append(t); if (n.l.right == None): n.l.right = n.r.right; else: t=snode(n.l.right, n.r.right) s.append(t); return t1; # Driver codeif __name__=='__main__': ''' Let us construct the first Binary Tree 1 / \ 2 3 / \ \ 4 5 6 ''' root1 = newNode(1); root1.left = newNode(2); root1.right = newNode(3); root1.left.left = newNode(4); root1.left.right = newNode(5); root1.right.right = newNode(6); ''' Let us construct the second Binary Tree 4 / \ 1 7 / / \ 3 2 6 ''' root2 = newNode(4); root2.left = newNode(1); root2.right = newNode(7); root2.left.left = newNode(3); root2.right.left = newNode(2); root2.right.right = newNode(6); root3 = MergeTrees(root1, root2); print("The Merged Binary Tree is:"); inorder(root3); # This code is contributed by rutvik76
// C# program to Merge Two Binary Treesusing System;using System.Collections.Generic; class GFG{ // A binary tree node has data, pointer// to left child and a pointer to right// childpublic class Node{ public int data; public Node left, right;}; // Structure to store node pair onto stackpublic class snode{ public Node l, r;}; // Helper function that allocates a new// node with the given data and null// left and right pointers.static Node newNode(int data){ Node new_node = new Node(); new_node.data = data; new_node.left = new_node.right = null; return new_node;} // Given a binary tree, print its// nodes in inorderstatic void inorder(Node node){ if (node == null) return; // First recur on left child inorder(node.left); // Then print the data of node Console.Write(node.data + " "); // Now recur on right child inorder(node.right);} // Function to merge given two binary treesstatic Node MergeTrees(Node t1, Node t2){ if ( t1 == null) return t2; if ( t2 == null) return t1; Stack<snode> s = new Stack<snode>(); snode temp = new snode(); temp.l = t1; temp.r = t2; s.Push(temp); snode n; while (s.Count != 0) { n = s.Peek(); s.Pop(); if (n.l == null|| n.r == null) continue; n.l.data += n.r.data; if (n.l.left == null) n.l.left = n.r.left; else { snode t = new snode(); t.l = n.l.left; t.r = n.r.left; s.Push(t); } if (n.l.right == null) n.l.right = n.r.right; else { snode t = new snode(); t.l = n.l.right; t.r = n.r.right; s.Push(t); } } return t1;} // Driver codepublic static void Main(String[] args){ /* Let us construct the first Binary Tree 1 / \ 2 3 / \ \ 4 5 6 */ Node root1 = newNode(1); root1.left = newNode(2); root1.right = newNode(3); root1.left.left = newNode(4); root1.left.right = newNode(5); root1.right.right = newNode(6); /* Let us construct the second Binary Tree 4 / \ 1 7 / / \ 3 2 6 */ Node root2 = newNode(4); root2.left = newNode(1); root2.right = newNode(7); root2.left.left = newNode(3); root2.right.left = newNode(2); root2.right.right = newNode(6); Node root3 = MergeTrees(root1, root2); Console.Write("The Merged Binary Tree is:\n"); inorder(root3);}} // This code is contributed by aashish1995
<script> // JavaScript program to Merge Two Binary Trees /* A binary tree node has data, pointer to left childand a pointer to right child */class Node{ constructor() { this.data=0; this.left=this.right=null; }} // Structure to store node pair onto stackclass snode{ constructor() { this.l=null; this.r=null; }} /* Helper function that allocates a new node with thegiven data and null left and right pointers. */function newNode(data){ let new_node = new Node(); new_node.data = data; new_node.left = new_node.right = null; return new_node;} /* Given a binary tree, print its nodes in inorder*/function inorder(node){ if (node == null) return; /* first recur on left child */ inorder(node.left); /* then print the data of node */ document.write(node.data+" "); /* now recur on right child */ inorder(node.right);} /* Function to merge given two binary trees*/function MergeTrees(t1,t2){ if ( t1 == null) return t2; if ( t2 == null) return t1; let s = []; let temp = new snode(); temp.l = t1; temp.r = t2; s.push(temp); let n; while ( s.length!=0) { n = s.pop(); if (n.l == null|| n.r == null) continue; n.l.data += n.r.data; if (n.l.left == null) n.l.left = n.r.left; else { let t = new snode(); t.l = n.l.left; t.r = n.r.left; s.push(t); } if (n.l.right == null) n.l.right = n.r.right; else { let t = new snode(); t.l = n.l.right; t.r = n.r.right; s.push(t); } } return t1;} // Driver code/* Let us construct the first Binary Tree 1 / \ 2 3 / \ \ 4 5 6 */ let root1 = newNode(1);root1.left = newNode(2);root1.right = newNode(3);root1.left.left = newNode(4);root1.left.right = newNode(5);root1.right.right = newNode(6); /* Let us construct second Binary Tree 4 / \ 1 7 / / \ 3 2 6 */let root2 = newNode(4);root2.left = newNode(1);root2.right = newNode(7);root2.left.left = newNode(3);root2.right.left = newNode(2);root2.right.right = newNode(6); let root3 = MergeTrees(root1, root2);document.write("The Merged Binary Tree is:<br>");inorder(root3); // This code is contributed by unknown2108 </script>
Output:
The Merged Binary Tree is:
7 3 5 5 2 10 12
Complexity Analysis:
Time complexity : O(n) A total of n nodes need to be traversed. Here, n represents the minimum number of nodes from the two given trees.
Auxiliary Space : O(n) The depth of the stack can go upto n in case of a skewed tree.
This article is contributed by Aakash Pal. 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.
shrikanth13
PranchalKatiyar
rutvik_56
GauravRajput1
aashish1995
divyeshrabadiya07
sagartomar9927
unknown2108
patel2127
sweetyty
surinderdawra388
mahmoodashqur
rravithejareddy
adityakumar129
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Tree Traversals (Inorder, Preorder and Postorder)
Binary Tree | Set 1 (Introduction)
AVL Tree | Set 1 (Insertion)
Level Order Binary Tree Traversal
Binary Tree | Set 3 (Types of Binary Tree)
Inorder Tree Traversal without Recursion
Write a Program to Find the Maximum Depth or Height of a Tree
Binary Tree | Set 2 (Properties)
Decision Tree
A program to check if a binary tree is BST or not | [
{
"code": null,
"e": 37093,
"s": 37065,
"text": "\n17 Apr, 2022"
},
{
"code": null,
"e": 37336,
"s": 37093,
"text": "Given two binary trees. We need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the non-null node will be used as the node of new tree."
},
{
"code": null,
"e": 37347,
"s": 37336,
"text": "Example: "
},
{
"code": null,
"e": 37757,
"s": 37347,
"text": "Input: \n Tree 1 Tree 2 \n 2 3 \n / \\ / \\ \n 1 4 6 1 \n / \\ \\ \n 5 2 7 \n\nOutput: Merged tree:\n 5\n / \\\n 7 5\n / \\ \\ \n 5 2 7"
},
{
"code": null,
"e": 37831,
"s": 37757,
"text": "Note: The merging process must start from the root nodes of both trees. "
},
{
"code": null,
"e": 37853,
"s": 37831,
"text": "Recursive Algorithm: "
},
{
"code": null,
"e": 38033,
"s": 37853,
"text": "Traverse the tree in Pre-order fashionCheck if both the tree nodes are NULL If not, then update the valueRecur for left subtreesRecur for right subtreesReturn root of updated Tree"
},
{
"code": null,
"e": 38072,
"s": 38033,
"text": "Traverse the tree in Pre-order fashion"
},
{
"code": null,
"e": 38140,
"s": 38072,
"text": "Check if both the tree nodes are NULL If not, then update the value"
},
{
"code": null,
"e": 38170,
"s": 38140,
"text": "If not, then update the value"
},
{
"code": null,
"e": 38200,
"s": 38170,
"text": "If not, then update the value"
},
{
"code": null,
"e": 38224,
"s": 38200,
"text": "Recur for left subtrees"
},
{
"code": null,
"e": 38249,
"s": 38224,
"text": "Recur for right subtrees"
},
{
"code": null,
"e": 38277,
"s": 38249,
"text": "Return root of updated Tree"
},
{
"code": null,
"e": 38281,
"s": 38277,
"text": "C++"
},
{
"code": null,
"e": 38283,
"s": 38281,
"text": "C"
},
{
"code": null,
"e": 38288,
"s": 38283,
"text": "Java"
},
{
"code": null,
"e": 38296,
"s": 38288,
"text": "Python3"
},
{
"code": null,
"e": 38299,
"s": 38296,
"text": "C#"
},
{
"code": null,
"e": 38310,
"s": 38299,
"text": "Javascript"
},
{
"code": "// C++ program to Merge Two Binary Trees#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */struct Node{ int data; struct Node *left, *right;}; /* Helper function that allocates a new node with the given data and NULL left and right pointers. */Node *newNode(int data){ Node *new_node = new Node; new_node->data = data; new_node->left = new_node->right = NULL; return new_node;} /* Given a binary tree, print its nodes in inorder*/void inorder(Node * node){ if (!node) return; /* first recur on left child */ inorder(node->left); /* then print the data of node */ cout<<node->data<<\" \"; /* now recur on right child */ inorder(node->right);} /* Function to merge given two binary trees*/Node *MergeTrees(Node * t1, Node * t2){ if (!t1) return t2; if (!t2) return t1; t1->data += t2->data; t1->left = MergeTrees(t1->left, t2->left); t1->right = MergeTrees(t1->right, t2->right); return t1;} // Driver codeint main(){ /* Let us construct the first Binary Tree 1 / \\ 2 3 / \\ \\ 4 5 6 */ Node *root1 = newNode(1); root1->left = newNode(2); root1->right = newNode(3); root1->left->left = newNode(4); root1->left->right = newNode(5); root1->right->right = newNode(6); /* Let us construct the second Binary Tree 4 / \\ 1 7 / / \\ 3 2 6 */ Node *root2 = newNode(4); root2->left = newNode(1); root2->right = newNode(7); root2->left->left = newNode(3); root2->right->left = newNode(2); root2->right->right = newNode(6); Node *root3 = MergeTrees(root1, root2); printf(\"The Merged Binary Tree is:\\n\"); inorder(root3); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 40217,
"s": 38310,
"text": null
},
{
"code": "// C program to Merge Two Binary Trees #include<stdio.h>#include<stdlib.h> /* A binary tree node has data, pointer to left child and a pointer to right child */typedef struct Node{ int data; struct Node *left, *right;}Node; /* Helper function that allocates a new node with the given data and NULL left and right pointers. */Node *newNode(int data){ Node *new_node = (Node *)malloc(sizeof(Node)); new_node->data = data; new_node->left = new_node->right = NULL; return new_node;} /* Given a binary tree, print its nodes in inorder*/void inorder(Node * node){ if (!node) return; /* first recur on left child */ inorder(node->left); /* then print the data of node */ printf(\"%d \", node->data); /* now recur on right child */ inorder(node->right);} /* Function to merge given two binary trees*/Node *MergeTrees(Node * t1, Node * t2){ if (!t1) return t2; if (!t2) return t1; t1->data += t2->data; t1->left = MergeTrees(t1->left, t2->left); t1->right = MergeTrees(t1->right, t2->right); return t1;} // Driver codeint main(){ /* Let us construct the first Binary Tree 1 / \\ 2 3 / \\ \\ 4 5 6 */ Node *root1 = newNode(1); root1->left = newNode(2); root1->right = newNode(3); root1->left->left = newNode(4); root1->left->right = newNode(5); root1->right->right = newNode(6); /* Let us construct the second Binary Tree 4 / \\ 1 7 / / \\ 3 2 6 */ Node *root2 = newNode(4); root2->left = newNode(1); root2->right = newNode(7); root2->left->left = newNode(3); root2->right->left = newNode(2); root2->right->right = newNode(6); Node *root3 = MergeTrees(root1, root2); printf(\"The Merged Binary Tree is:\\n\"); inorder(root3); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 42150,
"s": 40217,
"text": null
},
{
"code": "// Java program to Merge Two Binary Trees /* A binary tree node has data, pointer to left child and a pointer to right child */class Node{ int data; Node left, right; public Node(int data, Node left, Node right) { this.data = data; this.left = left; this.right = right; } /* Helper method that allocates a new node with the given data and NULL left and right pointers. */ static Node newNode(int data) { return new Node(data, null, null); } /* Given a binary tree, print its nodes in inorder*/ static void inorder(Node node) { if (node == null) return; /* first recur on left child */ inorder(node.left); /* then print the data of node */ System.out.printf(\"%d \", node.data); /* now recur on right child */ inorder(node.right); } /* Method to merge given two binary trees*/ static Node MergeTrees(Node t1, Node t2) { if (t1 == null) return t2; if (t2 == null) return t1; t1.data += t2.data; t1.left = MergeTrees(t1.left, t2.left); t1.right = MergeTrees(t1.right, t2.right); return t1; } // Driver method public static void main(String[] args) { /* Let us construct the first Binary Tree 1 / \\ 2 3 / \\ \\ 4 5 6 */ Node root1 = newNode(1); root1.left = newNode(2); root1.right = newNode(3); root1.left.left = newNode(4); root1.left.right = newNode(5); root1.right.right = newNode(6); /* Let us construct the second Binary Tree 4 / \\ 1 7 / / \\ 3 2 6 */ Node root2 = newNode(4); root2.left = newNode(1); root2.right = newNode(7); root2.left.left = newNode(3); root2.right.left = newNode(2); root2.right.right = newNode(6); Node root3 = MergeTrees(root1, root2); System.out.printf(\"The Merged Binary Tree is:\\n\"); inorder(root3); }}// This code is contributed by Gaurav Miglani",
"e": 44450,
"s": 42150,
"text": null
},
{
"code": "# Python3 program to Merge Two Binary Trees # Helper class that allocates a new node# with the given data and None left and# right pointers.class newNode: def __init__(self, data): self.data = data self.left = self.right = None # Given a binary tree, prints nodes# in inorderdef inorder(node): if (not node): return # first recur on left child inorder(node.left) # then print the data of node print(node.data, end = \" \") # now recur on right child inorder(node.right) # Function to merge given two# binary treesdef MergeTrees(t1, t2): if (not t1): return t2 if (not t2): return t1 t1.data += t2.data t1.left = MergeTrees(t1.left, t2.left) t1.right = MergeTrees(t1.right, t2.right) return t1 # Driver codeif __name__ == '__main__': # Let us construct the first Binary Tree # 1 # / \\ # 2 3 # / \\ \\ # 4 5 6 root1 = newNode(1) root1.left = newNode(2) root1.right = newNode(3) root1.left.left = newNode(4) root1.left.right = newNode(5) root1.right.right = newNode(6) # Let us construct the second Binary Tree # 4 # / \\ # 1 7 # / / \\ # 3 2 6 root2 = newNode(4) root2.left = newNode(1) root2.right = newNode(7) root2.left.left = newNode(3) root2.right.left = newNode(2) root2.right.right = newNode(6) root3 = MergeTrees(root1, root2) print(\"The Merged Binary Tree is:\") inorder(root3) # This code is contributed by PranchalK",
"e": 45980,
"s": 44450,
"text": null
},
{
"code": "// C# program to Merge Two Binary Treesusing System; /* A binary tree node has data, pointerto left child and a pointer to right child */public class Node{public int data;public Node left, right; public Node(int data, Node left, Node right){ this.data = data; this.left = left; this.right = right;} /* Helper method that allocates a newnode with the given data and NULL leftand right pointers. */public static Node newNode(int data){ return new Node(data, null, null);} /* Given a binary tree, print its nodes in inorder*/public static void preorder(Node node){ if (node == null) { return; } /* then print the data of node */ Console.Write(\"{0:D} \", node.data); /* first recur on left child */ inorder(node.left); /* now recur on right child */ inorder(node.right);} /* Method to merge given two binary trees*/public static Node MergeTrees(Node t1, Node t2){ if (t1 == null) { return t2; } if (t2 == null) { return t1; } t1.data += t2.data; t1.left = MergeTrees(t1.left, t2.left); t1.right = MergeTrees(t1.right, t2.right); return t1;} // Driver Codepublic static void Main(string[] args){ /* Let us construct the first Binary Tree 1 / \\ 2 3 / \\ \\ 4 5 6 */ Node root1 = newNode(1); root1.left = newNode(2); root1.right = newNode(3); root1.left.left = newNode(4); root1.left.right = newNode(5); root1.right.right = newNode(6); /* Let us construct the second Binary Tree 4 / \\ 1 7 / / \\ 3 2 6 */ Node root2 = newNode(4); root2.left = newNode(1); root2.right = newNode(7); root2.left.left = newNode(3); root2.right.left = newNode(2); root2.right.right = newNode(6); Node root3 = MergeTrees(root1, root2); Console.Write(\"The Merged Binary Tree is:\\n\"); preorder(root3);}} // This code is contributed by Shrikant13",
"e": 47963,
"s": 45980,
"text": null
},
{
"code": "<script> // Javascript program to Merge Two Binary Treesclass Node{ constructor(data) { this.left = null; this.right = null; this.data = data; }} // Helper method that allocates a new// node with the given data and NULL// left and right pointers.function newNode(data){ return new Node(data);} // Given a binary tree, print its// nodes in inorderfunction inorder(node){ if (node == null) return; // First recur on left child inorder(node.left); // Then print the data of node document.write(node.data + \" \"); // Now recur on right child inorder(node.right);} // Method to merge given two binary treesfunction MergeTrees(t1, t2){ if (t1 == null) return t2; if (t2 == null) return t1; t1.data += t2.data; t1.left = MergeTrees(t1.left, t2.left); t1.right = MergeTrees(t1.right, t2.right); return t1;} // Driver code/* Let us construct the first Binary Tree 1 / \\ 2 3 / \\ \\ 4 5 6 */let root1 = newNode(1);root1.left = newNode(2);root1.right = newNode(3);root1.left.left = newNode(4);root1.left.right = newNode(5);root1.right.right = newNode(6); /* Let us construct the second Binary Tree 4 / \\ 1 7 / / \\ 3 2 6 */let root2 = newNode(4);root2.left = newNode(1);root2.right = newNode(7);root2.left.left = newNode(3);root2.right.left = newNode(2);root2.right.right = newNode(6); let root3 = MergeTrees(root1, root2);document.write(\"The Merged Binary Tree is:\" + \"</br>\");inorder(root3); // This code is contributed by divyeshrabadiya07 </script>",
"e": 49657,
"s": 47963,
"text": null
},
{
"code": null,
"e": 49666,
"s": 49657,
"text": "Output: "
},
{
"code": null,
"e": 49709,
"s": 49666,
"text": "The Merged Binary Tree is:\n7 3 5 5 2 10 12"
},
{
"code": null,
"e": 49731,
"s": 49709,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 49868,
"s": 49731,
"text": "Time complexity : O(n) A total of n nodes need to be traversed. Here, n represents the minimum number of nodes from the two given trees."
},
{
"code": null,
"e": 50003,
"s": 49868,
"text": "Auxiliary Space : O(n) The depth of the recursion tree can go upto n in case of a skewed tree. In average case, depth will be O(logn)."
},
{
"code": null,
"e": 50024,
"s": 50003,
"text": "Iterative Algorithm:"
},
{
"code": null,
"e": 50712,
"s": 50024,
"text": "Create a stackPush the root nodes of both the trees onto the stack.While the stack is not empty, perform following steps : Pop a node pair from the top of the stackFor every node pair removed, add the values corresponding to the two nodes and update the value of the corresponding node in the first treeIf the left child of the first tree exists, push the left child(pair) of both the trees onto the stack.If the left child of the first tree doesn’t exist, append the left child of the second tree to the current node of the first treeDo same for right child pair as well.If both the current nodes are NULL, continue with popping the next nodes from the stack.Return root of updated Tree"
},
{
"code": null,
"e": 50727,
"s": 50712,
"text": "Create a stack"
},
{
"code": null,
"e": 50781,
"s": 50727,
"text": "Push the root nodes of both the trees onto the stack."
},
{
"code": null,
"e": 51375,
"s": 50781,
"text": "While the stack is not empty, perform following steps : Pop a node pair from the top of the stackFor every node pair removed, add the values corresponding to the two nodes and update the value of the corresponding node in the first treeIf the left child of the first tree exists, push the left child(pair) of both the trees onto the stack.If the left child of the first tree doesn’t exist, append the left child of the second tree to the current node of the first treeDo same for right child pair as well.If both the current nodes are NULL, continue with popping the next nodes from the stack."
},
{
"code": null,
"e": 51913,
"s": 51375,
"text": "Pop a node pair from the top of the stackFor every node pair removed, add the values corresponding to the two nodes and update the value of the corresponding node in the first treeIf the left child of the first tree exists, push the left child(pair) of both the trees onto the stack.If the left child of the first tree doesn’t exist, append the left child of the second tree to the current node of the first treeDo same for right child pair as well.If both the current nodes are NULL, continue with popping the next nodes from the stack."
},
{
"code": null,
"e": 51955,
"s": 51913,
"text": "Pop a node pair from the top of the stack"
},
{
"code": null,
"e": 52095,
"s": 51955,
"text": "For every node pair removed, add the values corresponding to the two nodes and update the value of the corresponding node in the first tree"
},
{
"code": null,
"e": 52199,
"s": 52095,
"text": "If the left child of the first tree exists, push the left child(pair) of both the trees onto the stack."
},
{
"code": null,
"e": 52329,
"s": 52199,
"text": "If the left child of the first tree doesn’t exist, append the left child of the second tree to the current node of the first tree"
},
{
"code": null,
"e": 52367,
"s": 52329,
"text": "Do same for right child pair as well."
},
{
"code": null,
"e": 52456,
"s": 52367,
"text": "If both the current nodes are NULL, continue with popping the next nodes from the stack."
},
{
"code": null,
"e": 52484,
"s": 52456,
"text": "Return root of updated Tree"
},
{
"code": null,
"e": 52488,
"s": 52484,
"text": "C++"
},
{
"code": null,
"e": 52493,
"s": 52488,
"text": "Java"
},
{
"code": null,
"e": 52501,
"s": 52493,
"text": "Python3"
},
{
"code": null,
"e": 52504,
"s": 52501,
"text": "C#"
},
{
"code": null,
"e": 52515,
"s": 52504,
"text": "Javascript"
},
{
"code": "// C++ program to Merge Two Binary Trees#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left childand a pointer to right child */struct Node{ int data; struct Node *left, *right;}; // Structure to store node pair onto stackstruct snode{ Node *l, *r;}; /* Helper function that allocates a new node with thegiven data and NULL left and right pointers. */Node *newNode(int data){ Node *new_node = new Node; new_node->data = data; new_node->left = new_node->right = NULL; return new_node;} /* Given a binary tree, print its nodes in inorder*/void inorder(Node * node){ if (! node) return; /* first recur on left child */ inorder(node->left); /* then print the data of node */ printf(\"%d \", node->data); /* now recur on right child */ inorder(node->right);} /* Function to merge given two binary trees*/ Node* MergeTrees(Node* t1, Node* t2){ if (! t1) return t2; if (! t2) return t1; stack<snode> s; snode temp; temp.l = t1; temp.r = t2; s.push(temp); snode n; while (! s.empty()) { n = s.top(); s.pop(); if (n.l == NULL|| n.r == NULL) continue; n.l->data += n.r->data; if (n.l->left == NULL) n.l->left = n.r->left; else { snode t; t.l = n.l->left; t.r = n.r->left; s.push(t); } if (n.l->right == NULL) n.l->right = n.r->right; else { snode t; t.l = n.l->right; t.r = n.r->right; s.push(t); } } return t1;} // Driver codeint main(){ /* Let us construct the first Binary Tree 1 / \\ 2 3 / \\ \\ 4 5 6 */ Node *root1 = newNode(1); root1->left = newNode(2); root1->right = newNode(3); root1->left->left = newNode(4); root1->left->right = newNode(5); root1->right->right = newNode(6); /* Let us construct the second Binary Tree 4 / \\ 1 7 / / \\ 3 2 6 */ Node *root2 = newNode(4); root2->left = newNode(1); root2->right = newNode(7); root2->left->left = newNode(3); root2->right->left = newNode(2); root2->right->right = newNode(6); Node *root3 = MergeTrees(root1, root2); printf(\"The Merged Binary Tree is:\\n\"); inorder(root3); return 0;}",
"e": 54964,
"s": 52515,
"text": null
},
{
"code": "// Java program to Merge Two Binary Treesimport java.util.*; class GFG{ /* A binary tree node has data, pointer to left childand a pointer to right child */static class Node{ int data; Node left, right;}; // Structure to store node pair onto stackstatic class snode{ Node l, r;}; /* Helper function that allocates a new node with thegiven data and null left and right pointers. */static Node newNode(int data){ Node new_node = new Node(); new_node.data = data; new_node.left = new_node.right = null; return new_node;} /* Given a binary tree, print its nodes in inorder*/static void inorder(Node node){ if (node == null) return; /* first recur on left child */ inorder(node.left); /* then print the data of node */ System.out.printf(\"%d \", node.data); /* now recur on right child */ inorder(node.right);} /* Function to merge given two binary trees*/ static Node MergeTrees(Node t1, Node t2){ if ( t1 == null) return t2; if ( t2 == null) return t1; Stack<snode> s = new Stack<>(); snode temp = new snode(); temp.l = t1; temp.r = t2; s.add(temp); snode n; while (! s.isEmpty()) { n = s.peek(); s.pop(); if (n.l == null|| n.r == null) continue; n.l.data += n.r.data; if (n.l.left == null) n.l.left = n.r.left; else { snode t = new snode(); t.l = n.l.left; t.r = n.r.left; s.add(t); } if (n.l.right == null) n.l.right = n.r.right; else { snode t = new snode(); t.l = n.l.right; t.r = n.r.right; s.add(t); } } return t1;} // Driver codepublic static void main(String[] args){ /* Let us construct the first Binary Tree 1 / \\ 2 3 / \\ \\ 4 5 6 */ Node root1 = newNode(1); root1.left = newNode(2); root1.right = newNode(3); root1.left.left = newNode(4); root1.left.right = newNode(5); root1.right.right = newNode(6); /* Let us construct the second Binary Tree 4 / \\ 1 7 / / \\ 3 2 6 */ Node root2 = newNode(4); root2.left = newNode(1); root2.right = newNode(7); root2.left.left = newNode(3); root2.right.left = newNode(2); root2.right.right = newNode(6); Node root3 = MergeTrees(root1, root2); System.out.printf(\"The Merged Binary Tree is:\\n\"); inorder(root3);}} // This code is contributed by gauravrajput1",
"e": 57542,
"s": 54964,
"text": null
},
{
"code": "# Python3 program to Merge Two Binary Trees ''' A binary tree node has data, pointer to left childand a pointer to right child '''class Node: def __init__(self, data): self.data = data self.left = None self.right = None # Structure to store node pair onto stackclass snode: def __init__(self, l, r): self.l = l self.r = r ''' Helper function that allocates a new node with thegiven data and None left and right pointers. '''def newNode(data): new_node = Node(data) return new_node ''' Given a binary tree, print its nodes in inorder'''def inorder(node): if (not node): return; ''' first recur on left child ''' inorder(node.left); ''' then print the data of node ''' print(node.data, end=' '); ''' now recur on right child ''' inorder(node.right); ''' Function to merge given two binary trees''' def MergeTrees(t1, t2): if (not t1): return t2; if (not t2): return t1; s = [] temp = snode(t1, t2) s.append(temp); n = None while (len(s) != 0): n = s[-1] s.pop(); if (n.l == None or n.r == None): continue; n.l.data += n.r.data; if (n.l.left == None): n.l.left = n.r.left; else: t=snode(n.l.left, n.r.left) s.append(t); if (n.l.right == None): n.l.right = n.r.right; else: t=snode(n.l.right, n.r.right) s.append(t); return t1; # Driver codeif __name__=='__main__': ''' Let us construct the first Binary Tree 1 / \\ 2 3 / \\ \\ 4 5 6 ''' root1 = newNode(1); root1.left = newNode(2); root1.right = newNode(3); root1.left.left = newNode(4); root1.left.right = newNode(5); root1.right.right = newNode(6); ''' Let us construct the second Binary Tree 4 / \\ 1 7 / / \\ 3 2 6 ''' root2 = newNode(4); root2.left = newNode(1); root2.right = newNode(7); root2.left.left = newNode(3); root2.right.left = newNode(2); root2.right.right = newNode(6); root3 = MergeTrees(root1, root2); print(\"The Merged Binary Tree is:\"); inorder(root3); # This code is contributed by rutvik76",
"e": 59948,
"s": 57542,
"text": null
},
{
"code": "// C# program to Merge Two Binary Treesusing System;using System.Collections.Generic; class GFG{ // A binary tree node has data, pointer// to left child and a pointer to right// childpublic class Node{ public int data; public Node left, right;}; // Structure to store node pair onto stackpublic class snode{ public Node l, r;}; // Helper function that allocates a new// node with the given data and null// left and right pointers.static Node newNode(int data){ Node new_node = new Node(); new_node.data = data; new_node.left = new_node.right = null; return new_node;} // Given a binary tree, print its// nodes in inorderstatic void inorder(Node node){ if (node == null) return; // First recur on left child inorder(node.left); // Then print the data of node Console.Write(node.data + \" \"); // Now recur on right child inorder(node.right);} // Function to merge given two binary treesstatic Node MergeTrees(Node t1, Node t2){ if ( t1 == null) return t2; if ( t2 == null) return t1; Stack<snode> s = new Stack<snode>(); snode temp = new snode(); temp.l = t1; temp.r = t2; s.Push(temp); snode n; while (s.Count != 0) { n = s.Peek(); s.Pop(); if (n.l == null|| n.r == null) continue; n.l.data += n.r.data; if (n.l.left == null) n.l.left = n.r.left; else { snode t = new snode(); t.l = n.l.left; t.r = n.r.left; s.Push(t); } if (n.l.right == null) n.l.right = n.r.right; else { snode t = new snode(); t.l = n.l.right; t.r = n.r.right; s.Push(t); } } return t1;} // Driver codepublic static void Main(String[] args){ /* Let us construct the first Binary Tree 1 / \\ 2 3 / \\ \\ 4 5 6 */ Node root1 = newNode(1); root1.left = newNode(2); root1.right = newNode(3); root1.left.left = newNode(4); root1.left.right = newNode(5); root1.right.right = newNode(6); /* Let us construct the second Binary Tree 4 / \\ 1 7 / / \\ 3 2 6 */ Node root2 = newNode(4); root2.left = newNode(1); root2.right = newNode(7); root2.left.left = newNode(3); root2.right.left = newNode(2); root2.right.right = newNode(6); Node root3 = MergeTrees(root1, root2); Console.Write(\"The Merged Binary Tree is:\\n\"); inorder(root3);}} // This code is contributed by aashish1995",
"e": 62622,
"s": 59948,
"text": null
},
{
"code": "<script> // JavaScript program to Merge Two Binary Trees /* A binary tree node has data, pointer to left childand a pointer to right child */class Node{ constructor() { this.data=0; this.left=this.right=null; }} // Structure to store node pair onto stackclass snode{ constructor() { this.l=null; this.r=null; }} /* Helper function that allocates a new node with thegiven data and null left and right pointers. */function newNode(data){ let new_node = new Node(); new_node.data = data; new_node.left = new_node.right = null; return new_node;} /* Given a binary tree, print its nodes in inorder*/function inorder(node){ if (node == null) return; /* first recur on left child */ inorder(node.left); /* then print the data of node */ document.write(node.data+\" \"); /* now recur on right child */ inorder(node.right);} /* Function to merge given two binary trees*/function MergeTrees(t1,t2){ if ( t1 == null) return t2; if ( t2 == null) return t1; let s = []; let temp = new snode(); temp.l = t1; temp.r = t2; s.push(temp); let n; while ( s.length!=0) { n = s.pop(); if (n.l == null|| n.r == null) continue; n.l.data += n.r.data; if (n.l.left == null) n.l.left = n.r.left; else { let t = new snode(); t.l = n.l.left; t.r = n.r.left; s.push(t); } if (n.l.right == null) n.l.right = n.r.right; else { let t = new snode(); t.l = n.l.right; t.r = n.r.right; s.push(t); } } return t1;} // Driver code/* Let us construct the first Binary Tree 1 / \\ 2 3 / \\ \\ 4 5 6 */ let root1 = newNode(1);root1.left = newNode(2);root1.right = newNode(3);root1.left.left = newNode(4);root1.left.right = newNode(5);root1.right.right = newNode(6); /* Let us construct second Binary Tree 4 / \\ 1 7 / / \\ 3 2 6 */let root2 = newNode(4);root2.left = newNode(1);root2.right = newNode(7);root2.left.left = newNode(3);root2.right.left = newNode(2);root2.right.right = newNode(6); let root3 = MergeTrees(root1, root2);document.write(\"The Merged Binary Tree is:<br>\");inorder(root3); // This code is contributed by unknown2108 </script>",
"e": 65108,
"s": 62622,
"text": null
},
{
"code": null,
"e": 65117,
"s": 65108,
"text": "Output: "
},
{
"code": null,
"e": 65160,
"s": 65117,
"text": "The Merged Binary Tree is:\n7 3 5 5 2 10 12"
},
{
"code": null,
"e": 65183,
"s": 65160,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 65320,
"s": 65183,
"text": "Time complexity : O(n) A total of n nodes need to be traversed. Here, n represents the minimum number of nodes from the two given trees."
},
{
"code": null,
"e": 65406,
"s": 65320,
"text": "Auxiliary Space : O(n) The depth of the stack can go upto n in case of a skewed tree."
},
{
"code": null,
"e": 65825,
"s": 65406,
"text": "This article is contributed by Aakash Pal. 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": 65837,
"s": 65825,
"text": "shrikanth13"
},
{
"code": null,
"e": 65853,
"s": 65837,
"text": "PranchalKatiyar"
},
{
"code": null,
"e": 65863,
"s": 65853,
"text": "rutvik_56"
},
{
"code": null,
"e": 65877,
"s": 65863,
"text": "GauravRajput1"
},
{
"code": null,
"e": 65889,
"s": 65877,
"text": "aashish1995"
},
{
"code": null,
"e": 65907,
"s": 65889,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 65922,
"s": 65907,
"text": "sagartomar9927"
},
{
"code": null,
"e": 65934,
"s": 65922,
"text": "unknown2108"
},
{
"code": null,
"e": 65944,
"s": 65934,
"text": "patel2127"
},
{
"code": null,
"e": 65953,
"s": 65944,
"text": "sweetyty"
},
{
"code": null,
"e": 65970,
"s": 65953,
"text": "surinderdawra388"
},
{
"code": null,
"e": 65984,
"s": 65970,
"text": "mahmoodashqur"
},
{
"code": null,
"e": 66000,
"s": 65984,
"text": "rravithejareddy"
},
{
"code": null,
"e": 66015,
"s": 66000,
"text": "adityakumar129"
},
{
"code": null,
"e": 66020,
"s": 66015,
"text": "Tree"
},
{
"code": null,
"e": 66025,
"s": 66020,
"text": "Tree"
},
{
"code": null,
"e": 66123,
"s": 66025,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 66173,
"s": 66123,
"text": "Tree Traversals (Inorder, Preorder and Postorder)"
},
{
"code": null,
"e": 66208,
"s": 66173,
"text": "Binary Tree | Set 1 (Introduction)"
},
{
"code": null,
"e": 66237,
"s": 66208,
"text": "AVL Tree | Set 1 (Insertion)"
},
{
"code": null,
"e": 66271,
"s": 66237,
"text": "Level Order Binary Tree Traversal"
},
{
"code": null,
"e": 66314,
"s": 66271,
"text": "Binary Tree | Set 3 (Types of Binary Tree)"
},
{
"code": null,
"e": 66355,
"s": 66314,
"text": "Inorder Tree Traversal without Recursion"
},
{
"code": null,
"e": 66417,
"s": 66355,
"text": "Write a Program to Find the Maximum Depth or Height of a Tree"
},
{
"code": null,
"e": 66450,
"s": 66417,
"text": "Binary Tree | Set 2 (Properties)"
},
{
"code": null,
"e": 66464,
"s": 66450,
"text": "Decision Tree"
}
] |
Introduction to SQLite - GeeksforGeeks | 10 May, 2019
SQLite is a self-contained, high-reliability, embedded, full-featured, public-domain, SQL database engine. It is the most used database engine in the world. It is an in-process library and its code is publicly available. It is free for use for any purpose, commercial or private. It is basically an embedded SQL database engine. Ordinary disk files can be easily read and write by SQLite because it does not have any separate server like SQL. The SQLite database file format is cross-platform so that anyone can easily copy a database between 32-bit and 64-bit systems. Due to all these features, it is a popular choice as an Application File Format.
History:It was designed by D. Richard Hipp for the purpose of no administration required for operating a program. in August 2000. As it is very lightweight compared to others like MySql and Oracle, it is called SQLite. Different versions of SQLite are released since 2000.
Installation on Windows:1. Visit the official website of SQLite for downloading the zip file.2. Download that zip file.3. Create a folder in C or D ( wherever you want ) for storing SQLite by expanding zip file.4. Open the command prompt and set the path for the location of SQLite folder given in the previous step. After that write “sqlite3” and press enter.
You can also directly open the .exe file from the folder where you have stored the SQLite whole thing.After clicking on the selected .exe file it will open SQLite application
Installation on Linux:
Open Terminal, type this command and enter password
sudo apt-get install sqlite3 libsqlite3-dev
It will automatically install and once it asks Do you want to continue (Y/N) type Y and press enter. After successful installation, we can check it by command sqlite3.
Features of SQLite
The transactions follow ACID properties i.e. atomicity, consistency, isolation, and durability even after system crashes and power failures.The configuration process is very easy, no setup or administration needed.All the features of SQL are implemented in it with some additional features like partial indexes, indexes on expressions, JSON, and common table expressions.Sometimes it is faster than the direct file system I/O.It supports terabyte-sized databases and gigabyte-sized strings and blobs.Almost all OS supports SQLite like Android, BSD, iOS, Linux, Mac, Solaris, VxWorks, and Windows (Win32, WinCE, etc. It is very much easy to port to other systems.Complete database can be stored in a single cross-platform disk file.
The transactions follow ACID properties i.e. atomicity, consistency, isolation, and durability even after system crashes and power failures.
The configuration process is very easy, no setup or administration needed.
All the features of SQL are implemented in it with some additional features like partial indexes, indexes on expressions, JSON, and common table expressions.
Sometimes it is faster than the direct file system I/O.
It supports terabyte-sized databases and gigabyte-sized strings and blobs.
Almost all OS supports SQLite like Android, BSD, iOS, Linux, Mac, Solaris, VxWorks, and Windows (Win32, WinCE, etc. It is very much easy to port to other systems.
Complete database can be stored in a single cross-platform disk file.
Applications of SQLite
Due to its small code print and efficient usage of memory, it is the popular choice for the database engine in cellphones, PDAs, MP3 players, set-top boxes, and other electronic gadgets.It is used as an alternative for open to writing XML, JSON, CSV or some proprietary format into disk files used by the application.As it has no complication for configuration and easily stores file in an ordinary disk file, so it can be used as a database for small to medium sized websites.It is faster and accessible through a wide variety of third-party tools, so it has great application in different software platforms.
Due to its small code print and efficient usage of memory, it is the popular choice for the database engine in cellphones, PDAs, MP3 players, set-top boxes, and other electronic gadgets.
It is used as an alternative for open to writing XML, JSON, CSV or some proprietary format into disk files used by the application.
As it has no complication for configuration and easily stores file in an ordinary disk file, so it can be used as a database for small to medium sized websites.
It is faster and accessible through a wide variety of third-party tools, so it has great application in different software platforms.
SQLite CommandsIn SQLite, there are several dot commands which do not end with a semicolon(;). Here are all commands and their description:
Some DDL and DML CommandsIt is same as compared to previous technology like MySQL, Oracle.
Creating Table:CREATE TABLE STUDENT(ID INT PRIMARY KEY NOT NULL,NAME TEXT NOT NULL,AGE INT NOT NULL,ADDRESS CHAR(50),FEES REAL);
Insert Command:INSERT INTO STUDENT (ID, NAME, AGE, ADDRESS, FEES)VALUES (1, 'Sunil', 28, 'Mumbai', 20000.00);
Drop Table:Drop Table Student;
Disadvantages of SQLite
It is only used where there is low to medium traffic requests are there.
The database size is restricted i.e. it is 2GB in most cases.
References :https://www.sqlite.org/index.htmlhttps://www.javatpoint.com
sanskar27jain
ManasChhabra2
SQL
Technical Scripter
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Interview Questions
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
Difference between SQL and NoSQL
Difference between DELETE, DROP and TRUNCATE
MySQL | Group_CONCAT() Function
Difference between DELETE and TRUNCATE
SQL | Subquery
How to Create a Table With Multiple Foreign Keys in SQL?
What is Temporary Table in SQL? | [
{
"code": null,
"e": 25983,
"s": 25955,
"text": "\n10 May, 2019"
},
{
"code": null,
"e": 26634,
"s": 25983,
"text": "SQLite is a self-contained, high-reliability, embedded, full-featured, public-domain, SQL database engine. It is the most used database engine in the world. It is an in-process library and its code is publicly available. It is free for use for any purpose, commercial or private. It is basically an embedded SQL database engine. Ordinary disk files can be easily read and write by SQLite because it does not have any separate server like SQL. The SQLite database file format is cross-platform so that anyone can easily copy a database between 32-bit and 64-bit systems. Due to all these features, it is a popular choice as an Application File Format."
},
{
"code": null,
"e": 26907,
"s": 26634,
"text": "History:It was designed by D. Richard Hipp for the purpose of no administration required for operating a program. in August 2000. As it is very lightweight compared to others like MySql and Oracle, it is called SQLite. Different versions of SQLite are released since 2000."
},
{
"code": null,
"e": 27268,
"s": 26907,
"text": "Installation on Windows:1. Visit the official website of SQLite for downloading the zip file.2. Download that zip file.3. Create a folder in C or D ( wherever you want ) for storing SQLite by expanding zip file.4. Open the command prompt and set the path for the location of SQLite folder given in the previous step. After that write “sqlite3” and press enter."
},
{
"code": null,
"e": 27443,
"s": 27268,
"text": "You can also directly open the .exe file from the folder where you have stored the SQLite whole thing.After clicking on the selected .exe file it will open SQLite application"
},
{
"code": null,
"e": 27466,
"s": 27443,
"text": "Installation on Linux:"
},
{
"code": null,
"e": 27518,
"s": 27466,
"text": "Open Terminal, type this command and enter password"
},
{
"code": null,
"e": 27562,
"s": 27518,
"text": "sudo apt-get install sqlite3 libsqlite3-dev"
},
{
"code": null,
"e": 27730,
"s": 27562,
"text": "It will automatically install and once it asks Do you want to continue (Y/N) type Y and press enter. After successful installation, we can check it by command sqlite3."
},
{
"code": null,
"e": 27749,
"s": 27730,
"text": "Features of SQLite"
},
{
"code": null,
"e": 28481,
"s": 27749,
"text": "The transactions follow ACID properties i.e. atomicity, consistency, isolation, and durability even after system crashes and power failures.The configuration process is very easy, no setup or administration needed.All the features of SQL are implemented in it with some additional features like partial indexes, indexes on expressions, JSON, and common table expressions.Sometimes it is faster than the direct file system I/O.It supports terabyte-sized databases and gigabyte-sized strings and blobs.Almost all OS supports SQLite like Android, BSD, iOS, Linux, Mac, Solaris, VxWorks, and Windows (Win32, WinCE, etc. It is very much easy to port to other systems.Complete database can be stored in a single cross-platform disk file."
},
{
"code": null,
"e": 28622,
"s": 28481,
"text": "The transactions follow ACID properties i.e. atomicity, consistency, isolation, and durability even after system crashes and power failures."
},
{
"code": null,
"e": 28697,
"s": 28622,
"text": "The configuration process is very easy, no setup or administration needed."
},
{
"code": null,
"e": 28855,
"s": 28697,
"text": "All the features of SQL are implemented in it with some additional features like partial indexes, indexes on expressions, JSON, and common table expressions."
},
{
"code": null,
"e": 28911,
"s": 28855,
"text": "Sometimes it is faster than the direct file system I/O."
},
{
"code": null,
"e": 28986,
"s": 28911,
"text": "It supports terabyte-sized databases and gigabyte-sized strings and blobs."
},
{
"code": null,
"e": 29149,
"s": 28986,
"text": "Almost all OS supports SQLite like Android, BSD, iOS, Linux, Mac, Solaris, VxWorks, and Windows (Win32, WinCE, etc. It is very much easy to port to other systems."
},
{
"code": null,
"e": 29219,
"s": 29149,
"text": "Complete database can be stored in a single cross-platform disk file."
},
{
"code": null,
"e": 29242,
"s": 29219,
"text": "Applications of SQLite"
},
{
"code": null,
"e": 29853,
"s": 29242,
"text": "Due to its small code print and efficient usage of memory, it is the popular choice for the database engine in cellphones, PDAs, MP3 players, set-top boxes, and other electronic gadgets.It is used as an alternative for open to writing XML, JSON, CSV or some proprietary format into disk files used by the application.As it has no complication for configuration and easily stores file in an ordinary disk file, so it can be used as a database for small to medium sized websites.It is faster and accessible through a wide variety of third-party tools, so it has great application in different software platforms."
},
{
"code": null,
"e": 30040,
"s": 29853,
"text": "Due to its small code print and efficient usage of memory, it is the popular choice for the database engine in cellphones, PDAs, MP3 players, set-top boxes, and other electronic gadgets."
},
{
"code": null,
"e": 30172,
"s": 30040,
"text": "It is used as an alternative for open to writing XML, JSON, CSV or some proprietary format into disk files used by the application."
},
{
"code": null,
"e": 30333,
"s": 30172,
"text": "As it has no complication for configuration and easily stores file in an ordinary disk file, so it can be used as a database for small to medium sized websites."
},
{
"code": null,
"e": 30467,
"s": 30333,
"text": "It is faster and accessible through a wide variety of third-party tools, so it has great application in different software platforms."
},
{
"code": null,
"e": 30607,
"s": 30467,
"text": "SQLite CommandsIn SQLite, there are several dot commands which do not end with a semicolon(;). Here are all commands and their description:"
},
{
"code": null,
"e": 30698,
"s": 30607,
"text": "Some DDL and DML CommandsIt is same as compared to previous technology like MySQL, Oracle."
},
{
"code": null,
"e": 30827,
"s": 30698,
"text": "Creating Table:CREATE TABLE STUDENT(ID INT PRIMARY KEY NOT NULL,NAME TEXT NOT NULL,AGE INT NOT NULL,ADDRESS CHAR(50),FEES REAL);"
},
{
"code": null,
"e": 30937,
"s": 30827,
"text": "Insert Command:INSERT INTO STUDENT (ID, NAME, AGE, ADDRESS, FEES)VALUES (1, 'Sunil', 28, 'Mumbai', 20000.00);"
},
{
"code": null,
"e": 30968,
"s": 30937,
"text": "Drop Table:Drop Table Student;"
},
{
"code": null,
"e": 30992,
"s": 30968,
"text": "Disadvantages of SQLite"
},
{
"code": null,
"e": 31065,
"s": 30992,
"text": "It is only used where there is low to medium traffic requests are there."
},
{
"code": null,
"e": 31127,
"s": 31065,
"text": "The database size is restricted i.e. it is 2GB in most cases."
},
{
"code": null,
"e": 31199,
"s": 31127,
"text": "References :https://www.sqlite.org/index.htmlhttps://www.javatpoint.com"
},
{
"code": null,
"e": 31213,
"s": 31199,
"text": "sanskar27jain"
},
{
"code": null,
"e": 31227,
"s": 31213,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 31231,
"s": 31227,
"text": "SQL"
},
{
"code": null,
"e": 31250,
"s": 31231,
"text": "Technical Scripter"
},
{
"code": null,
"e": 31254,
"s": 31250,
"text": "SQL"
},
{
"code": null,
"e": 31352,
"s": 31254,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31376,
"s": 31352,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 31387,
"s": 31376,
"text": "CTE in SQL"
},
{
"code": null,
"e": 31453,
"s": 31387,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 31486,
"s": 31453,
"text": "Difference between SQL and NoSQL"
},
{
"code": null,
"e": 31531,
"s": 31486,
"text": "Difference between DELETE, DROP and TRUNCATE"
},
{
"code": null,
"e": 31563,
"s": 31531,
"text": "MySQL | Group_CONCAT() Function"
},
{
"code": null,
"e": 31602,
"s": 31563,
"text": "Difference between DELETE and TRUNCATE"
},
{
"code": null,
"e": 31617,
"s": 31602,
"text": "SQL | Subquery"
},
{
"code": null,
"e": 31674,
"s": 31617,
"text": "How to Create a Table With Multiple Foreign Keys in SQL?"
}
] |
Subsets and Splits