title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Command Line Scripts | Python Packaging - GeeksforGeeks | 29 Apr, 2019
How do we execute any script in Python?
$ python do_something.py
$ python do_something_with_args.py gfg vibhu
Probably that’s how you do it.If your answer was that you just click a button on your IDE to execute your Python code, just assume you were asked specifically how you do it on command line.
Let’s make it easier for you.
$ do_something
$ do_something_with_args gfg vibhu
That sure looks a lot cleaner. Basically, they are just your python scripts converted to command line tools. In this article, we will discuss how you can do that yourself.
The process can be broken down in these 6 steps:
Create your Command Line Script.Set-up files and folder structure for Packaging.Modify your setup.py file to incorporate your CLI scripts.Test your package before publishing and then Build.Upload on pypi and publish your package.Install your newly-published package.
Create your Command Line Script.
Set-up files and folder structure for Packaging.
Modify your setup.py file to incorporate your CLI scripts.
Test your package before publishing and then Build.
Upload on pypi and publish your package.
Install your newly-published package.
The first two steps are comprehensively covered in their respective articles. It’s recommended to have a look at them before moving forward. This article will mainly continue from Step 3.
Step #1: Make your Command Line Script-> gfg.py
import argparse def main(): parser = argparse.ArgumentParser(prog ='gfg', description ='GfG article demo package.') parser.add_argument('integers', metavar ='N', type = int, nargs ='+', help ='an integer for the accumulator') parser.add_argument('-greet', action ='store_const', const = True, default = False, dest ='greet', help ="Greet Message from Geeks For Geeks.") parser.add_argument('--sum', dest ='accumulate', action ='store_const', const = sum, default = max, help ='sum the integers (default: find the max)') args = parser.parse_args() if args.greet: print("Welcome to GeeksforGeeks !") if args.accumulate == max: print("The Computation Done is Maximum") else: print("The Computation Done is Summation") print("And Here's your result:", end =" ") print(args.accumulate(args.integers))
Step #2: Set-up files and folder Structure Step #3: Modify setup.py file
Setuptools allows modules to register entrypoints (entry_points) which other packages can hook into to provide certain functionality. It also provides a few itself, including the console_scripts entry point.This allows Python functions (not scripts!) to be directly registered as command-line accessible tools!-> setup.py
from setuptools import setup, find_packages with open('requirements.txt') as f: requirements = f.readlines() long_description = 'Sample Package made for a demo \ of its making for the GeeksforGeeks Article.' setup( name ='vibhu4gfg', version ='1.0.0', author ='Vibhu Agarwal', author_email ='[email protected]', url ='https://github.com/Vibhu-Agarwal/vibhu4gfg', description ='Demo Package for GfG Article.', long_description = long_description, long_description_content_type ="text/markdown", license ='MIT', packages = find_packages(), entry_points ={ 'console_scripts': [ 'gfg = vibhu4gfg.gfg:main' ] }, classifiers =( "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ), keywords ='geeksforgeeks gfg article python package vibhu4agarwal', install_requires = requirements, zip_safe = False)
Step #4: Test & BuildTest: Change the directory to top-level of your package, the same one with setup.py file.Install your intended package by typing in this command.
$ python3 setup.py install
This will install your package if there are no errors in setup.Now you can test all the functionalities of your package. If anything goes wrong, you can still fix things up.
Build: Make sure you have upgraded pip version along with latest setuptools and wheel. Now use this command to build distributions of your package.
$ python3 setup.py sdist bdist_wheel
Step #5: Publish the packagetwine is a library that helps you upload your package distributions to pypi. Before executing the following command, make sure you have an account on PyPI
$ twine upload dist/*
Provide the Credentials and Done! You just got your first Python package published on PyPI. Step #6: Install the packageNow install your newly published package by using pip.
$ pip install vibhu4gfg
Play.
$ gfg
usage: gfg [-h] [-greet] [--sum] N [N ...]
gfg: error: the following arguments are required: N
$ gfg -h
usage: gfg [-h] [-greet] [--sum] N [N ...]
GfG article demo package.
positional arguments:
N an integer for the accumulator
optional arguments:
-h, --help show this help message and exit
-greet Greet Message from Geeks For Geeks.
--sum sum the integers (default: find the max)
$ gfg 5 10 15 -greet
Welcome to GeeksforGeeks!
The Computation Done is Maximum
And Here's your result: 15
$ gfg 5 10 15 -greet --sum
Welcome to GeeksforGeeks!
The Computation Done is Summation
And Here's your result: 30
Reference: https://python-packaging.readthedocs.io/en/latest/command-line-scripts.html
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Reading and Writing to text files in Python
sum() function in Python | [
{
"code": null,
"e": 23849,
"s": 23821,
"text": "\n29 Apr, 2019"
},
{
"code": null,
"e": 23889,
"s": 23849,
"text": "How do we execute any script in Python?"
},
{
"code": null,
"e": 23960,
"s": 23889,
"text": "$ python do_something.py\n$ python do_something_with_args.py gfg vibhu\n"
},
{
"code": null,
"e": 24150,
"s": 23960,
"text": "Probably that’s how you do it.If your answer was that you just click a button on your IDE to execute your Python code, just assume you were asked specifically how you do it on command line."
},
{
"code": null,
"e": 24180,
"s": 24150,
"text": "Let’s make it easier for you."
},
{
"code": null,
"e": 24231,
"s": 24180,
"text": "$ do_something\n$ do_something_with_args gfg vibhu\n"
},
{
"code": null,
"e": 24403,
"s": 24231,
"text": "That sure looks a lot cleaner. Basically, they are just your python scripts converted to command line tools. In this article, we will discuss how you can do that yourself."
},
{
"code": null,
"e": 24452,
"s": 24403,
"text": "The process can be broken down in these 6 steps:"
},
{
"code": null,
"e": 24719,
"s": 24452,
"text": "Create your Command Line Script.Set-up files and folder structure for Packaging.Modify your setup.py file to incorporate your CLI scripts.Test your package before publishing and then Build.Upload on pypi and publish your package.Install your newly-published package."
},
{
"code": null,
"e": 24752,
"s": 24719,
"text": "Create your Command Line Script."
},
{
"code": null,
"e": 24801,
"s": 24752,
"text": "Set-up files and folder structure for Packaging."
},
{
"code": null,
"e": 24860,
"s": 24801,
"text": "Modify your setup.py file to incorporate your CLI scripts."
},
{
"code": null,
"e": 24912,
"s": 24860,
"text": "Test your package before publishing and then Build."
},
{
"code": null,
"e": 24953,
"s": 24912,
"text": "Upload on pypi and publish your package."
},
{
"code": null,
"e": 24991,
"s": 24953,
"text": "Install your newly-published package."
},
{
"code": null,
"e": 25179,
"s": 24991,
"text": "The first two steps are comprehensively covered in their respective articles. It’s recommended to have a look at them before moving forward. This article will mainly continue from Step 3."
},
{
"code": null,
"e": 25227,
"s": 25179,
"text": "Step #1: Make your Command Line Script-> gfg.py"
},
{
"code": "import argparse def main(): parser = argparse.ArgumentParser(prog ='gfg', description ='GfG article demo package.') parser.add_argument('integers', metavar ='N', type = int, nargs ='+', help ='an integer for the accumulator') parser.add_argument('-greet', action ='store_const', const = True, default = False, dest ='greet', help =\"Greet Message from Geeks For Geeks.\") parser.add_argument('--sum', dest ='accumulate', action ='store_const', const = sum, default = max, help ='sum the integers (default: find the max)') args = parser.parse_args() if args.greet: print(\"Welcome to GeeksforGeeks !\") if args.accumulate == max: print(\"The Computation Done is Maximum\") else: print(\"The Computation Done is Summation\") print(\"And Here's your result:\", end =\" \") print(args.accumulate(args.integers))",
"e": 26259,
"s": 25227,
"text": null
},
{
"code": null,
"e": 26333,
"s": 26259,
"text": " Step #2: Set-up files and folder Structure Step #3: Modify setup.py file"
},
{
"code": null,
"e": 26655,
"s": 26333,
"text": "Setuptools allows modules to register entrypoints (entry_points) which other packages can hook into to provide certain functionality. It also provides a few itself, including the console_scripts entry point.This allows Python functions (not scripts!) to be directly registered as command-line accessible tools!-> setup.py"
},
{
"code": "from setuptools import setup, find_packages with open('requirements.txt') as f: requirements = f.readlines() long_description = 'Sample Package made for a demo \\ of its making for the GeeksforGeeks Article.' setup( name ='vibhu4gfg', version ='1.0.0', author ='Vibhu Agarwal', author_email ='[email protected]', url ='https://github.com/Vibhu-Agarwal/vibhu4gfg', description ='Demo Package for GfG Article.', long_description = long_description, long_description_content_type =\"text/markdown\", license ='MIT', packages = find_packages(), entry_points ={ 'console_scripts': [ 'gfg = vibhu4gfg.gfg:main' ] }, classifiers =( \"Programming Language :: Python :: 3\", \"License :: OSI Approved :: MIT License\", \"Operating System :: OS Independent\", ), keywords ='geeksforgeeks gfg article python package vibhu4agarwal', install_requires = requirements, zip_safe = False)",
"e": 27724,
"s": 26655,
"text": null
},
{
"code": null,
"e": 27892,
"s": 27724,
"text": " Step #4: Test & BuildTest: Change the directory to top-level of your package, the same one with setup.py file.Install your intended package by typing in this command."
},
{
"code": null,
"e": 27919,
"s": 27892,
"text": "$ python3 setup.py install"
},
{
"code": null,
"e": 28093,
"s": 27919,
"text": "This will install your package if there are no errors in setup.Now you can test all the functionalities of your package. If anything goes wrong, you can still fix things up."
},
{
"code": null,
"e": 28241,
"s": 28093,
"text": "Build: Make sure you have upgraded pip version along with latest setuptools and wheel. Now use this command to build distributions of your package."
},
{
"code": null,
"e": 28279,
"s": 28241,
"text": "$ python3 setup.py sdist bdist_wheel\n"
},
{
"code": null,
"e": 28463,
"s": 28279,
"text": " Step #5: Publish the packagetwine is a library that helps you upload your package distributions to pypi. Before executing the following command, make sure you have an account on PyPI"
},
{
"code": null,
"e": 28486,
"s": 28463,
"text": "$ twine upload dist/*\n"
},
{
"code": null,
"e": 28661,
"s": 28486,
"text": "Provide the Credentials and Done! You just got your first Python package published on PyPI. Step #6: Install the packageNow install your newly published package by using pip."
},
{
"code": null,
"e": 28686,
"s": 28661,
"text": "$ pip install vibhu4gfg\n"
},
{
"code": null,
"e": 28692,
"s": 28686,
"text": "Play."
},
{
"code": null,
"e": 29336,
"s": 28692,
"text": "$ gfg\nusage: gfg [-h] [-greet] [--sum] N [N ...]\ngfg: error: the following arguments are required: N\n\n$ gfg -h\nusage: gfg [-h] [-greet] [--sum] N [N ...]\n\nGfG article demo package.\n\npositional arguments:\n N an integer for the accumulator\n\noptional arguments:\n -h, --help show this help message and exit\n -greet Greet Message from Geeks For Geeks.\n --sum sum the integers (default: find the max)\n\n$ gfg 5 10 15 -greet\nWelcome to GeeksforGeeks!\nThe Computation Done is Maximum\nAnd Here's your result: 15\n\n$ gfg 5 10 15 -greet --sum\nWelcome to GeeksforGeeks!\nThe Computation Done is Summation\nAnd Here's your result: 30\n"
},
{
"code": null,
"e": 29423,
"s": 29336,
"text": "Reference: https://python-packaging.readthedocs.io/en/latest/command-line-scripts.html"
},
{
"code": null,
"e": 29438,
"s": 29423,
"text": "python-utility"
},
{
"code": null,
"e": 29445,
"s": 29438,
"text": "Python"
},
{
"code": null,
"e": 29543,
"s": 29445,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29552,
"s": 29543,
"text": "Comments"
},
{
"code": null,
"e": 29565,
"s": 29552,
"text": "Old Comments"
},
{
"code": null,
"e": 29583,
"s": 29565,
"text": "Python Dictionary"
},
{
"code": null,
"e": 29618,
"s": 29583,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 29640,
"s": 29618,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 29672,
"s": 29640,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29702,
"s": 29672,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 29744,
"s": 29702,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 29770,
"s": 29744,
"text": "Python String | replace()"
},
{
"code": null,
"e": 29813,
"s": 29770,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 29857,
"s": 29813,
"text": "Reading and Writing to text files in Python"
}
] |
How to add string values to a C# list? | To add string values to a list in C#, use the Add() method.
Firstly, declare a string list in C# −
List<string> list1 = new List<string>();
Now add string items −
myList.Add("Jack");
myList.Add("Ben");
myList.Add("Eon");
myList.Add("Tim");
Let us see the complete code −
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Demo {
public class Program {
public static void Main(String[] args) {
List<string> myList = new List<string>();
myList.Add("Jack");
myList.Add("Ben");
myList.Add("Eon");
myList.Add("Tim");
Console.WriteLine(myList.Count);
}
}
} | [
{
"code": null,
"e": 1122,
"s": 1062,
"text": "To add string values to a list in C#, use the Add() method."
},
{
"code": null,
"e": 1161,
"s": 1122,
"text": "Firstly, declare a string list in C# −"
},
{
"code": null,
"e": 1202,
"s": 1161,
"text": "List<string> list1 = new List<string>();"
},
{
"code": null,
"e": 1225,
"s": 1202,
"text": "Now add string items −"
},
{
"code": null,
"e": 1302,
"s": 1225,
"text": "myList.Add(\"Jack\");\nmyList.Add(\"Ben\");\nmyList.Add(\"Eon\");\nmyList.Add(\"Tim\");"
},
{
"code": null,
"e": 1333,
"s": 1302,
"text": "Let us see the complete code −"
},
{
"code": null,
"e": 1751,
"s": 1333,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text.RegularExpressions;\n\nnamespace Demo {\n public class Program {\n public static void Main(String[] args) {\n List<string> myList = new List<string>();\n myList.Add(\"Jack\");\n myList.Add(\"Ben\");\n myList.Add(\"Eon\");\n myList.Add(\"Tim\");\n\n Console.WriteLine(myList.Count);\n }\n }\n}"
}
] |
Art of Vector Representation of Words | by ASHISH RANA | Towards Data Science | Expressing power of notations used to represent a vocabulary of a language has been a great deal of interest in the field of linguistics. Languages in practice have semantic ambiguity.
“John kissed his wife, and so did Sam”.
Sam kissed John’s wife or his own? These ambiguities must be handled in order to represent information in true form.
So, how do we develop a machine level understanding for language modelling task. Classical count based or similarity parameter based methods have existed for quite a long time in Computer Science.
But, now with the advent of deep learning models like RNNs this expressing power of language modelling is of great interest for creating efficient system to store information and finding relations between vocabulary terms. This will act as fundamental block in encoder-decoder models like seq-to-seq model.
In this article we will explore different representation system of words and their power of expression, from the classical NLP to modern Neural Network approaches. In the end we will conclude with hands on coding exercises and explanations.
For readers, keep your markers on & mark important points. It is quite a long read with some minor mathematics involved with concept explanation from scratch.
Machines are better at understanding numbers that actual text passed on as tokens. This process of converting text to numbers is called vectorization. Vectors then combine to form vector space which is continuous in nature, an algebraic model where rules of vector addition and similarity measures apply. Different approaches of vectorization exists let’s move from the most primitive ones to most advanced ones.
The representation models that will be discussed in this article are :
1. One-hot representations
2. Distributed Representations
3. Singular Value Decomposition
4. Continuous bag of words model
5. Skip-Gram model
6. Glove Representations
For defining representation power of a system we first will look into workings of different representation systems. These systems represent each and every word of a vocabulary in the form a vector and create a finite vector space.
Let’s see an example of one-hot representation of words. Each word is represented with a large vector of size |V| i.e. vocabulary’s size for the given corpus.
It is a very simple form of representation with very easy implementation. But, many of the faults would have become clear even from such small example. Like, huge memory required for storing and processing such vectors. Along, with sparse nature of these vectors.For example, the size of |V| is very large like 3M for Google 1T corpus. This notation will fail in terms of computation overhead caused by representation power of this system.
Also, no notion of similarity is captured. Cosine similarity b/w unique words is zero and Euclidean distance is always sqrt(2). Meaning, no semantic information is getting expressed with this representation system.
Now, clearly we should move to a representation which saves space and hold some semantic power to express relationships among words. Let’s see a representation based on similarity.
You shall know a word by the company it keeps
— Firth, J.R.
The idea is to quantify co-occurrence of terms in a corpus. This co-occurrence is measured with window size of ‘k’ around the terms which signifies the context being distributed in that window size. With this method in mind, a co-occurrence matrix of terms × terms which captures the number of times a term appears in the context of another term is created. Also, it is a good practice to remove stopwords as these are high frequency words providing least amount of meaningful insight. Also, we can set an upper threshold for t for words.
Now, consider the following corpus:
Human machine interface for computer applications
User opinion of computer system response time
User interface management system
System engineering for improved response time
Here, in above case if stopwords are not handled properly they will create problem with their relative high frequency. So, a new quantity known as Positive Pointwise Mutual Information will be used that takes into account relative and individual occurrences along with size of vocabulary.
With this method we were able to get some idea about context but still this won’t be an ideal approach. Consider example ‘cat’ and ‘dog’ in corpus but they don’t lie within the window gap. Clearly there is relation b/w cat and dog like both being pets, mammal etc. this method won’t be able to give any insight about their relation.
In above case co-occurrence between {system, machine} and {human, user} is not visible. But, they are related to each other in above corpus’s context.
Also, high dimensionality, sparse nature of matrix & redundancy( as symmetric matrix ) still persists along with increase in size along with vocabulary.
High dimensional problem are solved by PCA or by its generalized version SVD. SVD is a generalization of the eigen-decomposition of a positive semi-definite normal matrix to any matrix via an extension of the polar decomposition. It gives the best rank-k approximation of the original data. Let original data X be of dimension m x n. The singular value decomposition will break this into best rank approximation capturing information from most relevant to least relevant ones.
An analogy to this can be seen with with case of colors being represented with 8-bits. These 8-bits will provide more resolution to us. But, now we want to compress this into 4-bits only. Which bits should we retain, lower or higher ones?
When the bits are reduced, most important information is to identify the color not the shades of different colors. Similar resolution will exist for different colors like Red, Blue, Yellow etc.
As by capturing information about different shades only there would be no meaning for colors because all information related to colors was lost. Hence, lower bits are the most important ones. Now, in this case SVD would have captured those lower bits.
With SVD, the latent co-occurrence between {system, machine} and {human, user} will become visible. We take the matrix product of X and Xt, whose ij-th entry is the dot product between the representation of word i (X[i :]) and word j (X[j :]). The ij-th entry of X, Xt roughly captures the cosine similarity between word i , word j.
We would want representations of words(i, j) to be of smaller dimensions but still have the same similarity(dot product) as the corresponding rows of Xhat. Hence, our search for finding more powerful representations must go on.
Also, notice that the dot product between the rows of the the matrix Wword=UΣ is the same as the dot product between the rows of X̂hat.
The methods we have seen are count based models like SVD as it uses co-occurrence count which uses the classical statistic based NLP principles. Now, we will move onto prediction based model which directly learn word representations. Consider a task, predict the nth word given previous (n-1) words. For training data all n-word window in training corpus can be used and corpus can be obtained from scraping any webpage.
Now, How to model this task of predicting nth word? & What’s the connection between this task and learning word representations? For modelling this problem we will use feed-forward neural network as shown below.
Our aim is to predict a probability distribution over these |V| classes as a multi-class classification problem. But this looks very complex and neural networks have very high number parameters. How is this a simpler approach?
For this, we need to look little bit behind the mathematics behind the vector multiplication happening in behind the scenes with this neural network. The product Wcontext*x given that x is a one hot vector.
We can treat the i-th column of Wcontext as the representation of context i. For P(on|sat) is proportional to the dot product between jth column of Wcontext and ith column of Wword. P(word = i|sat) thus depends on the ithcolumn of Wword. We thus treat the ith column of Wword as the representation of word i. This clearly shows the weight parameters are being represented as word vector representation in a neural network architecture.
Having understood the simplicity of interpretation behind the parameters, our aim now is to learn these parameters. For multi-class classification problem use softmax as output activation function and cross-entropy as loss function.
Let’s see what we can interpret from update rule from above loss-function. Put value of yhat in loss-function and differentiate it to derive gradient update rule.
This increases the cosine similarity between vw and uc. As, training objective ensures that the cosine similarity between word (vw) and context word (uc) is maximized. Hence, similarity measure is also captured by this representation. Also, neural network helps in learning much simpler and abstract vector representations of words.
In practice, more than one words are used in the window size, it common to use ‘d’ window size depending on the use-case. That would simply mean we have to stack copies of Wcontext in the bottom layers as two one-hot rod bits will be high.
Here, still computation bottleneck of softmax is present with denominator term involving summation over the entire vocabulary. We must explore some other model mitigating this bottleneck step.
This model predicts context words with respect to given input words. The role of context and word has changed to an almost opposite sense. Now, with given input words as one hot representations our aim is to predict context word related to it. This opposite relation b/w CBOW model & Skip-Gram model will become more clear below.
Given a corpus the model loops on the words of each sentence and either tries to use the current word of to predict its neighbors(its context), in which case the model is called “Skip-Gram”, or it uses each of these contexts to predict the current word, in which case the model is called “Continuous Bag Of Words” (CBOW).
Train a simple neural network with a single hidden layer to perform a certain task, but then we’re not actually going to use that neural network for the task we trained it on every single time for new task of modeling! Instead, the goal is actually just to learn the weights of the hidden layer which will be word vectors as stated by mathematics shown in above section.
In the simple case when there is only one context word, we will arrive atthe same update rule for uc as we did for vw earlier. If we have multiple context words the loss function would just be a summation of many cross-entropy errors.
Again same issue as with CBOW, the problem of softmax being computationally expensive exists for this model also.
Three strategies namely negative sampling, contrastive estimation and hierarchical softmax can be used to eliminate this softmax problem of summation over entire vocabulary.
Negative Sampling: We sample k negative (w, r) pairs with no context for every positive (w, c) context pairs. The size of Ddash is thus k times the size of D. In our neural network we will define loss functions and train on both these sets. These corrupted pairs are drawn from a specially designed distribution, which favours less frequent words to be drawn more often.
Contrastive Estimation: The basic idea is to convert a multinomial classification problem(as it is the problem of predicting the next word) to a binary classification problem. Instead of using softmax to estimate a true probability distribution of the output word, a binary logistic regression (binary classification) is used instead i.e. the optimized classifier simply predicts whether a pair of words is good or bad. For each training sample, the enhanced (optimized) classifier is fed a true pair (a center word and another word that appears in its context) and a number of k randomly corrupted pairs (consisting of the center word and a randomly chosen word from the vocabulary). By learning to distinguish the true pairs from corrupted ones, the classifier will ultimately learn the word vectors.
Hierarchical softmax: In this technique a binary tree is constructed such that there are |V| leaf nodes each corresponding to one word in the vocabulary. There exists a unique path from the root node to a leaf node. In effect, the task gets formulated to the probability of predicting a word is the same as predicting the correct unique path from the root node to that word. The above model ensures that the representation of a context word vc will have a high(low) similarity with the representation of the node ui if ui appears on the path and the path branches to the left(right) at ui. Representations of contexts which appear with the same words will have high similarity.
Count based methods (SVD) rely on global co-occurrence counts from thecorpus for computing word representations. Predict based methods learn word representations using co-occurrence information. Why not combine the two count and learn mechanisms ?
Let’s formulate this idea mathematically and then develop an intuition for it. Let Xij encodes important global information about the co-occurrence between i and j.
Our aim will be to learn word vectors which complies with computed probability on entire corpus. Essentially we are saying that we want wordvectors vi and vj such that vi^T vj is faithful to the globally computed P (j|i).
Add the two equations for Xi and Xj respectively. Also, log(Xi) and log(Xj) depend only on the words i & j and we can think of them as word specific biases which will be learned. Formulate this problem in following way.
Now, the problem is weights of all the co-occurrences are equal. Weight should be defined in such a manner that neither rare or frequent words are over-weighted.
Words are represented by dense vectors where a vector represents the projection of the word into a continuous vector space. It is an improvement over more the traditional bag-of-word model encoding schemes where large sparse vectors were used to represent each word. Those representations were sparse because the vocabularies were vast and a given word or document would be represented by a large vector comprised mostly of zero values.
Considering the recent popular research papers. Boroni et.al [2014] showed that predict models consistently outperform count models in all tasks. Levy et.al [2015] do a much more through analysis (IMO) and show that goodold SVD does better than prediction based models on similarity tasks but noton analogy tasks. Levy showed that word2vec also implicitly does a matrix factorization. It turns out that we can also show that
Good old SVD will just do fine. But, currently working with pre-trained Glove embeddings on huge corpuses results in much better results and once trained, can be reused again. Libraries like Keras, Gensim does provide embedding layers which can be used with ease for modelling tasks. Also, for extensive NLP tasks it is much better to use Standford’s Glove vector representation dataset. Let’s take a look on few examples of these representation models in action.
Let’s see how to encode characters as integers. Which means that each unique character will be assigned a unique integer value and each sequence of characters will be encoded as a sequence of these unique integers. Follow the below script mentioned for doing the above mentioned thing.
As a preprocessing step, first create a file containing all the sequences and store that in a new file. This new file will contain the sequences of characters of equal length. Refer python script below for this preprocessing step. You can also refer to repository link for directly copying complete project and running it onto your machine.
# load doc into memorydef load_docx(filename): # open the file as read only file = open(filename, 'r') # read all text text = file.read() # close the file file.close() return text# save tokens to file, one dialog per linedef save_docx(lines, filename): data = '\n'.join(lines) file = open(filename, 'w') file.write(data) file.close()# load text data in your current directoryraw_text = load_docx('The-Road-Not-Taken.txt')print(raw_text)# clean the texttokens = raw_text.split()raw_text = ' '.join(tokens)# organize into sequences of characterslength = 16sequences = list()for i in range(length, len(raw_text)): # select sequence of tokens seq = raw_text[i-length:i+1] # store sequences.append(seq)print('Total Sequences: %d' % len(sequences))# save sequences to fileout_filename = 'char_sequences.txt'save_docx(sequences, out_filename)
For encoding these sequences we will create the mapping given a sorted set of unique characters in the raw input data. The mapping will be a dictionary of character values to integer values.
char = sorted(list(set(raw_text)))map = dict((c, i) for i, c in enumerate(char))
Next, we process each sequence of characters one at a time and use the dictionary mapping to look up the integer value for each character. The result is a list of integer lists representing sequences of characters in integer format.
sequences = list()for line in lines: # integer encoding line encoded_seq = [mapping[char] for char in line] # store in list of sequences sequences.append(encoded_seq)
Next, step is encoding into one hot vector each of size of vocabulary. Separate input and output columns into different sequence of characters.
sequences = array(sequences)X, Y = sequences[:,:-1], sequences[:,-1] # X containing all chars except at last position, Y containing only the last char# to_categorical() function in the Keras API to one hot encode the input and output sequences.sequences = [to_categorical(x, num_classes=vocab_size) for x in X]X = array(sequences)Y = to_categorical(y, num_classes=vocab_size)
After this preprocessing you can feed your data into your model for learning parameters.
Word embeddings provide a dense representation of words and convey some semantic information along with it. Embeddings can also be learned along with our model specific to our dataset.
The position of a word in the learned vector space is referred to as its embedding.
The Embedding layer provided by keras which requires input to be integer encoded is initialized with random weights and will learn an embedding for all of the words in the training dataset.
e = Embedding(200, 32, input_length=50)200: specifies the vocabulary size32: specifies the output vector dimensionsinput_length=50: length of input sequences in the document
The output of the Embedding layer is a 2D vector with one embedding for each word in the input sequence of words.
Keras Embedding layer can also use a word embedding learned elsewhere like from pretrained Glove vectors from Stanford. Load the Glove vectors into the memory to an embedding array.
# load the whole embedding into memoryembeddings_index = dict()f = open('glove.6B.100d.txt')for line in f: values = line.split() word = values[0] coefs = asarray(values[1:], dtype='float32') embeddings_index[word] = coefsf.close()print('Loaded %s word vectors.' % len(embeddings_index))# for loading again it is better to store this as pickle object.
Then create resultant weight matrix which can be passed onto Keras Embedding layer. Finally, we do not want to update the learned word weights in this model, therefore we will set the trainable attribute for the model to be False.
# Here, we are using 100 dim vectors version from downloaded file# create a weight matrix for words in training docsembedding_matrix = zeros((vocab_size, 100))for word, i in t.word_index.items(): embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[i] = embedding_vectore = Embedding(vocab_size, 100, weights=[embedding_matrix], input_length=4, trainable=False)
Above, code snippets do give an idea about on getting started with vectorization task depending on complexity of model that is being used. One hot vectors for least complex to Glove vectors for good performance for complex models.
Thanks to Prof. Mitesh M. Khapra and his TAs for wonderful course on Deep Learning(CS7015). Also, to Jason from machinelearningmastery.com for useful code snippets and few stackoverflow threads. | [
{
"code": null,
"e": 356,
"s": 171,
"text": "Expressing power of notations used to represent a vocabulary of a language has been a great deal of interest in the field of linguistics. Languages in practice have semantic ambiguity."
},
{
"code": null,
"e": 396,
"s": 356,
"text": "“John kissed his wife, and so did Sam”."
},
{
"code": null,
"e": 513,
"s": 396,
"text": "Sam kissed John’s wife or his own? These ambiguities must be handled in order to represent information in true form."
},
{
"code": null,
"e": 710,
"s": 513,
"text": "So, how do we develop a machine level understanding for language modelling task. Classical count based or similarity parameter based methods have existed for quite a long time in Computer Science."
},
{
"code": null,
"e": 1017,
"s": 710,
"text": "But, now with the advent of deep learning models like RNNs this expressing power of language modelling is of great interest for creating efficient system to store information and finding relations between vocabulary terms. This will act as fundamental block in encoder-decoder models like seq-to-seq model."
},
{
"code": null,
"e": 1258,
"s": 1017,
"text": "In this article we will explore different representation system of words and their power of expression, from the classical NLP to modern Neural Network approaches. In the end we will conclude with hands on coding exercises and explanations."
},
{
"code": null,
"e": 1417,
"s": 1258,
"text": "For readers, keep your markers on & mark important points. It is quite a long read with some minor mathematics involved with concept explanation from scratch."
},
{
"code": null,
"e": 1830,
"s": 1417,
"text": "Machines are better at understanding numbers that actual text passed on as tokens. This process of converting text to numbers is called vectorization. Vectors then combine to form vector space which is continuous in nature, an algebraic model where rules of vector addition and similarity measures apply. Different approaches of vectorization exists let’s move from the most primitive ones to most advanced ones."
},
{
"code": null,
"e": 1901,
"s": 1830,
"text": "The representation models that will be discussed in this article are :"
},
{
"code": null,
"e": 1928,
"s": 1901,
"text": "1. One-hot representations"
},
{
"code": null,
"e": 1959,
"s": 1928,
"text": "2. Distributed Representations"
},
{
"code": null,
"e": 1991,
"s": 1959,
"text": "3. Singular Value Decomposition"
},
{
"code": null,
"e": 2024,
"s": 1991,
"text": "4. Continuous bag of words model"
},
{
"code": null,
"e": 2043,
"s": 2024,
"text": "5. Skip-Gram model"
},
{
"code": null,
"e": 2068,
"s": 2043,
"text": "6. Glove Representations"
},
{
"code": null,
"e": 2299,
"s": 2068,
"text": "For defining representation power of a system we first will look into workings of different representation systems. These systems represent each and every word of a vocabulary in the form a vector and create a finite vector space."
},
{
"code": null,
"e": 2458,
"s": 2299,
"text": "Let’s see an example of one-hot representation of words. Each word is represented with a large vector of size |V| i.e. vocabulary’s size for the given corpus."
},
{
"code": null,
"e": 2898,
"s": 2458,
"text": "It is a very simple form of representation with very easy implementation. But, many of the faults would have become clear even from such small example. Like, huge memory required for storing and processing such vectors. Along, with sparse nature of these vectors.For example, the size of |V| is very large like 3M for Google 1T corpus. This notation will fail in terms of computation overhead caused by representation power of this system."
},
{
"code": null,
"e": 3113,
"s": 2898,
"text": "Also, no notion of similarity is captured. Cosine similarity b/w unique words is zero and Euclidean distance is always sqrt(2). Meaning, no semantic information is getting expressed with this representation system."
},
{
"code": null,
"e": 3294,
"s": 3113,
"text": "Now, clearly we should move to a representation which saves space and hold some semantic power to express relationships among words. Let’s see a representation based on similarity."
},
{
"code": null,
"e": 3340,
"s": 3294,
"text": "You shall know a word by the company it keeps"
},
{
"code": null,
"e": 3354,
"s": 3340,
"text": "— Firth, J.R."
},
{
"code": null,
"e": 3893,
"s": 3354,
"text": "The idea is to quantify co-occurrence of terms in a corpus. This co-occurrence is measured with window size of ‘k’ around the terms which signifies the context being distributed in that window size. With this method in mind, a co-occurrence matrix of terms × terms which captures the number of times a term appears in the context of another term is created. Also, it is a good practice to remove stopwords as these are high frequency words providing least amount of meaningful insight. Also, we can set an upper threshold for t for words."
},
{
"code": null,
"e": 3929,
"s": 3893,
"text": "Now, consider the following corpus:"
},
{
"code": null,
"e": 3979,
"s": 3929,
"text": "Human machine interface for computer applications"
},
{
"code": null,
"e": 4025,
"s": 3979,
"text": "User opinion of computer system response time"
},
{
"code": null,
"e": 4058,
"s": 4025,
"text": "User interface management system"
},
{
"code": null,
"e": 4104,
"s": 4058,
"text": "System engineering for improved response time"
},
{
"code": null,
"e": 4393,
"s": 4104,
"text": "Here, in above case if stopwords are not handled properly they will create problem with their relative high frequency. So, a new quantity known as Positive Pointwise Mutual Information will be used that takes into account relative and individual occurrences along with size of vocabulary."
},
{
"code": null,
"e": 4726,
"s": 4393,
"text": "With this method we were able to get some idea about context but still this won’t be an ideal approach. Consider example ‘cat’ and ‘dog’ in corpus but they don’t lie within the window gap. Clearly there is relation b/w cat and dog like both being pets, mammal etc. this method won’t be able to give any insight about their relation."
},
{
"code": null,
"e": 4877,
"s": 4726,
"text": "In above case co-occurrence between {system, machine} and {human, user} is not visible. But, they are related to each other in above corpus’s context."
},
{
"code": null,
"e": 5030,
"s": 4877,
"text": "Also, high dimensionality, sparse nature of matrix & redundancy( as symmetric matrix ) still persists along with increase in size along with vocabulary."
},
{
"code": null,
"e": 5507,
"s": 5030,
"text": "High dimensional problem are solved by PCA or by its generalized version SVD. SVD is a generalization of the eigen-decomposition of a positive semi-definite normal matrix to any matrix via an extension of the polar decomposition. It gives the best rank-k approximation of the original data. Let original data X be of dimension m x n. The singular value decomposition will break this into best rank approximation capturing information from most relevant to least relevant ones."
},
{
"code": null,
"e": 5746,
"s": 5507,
"text": "An analogy to this can be seen with with case of colors being represented with 8-bits. These 8-bits will provide more resolution to us. But, now we want to compress this into 4-bits only. Which bits should we retain, lower or higher ones?"
},
{
"code": null,
"e": 5940,
"s": 5746,
"text": "When the bits are reduced, most important information is to identify the color not the shades of different colors. Similar resolution will exist for different colors like Red, Blue, Yellow etc."
},
{
"code": null,
"e": 6192,
"s": 5940,
"text": "As by capturing information about different shades only there would be no meaning for colors because all information related to colors was lost. Hence, lower bits are the most important ones. Now, in this case SVD would have captured those lower bits."
},
{
"code": null,
"e": 6525,
"s": 6192,
"text": "With SVD, the latent co-occurrence between {system, machine} and {human, user} will become visible. We take the matrix product of X and Xt, whose ij-th entry is the dot product between the representation of word i (X[i :]) and word j (X[j :]). The ij-th entry of X, Xt roughly captures the cosine similarity between word i , word j."
},
{
"code": null,
"e": 6753,
"s": 6525,
"text": "We would want representations of words(i, j) to be of smaller dimensions but still have the same similarity(dot product) as the corresponding rows of Xhat. Hence, our search for finding more powerful representations must go on."
},
{
"code": null,
"e": 6889,
"s": 6753,
"text": "Also, notice that the dot product between the rows of the the matrix Wword=UΣ is the same as the dot product between the rows of X̂hat."
},
{
"code": null,
"e": 7310,
"s": 6889,
"text": "The methods we have seen are count based models like SVD as it uses co-occurrence count which uses the classical statistic based NLP principles. Now, we will move onto prediction based model which directly learn word representations. Consider a task, predict the nth word given previous (n-1) words. For training data all n-word window in training corpus can be used and corpus can be obtained from scraping any webpage."
},
{
"code": null,
"e": 7522,
"s": 7310,
"text": "Now, How to model this task of predicting nth word? & What’s the connection between this task and learning word representations? For modelling this problem we will use feed-forward neural network as shown below."
},
{
"code": null,
"e": 7749,
"s": 7522,
"text": "Our aim is to predict a probability distribution over these |V| classes as a multi-class classification problem. But this looks very complex and neural networks have very high number parameters. How is this a simpler approach?"
},
{
"code": null,
"e": 7956,
"s": 7749,
"text": "For this, we need to look little bit behind the mathematics behind the vector multiplication happening in behind the scenes with this neural network. The product Wcontext*x given that x is a one hot vector."
},
{
"code": null,
"e": 8392,
"s": 7956,
"text": "We can treat the i-th column of Wcontext as the representation of context i. For P(on|sat) is proportional to the dot product between jth column of Wcontext and ith column of Wword. P(word = i|sat) thus depends on the ithcolumn of Wword. We thus treat the ith column of Wword as the representation of word i. This clearly shows the weight parameters are being represented as word vector representation in a neural network architecture."
},
{
"code": null,
"e": 8625,
"s": 8392,
"text": "Having understood the simplicity of interpretation behind the parameters, our aim now is to learn these parameters. For multi-class classification problem use softmax as output activation function and cross-entropy as loss function."
},
{
"code": null,
"e": 8788,
"s": 8625,
"text": "Let’s see what we can interpret from update rule from above loss-function. Put value of yhat in loss-function and differentiate it to derive gradient update rule."
},
{
"code": null,
"e": 9121,
"s": 8788,
"text": "This increases the cosine similarity between vw and uc. As, training objective ensures that the cosine similarity between word (vw) and context word (uc) is maximized. Hence, similarity measure is also captured by this representation. Also, neural network helps in learning much simpler and abstract vector representations of words."
},
{
"code": null,
"e": 9361,
"s": 9121,
"text": "In practice, more than one words are used in the window size, it common to use ‘d’ window size depending on the use-case. That would simply mean we have to stack copies of Wcontext in the bottom layers as two one-hot rod bits will be high."
},
{
"code": null,
"e": 9554,
"s": 9361,
"text": "Here, still computation bottleneck of softmax is present with denominator term involving summation over the entire vocabulary. We must explore some other model mitigating this bottleneck step."
},
{
"code": null,
"e": 9884,
"s": 9554,
"text": "This model predicts context words with respect to given input words. The role of context and word has changed to an almost opposite sense. Now, with given input words as one hot representations our aim is to predict context word related to it. This opposite relation b/w CBOW model & Skip-Gram model will become more clear below."
},
{
"code": null,
"e": 10206,
"s": 9884,
"text": "Given a corpus the model loops on the words of each sentence and either tries to use the current word of to predict its neighbors(its context), in which case the model is called “Skip-Gram”, or it uses each of these contexts to predict the current word, in which case the model is called “Continuous Bag Of Words” (CBOW)."
},
{
"code": null,
"e": 10577,
"s": 10206,
"text": "Train a simple neural network with a single hidden layer to perform a certain task, but then we’re not actually going to use that neural network for the task we trained it on every single time for new task of modeling! Instead, the goal is actually just to learn the weights of the hidden layer which will be word vectors as stated by mathematics shown in above section."
},
{
"code": null,
"e": 10812,
"s": 10577,
"text": "In the simple case when there is only one context word, we will arrive atthe same update rule for uc as we did for vw earlier. If we have multiple context words the loss function would just be a summation of many cross-entropy errors."
},
{
"code": null,
"e": 10926,
"s": 10812,
"text": "Again same issue as with CBOW, the problem of softmax being computationally expensive exists for this model also."
},
{
"code": null,
"e": 11100,
"s": 10926,
"text": "Three strategies namely negative sampling, contrastive estimation and hierarchical softmax can be used to eliminate this softmax problem of summation over entire vocabulary."
},
{
"code": null,
"e": 11471,
"s": 11100,
"text": "Negative Sampling: We sample k negative (w, r) pairs with no context for every positive (w, c) context pairs. The size of Ddash is thus k times the size of D. In our neural network we will define loss functions and train on both these sets. These corrupted pairs are drawn from a specially designed distribution, which favours less frequent words to be drawn more often."
},
{
"code": null,
"e": 12274,
"s": 11471,
"text": "Contrastive Estimation: The basic idea is to convert a multinomial classification problem(as it is the problem of predicting the next word) to a binary classification problem. Instead of using softmax to estimate a true probability distribution of the output word, a binary logistic regression (binary classification) is used instead i.e. the optimized classifier simply predicts whether a pair of words is good or bad. For each training sample, the enhanced (optimized) classifier is fed a true pair (a center word and another word that appears in its context) and a number of k randomly corrupted pairs (consisting of the center word and a randomly chosen word from the vocabulary). By learning to distinguish the true pairs from corrupted ones, the classifier will ultimately learn the word vectors."
},
{
"code": null,
"e": 12952,
"s": 12274,
"text": "Hierarchical softmax: In this technique a binary tree is constructed such that there are |V| leaf nodes each corresponding to one word in the vocabulary. There exists a unique path from the root node to a leaf node. In effect, the task gets formulated to the probability of predicting a word is the same as predicting the correct unique path from the root node to that word. The above model ensures that the representation of a context word vc will have a high(low) similarity with the representation of the node ui if ui appears on the path and the path branches to the left(right) at ui. Representations of contexts which appear with the same words will have high similarity."
},
{
"code": null,
"e": 13200,
"s": 12952,
"text": "Count based methods (SVD) rely on global co-occurrence counts from thecorpus for computing word representations. Predict based methods learn word representations using co-occurrence information. Why not combine the two count and learn mechanisms ?"
},
{
"code": null,
"e": 13365,
"s": 13200,
"text": "Let’s formulate this idea mathematically and then develop an intuition for it. Let Xij encodes important global information about the co-occurrence between i and j."
},
{
"code": null,
"e": 13587,
"s": 13365,
"text": "Our aim will be to learn word vectors which complies with computed probability on entire corpus. Essentially we are saying that we want wordvectors vi and vj such that vi^T vj is faithful to the globally computed P (j|i)."
},
{
"code": null,
"e": 13807,
"s": 13587,
"text": "Add the two equations for Xi and Xj respectively. Also, log(Xi) and log(Xj) depend only on the words i & j and we can think of them as word specific biases which will be learned. Formulate this problem in following way."
},
{
"code": null,
"e": 13969,
"s": 13807,
"text": "Now, the problem is weights of all the co-occurrences are equal. Weight should be defined in such a manner that neither rare or frequent words are over-weighted."
},
{
"code": null,
"e": 14406,
"s": 13969,
"text": "Words are represented by dense vectors where a vector represents the projection of the word into a continuous vector space. It is an improvement over more the traditional bag-of-word model encoding schemes where large sparse vectors were used to represent each word. Those representations were sparse because the vocabularies were vast and a given word or document would be represented by a large vector comprised mostly of zero values."
},
{
"code": null,
"e": 14831,
"s": 14406,
"text": "Considering the recent popular research papers. Boroni et.al [2014] showed that predict models consistently outperform count models in all tasks. Levy et.al [2015] do a much more through analysis (IMO) and show that goodold SVD does better than prediction based models on similarity tasks but noton analogy tasks. Levy showed that word2vec also implicitly does a matrix factorization. It turns out that we can also show that"
},
{
"code": null,
"e": 15295,
"s": 14831,
"text": "Good old SVD will just do fine. But, currently working with pre-trained Glove embeddings on huge corpuses results in much better results and once trained, can be reused again. Libraries like Keras, Gensim does provide embedding layers which can be used with ease for modelling tasks. Also, for extensive NLP tasks it is much better to use Standford’s Glove vector representation dataset. Let’s take a look on few examples of these representation models in action."
},
{
"code": null,
"e": 15581,
"s": 15295,
"text": "Let’s see how to encode characters as integers. Which means that each unique character will be assigned a unique integer value and each sequence of characters will be encoded as a sequence of these unique integers. Follow the below script mentioned for doing the above mentioned thing."
},
{
"code": null,
"e": 15922,
"s": 15581,
"text": "As a preprocessing step, first create a file containing all the sequences and store that in a new file. This new file will contain the sequences of characters of equal length. Refer python script below for this preprocessing step. You can also refer to repository link for directly copying complete project and running it onto your machine."
},
{
"code": null,
"e": 16758,
"s": 15922,
"text": "# load doc into memorydef load_docx(filename): # open the file as read only file = open(filename, 'r') # read all text text = file.read() # close the file file.close() return text# save tokens to file, one dialog per linedef save_docx(lines, filename): data = '\\n'.join(lines) file = open(filename, 'w') file.write(data) file.close()# load text data in your current directoryraw_text = load_docx('The-Road-Not-Taken.txt')print(raw_text)# clean the texttokens = raw_text.split()raw_text = ' '.join(tokens)# organize into sequences of characterslength = 16sequences = list()for i in range(length, len(raw_text)): # select sequence of tokens seq = raw_text[i-length:i+1] # store sequences.append(seq)print('Total Sequences: %d' % len(sequences))# save sequences to fileout_filename = 'char_sequences.txt'save_docx(sequences, out_filename)"
},
{
"code": null,
"e": 16949,
"s": 16758,
"text": "For encoding these sequences we will create the mapping given a sorted set of unique characters in the raw input data. The mapping will be a dictionary of character values to integer values."
},
{
"code": null,
"e": 17030,
"s": 16949,
"text": "char = sorted(list(set(raw_text)))map = dict((c, i) for i, c in enumerate(char))"
},
{
"code": null,
"e": 17263,
"s": 17030,
"text": "Next, we process each sequence of characters one at a time and use the dictionary mapping to look up the integer value for each character. The result is a list of integer lists representing sequences of characters in integer format."
},
{
"code": null,
"e": 17430,
"s": 17263,
"text": "sequences = list()for line in lines: # integer encoding line encoded_seq = [mapping[char] for char in line] # store in list of sequences sequences.append(encoded_seq)"
},
{
"code": null,
"e": 17574,
"s": 17430,
"text": "Next, step is encoding into one hot vector each of size of vocabulary. Separate input and output columns into different sequence of characters."
},
{
"code": null,
"e": 17950,
"s": 17574,
"text": "sequences = array(sequences)X, Y = sequences[:,:-1], sequences[:,-1] # X containing all chars except at last position, Y containing only the last char# to_categorical() function in the Keras API to one hot encode the input and output sequences.sequences = [to_categorical(x, num_classes=vocab_size) for x in X]X = array(sequences)Y = to_categorical(y, num_classes=vocab_size)"
},
{
"code": null,
"e": 18039,
"s": 17950,
"text": "After this preprocessing you can feed your data into your model for learning parameters."
},
{
"code": null,
"e": 18224,
"s": 18039,
"text": "Word embeddings provide a dense representation of words and convey some semantic information along with it. Embeddings can also be learned along with our model specific to our dataset."
},
{
"code": null,
"e": 18308,
"s": 18224,
"text": "The position of a word in the learned vector space is referred to as its embedding."
},
{
"code": null,
"e": 18498,
"s": 18308,
"text": "The Embedding layer provided by keras which requires input to be integer encoded is initialized with random weights and will learn an embedding for all of the words in the training dataset."
},
{
"code": null,
"e": 18672,
"s": 18498,
"text": "e = Embedding(200, 32, input_length=50)200: specifies the vocabulary size32: specifies the output vector dimensionsinput_length=50: length of input sequences in the document"
},
{
"code": null,
"e": 18786,
"s": 18672,
"text": "The output of the Embedding layer is a 2D vector with one embedding for each word in the input sequence of words."
},
{
"code": null,
"e": 18968,
"s": 18786,
"text": "Keras Embedding layer can also use a word embedding learned elsewhere like from pretrained Glove vectors from Stanford. Load the Glove vectors into the memory to an embedding array."
},
{
"code": null,
"e": 19319,
"s": 18968,
"text": "# load the whole embedding into memoryembeddings_index = dict()f = open('glove.6B.100d.txt')for line in f: values = line.split() word = values[0] coefs = asarray(values[1:], dtype='float32') embeddings_index[word] = coefsf.close()print('Loaded %s word vectors.' % len(embeddings_index))# for loading again it is better to store this as pickle object."
},
{
"code": null,
"e": 19550,
"s": 19319,
"text": "Then create resultant weight matrix which can be passed onto Keras Embedding layer. Finally, we do not want to update the learned word weights in this model, therefore we will set the trainable attribute for the model to be False."
},
{
"code": null,
"e": 19956,
"s": 19550,
"text": "# Here, we are using 100 dim vectors version from downloaded file# create a weight matrix for words in training docsembedding_matrix = zeros((vocab_size, 100))for word, i in t.word_index.items(): embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[i] = embedding_vectore = Embedding(vocab_size, 100, weights=[embedding_matrix], input_length=4, trainable=False)"
},
{
"code": null,
"e": 20187,
"s": 19956,
"text": "Above, code snippets do give an idea about on getting started with vectorization task depending on complexity of model that is being used. One hot vectors for least complex to Glove vectors for good performance for complex models."
}
] |
Rendering elements in React.js | The smallest building blocks of React applications are the elements. Example of an element is −
const message = <h1>Welcome, Steve</h1>;
React DOM updates the actual DOM with the converted react elements. React components are made up of elements.
We will have a parent div element in the main html file . This div can be called as root.
<div id=”app”> </div>
ReactDOM manages everything which is inside the app div. We can add multiple such an isolated div in applications if required.
To render the element it will be passed to the ReactDOM render method −
const message = <h1>Welcome, Steve</h1>;
ReactDOM.render(message, document.getElementById('app'));
This will display a message − Welcome, Steve on browser
React elements are immutable that means once created it cannot be changed. Change will create a new element and update the UI.
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
function getCurrentTime() {
const currentTime = (
<div>
<h1>Welcome !</h1>
<h2>It is {new Date().toLocaleTimeString()}.</h2>
</div>
);
ReactDOM.render(currentTime, document.getElementById('root'));
}
setInterval(getCurrentTime, 1000);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister(); | [
{
"code": null,
"e": 1158,
"s": 1062,
"text": "The smallest building blocks of React applications are the elements. Example of an element is −"
},
{
"code": null,
"e": 1199,
"s": 1158,
"text": "const message = <h1>Welcome, Steve</h1>;"
},
{
"code": null,
"e": 1309,
"s": 1199,
"text": "React DOM updates the actual DOM with the converted react elements. React components are made up of elements."
},
{
"code": null,
"e": 1399,
"s": 1309,
"text": "We will have a parent div element in the main html file . This div can be called as root."
},
{
"code": null,
"e": 1421,
"s": 1399,
"text": "<div id=”app”> </div>"
},
{
"code": null,
"e": 1548,
"s": 1421,
"text": "ReactDOM manages everything which is inside the app div. We can add multiple such an isolated div in applications if required."
},
{
"code": null,
"e": 1620,
"s": 1548,
"text": "To render the element it will be passed to the ReactDOM render method −"
},
{
"code": null,
"e": 1719,
"s": 1620,
"text": "const message = <h1>Welcome, Steve</h1>;\nReactDOM.render(message, document.getElementById('app'));"
},
{
"code": null,
"e": 1775,
"s": 1719,
"text": "This will display a message − Welcome, Steve on browser"
},
{
"code": null,
"e": 1902,
"s": 1775,
"text": "React elements are immutable that means once created it cannot be changed. Change will create a new element and update the UI."
},
{
"code": null,
"e": 2567,
"s": 1902,
"text": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport './index.css';\nimport App from './App';\nimport * as serviceWorker from './serviceWorker';\nfunction getCurrentTime() {\n const currentTime = (\n <div>\n <h1>Welcome !</h1>\n <h2>It is {new Date().toLocaleTimeString()}.</h2>\n </div>\n );\n ReactDOM.render(currentTime, document.getElementById('root'));\n}\nsetInterval(getCurrentTime, 1000);\n// If you want your app to work offline and load faster, you can change\n// unregister() to register() below. Note this comes with some pitfalls.\n// Learn more about service workers: https://bit.ly/CRA-PWA\nserviceWorker.unregister();"
}
] |
Make first letter of a string uppercase in JavaScript? | To make first letter of a string uppercase, use toUpperCase() in JavaScript. With that, we will
use charAt(0) since we need to only capitalize the 1st letter.
function replaceWithTheCapitalLetter(values){
return values.charAt(0).toUpperCase() + values.slice(1);
}
var word="javascript"
console.log(replaceWithTheCapitalLetter(word));
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo167.js.
This will produce the following output −
PS C:\Users\Amit\javascript-code> node demo167.js
Javascript | [
{
"code": null,
"e": 1221,
"s": 1062,
"text": "To make first letter of a string uppercase, use toUpperCase() in JavaScript. With that, we will\nuse charAt(0) since we need to only capitalize the 1st letter."
},
{
"code": null,
"e": 1399,
"s": 1221,
"text": "function replaceWithTheCapitalLetter(values){\n return values.charAt(0).toUpperCase() + values.slice(1);\n}\nvar word=\"javascript\"\nconsole.log(replaceWithTheCapitalLetter(word));"
},
{
"code": null,
"e": 1465,
"s": 1399,
"text": "To run the above program, you need to use the following command −"
},
{
"code": null,
"e": 1483,
"s": 1465,
"text": "node fileName.js."
},
{
"code": null,
"e": 1517,
"s": 1483,
"text": "Here, my file name is demo167.js."
},
{
"code": null,
"e": 1558,
"s": 1517,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1619,
"s": 1558,
"text": "PS C:\\Users\\Amit\\javascript-code> node demo167.js\nJavascript"
}
] |
Brilliant Numbers - GeeksforGeeks | 16 Jul, 2021
Brilliant Number is a number N which is the product of two primes with the same number of digits.Few Brilliant numbers are:
4, 6, 9, 10, 14, 15, 21, 25, 35, 49....
Given a number N, the task is to check if N is a Brilliant Number or not. If N is a Brilliant Number then print “Yes” else print “No”.Examples:
Input: N = 1711 Output: Yes Explanation: 1711 = 29*59 and both 29 and 59 have two digits.Input: N = 16 Output: No
Approach: The idea is to find all the primes less than or equal to the given number N using Sieve of Eratosthenes. Once we have an array that tells all primes, we can traverse through this array to find a pair with a given product. We will find Two Prime Numbers with given product using the sieve of Eratosthenes and check if the pair has the same number of digits or not.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation for the// above approach #include <bits/stdc++.h>using namespace std; // Function to generate all prime// numbers less than nbool SieveOfEratosthenes(int n, bool isPrime[]){ // Initialize all entries of // boolean array as true. // A value in isPrime[i] // will finally be false // if i is Not a prime isPrime[0] = isPrime[1] = false; for (int i = 2; i <= n; i++) isPrime[i] = true; for (int p = 2; p * p <= n; p++) { // If isPrime[p] is not changed, // then it is a prime if (isPrime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= n; i += p) isPrime[i] = false; } }} // Function to return the number// of digits in a numberint countDigit(long long n){ return floor(log10(n) + 1);} // Function to check if N is a// Brilliant numberbool isBrilliant(int n){ int flag = 0; // Generating primes using Sieve bool isPrime[n + 1]; SieveOfEratosthenes(n, isPrime); // Traversing all numbers // to find first pair for (int i = 2; i < n; i++) { int x = n / i; if (isPrime[i] && isPrime[x] and x * i == n) { if (countDigit(i) == countDigit(x)) return true; } } return false;} // Driver Codeint main(){ // Given Number int n = 1711; // Function Call if (isBrilliant(n)) cout << "Yes"; else cout << "No"; return 0;}
// Java implementation for the// above approachimport java.util.*;class GFG{ // Function to generate all prime// numbers less than nstatic void SieveOfEratosthenes(int n, boolean isPrime[]){ // Initialize all entries of // boolean array as true. // A value in isPrime[i] // will finally be false // if i is Not a prime isPrime[0] = isPrime[1] = false; for (int i = 2; i <= n; i++) isPrime[i] = true; for (int p = 2; p * p <= n; p++) { // If isPrime[p] is not changed, // then it is a prime if (isPrime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= n; i += p) isPrime[i] = false; } }} // Function to return the number// of digits in a numberstatic int countDigit(int n){ int count = 0; while (n != 0) { n = n / 10; ++count; } return count;} // Function to check if N is a// Brilliant numberstatic boolean isBrilliant(int n){ int flag = 0; // Generating primes using Sieve boolean isPrime[] = new boolean[n + 1]; SieveOfEratosthenes(n, isPrime); // Traversing all numbers // to find first pair for (int i = 2; i < n; i++) { int x = n / i; if (isPrime[i] && isPrime[x] && (x * i) == n) { if (countDigit(i) == countDigit(x)) return true; } } return false;} // Driver Codepublic static void main (String[] args){ // Given Number int n = 1711; // Function Call if (isBrilliant(n)) System.out.print("Yes"); else System.out.print("No");}} // This code is contributed by Ritik Bansal
# Python3 program for the# above approachimport math # Function to generate all prime# numbers less than ndef SieveOfEratosthenes(n, isPrime): # Initialize all entries of # boolean array as true. # A value in isPrime[i] # will finally be false # if i is Not a prime isPrime[0] = isPrime[1] = False for i in range(2, n + 1, 1): isPrime[i] = True p = 2 while(p * p <= n ): # If isPrime[p] is not changed, # then it is a prime if (isPrime[p] == True): # Update all multiples of p for i in range(p * 2, n + 1, p): isPrime[i] = False p += 1 # Function to return the number# of digits in a numberdef countDigit(n): return math.floor(math.log10(n) + 1) # Function to check if N is a# Brilliant numberdef isBrilliant(n): flag = 0 # Generating primes using Sieve isPrime = [0] * (n + 1) SieveOfEratosthenes(n, isPrime) # Traversing all numbers # to find first pair for i in range(2, n, 1): x = n // i if (isPrime[i] and isPrime[x] and x * i == n): if (countDigit(i) == countDigit(x)): return True return False # Driver Code # Given Numbern = 1711 # Function Callif (isBrilliant(n)): print("Yes")else: print("No") # This code is contributed by sanjoy_62
// C# implementation for the// above approachusing System;class GFG{ // Function to generate all prime// numbers less than nstatic void SieveOfEratosthenes(int n, bool []isPrime){ // Initialize all entries of // boolean array as true. // A value in isPrime[i] // will finally be false // if i is Not a prime isPrime[0] = isPrime[1] = false; for(int i = 2; i <= n; i++) isPrime[i] = true; for(int p = 2; p * p <= n; p++) { // If isPrime[p] is not changed, // then it is a prime if (isPrime[p] == true) { // Update all multiples of p for(int i = p * 2; i <= n; i += p) isPrime[i] = false; } }} // Function to return the number// of digits in a numberstatic int countDigit(int n){ int count = 0; while (n != 0) { n = n / 10; ++count; } return count;} // Function to check if N is a// Brilliant numberstatic bool isBrilliant(int n){ //int flag = 0; // Generating primes using Sieve bool []isPrime = new bool[n + 1]; SieveOfEratosthenes(n, isPrime); // Traversing all numbers // to find first pair for(int i = 2; i < n; i++) { int x = n / i; if (isPrime[i] && isPrime[x] && (x * i) == n) { if (countDigit(i) == countDigit(x)) return true; } } return false;} // Driver Codepublic static void Main(){ // Given Number int n = 1711; // Function Call if (isBrilliant(n)) Console.Write("Yes"); else Console.Write("No");}} // This code is contributed by Code_Mech
<script>// Javascript implementation for the// above approach // Function to generate all prime // numbers less than n function SieveOfEratosthenes( n, isPrime) { // Initialize all entries of // let array as true. // A value in isPrime[i] // will finally be false // if i is Not a prime isPrime[0] = isPrime[1] = false; for ( let i = 2; i <= n; i++) isPrime[i] = true; for (let p = 2; p * p <= n; p++) { // If isPrime[p] is not changed, // then it is a prime if (isPrime[p] == true) { // Update all multiples of p for (let i = p * 2; i <= n; i += p) isPrime[i] = false; } } } // Function to return the number // of digits in a number function countDigit( n) { let count = 0; while (n != 0) { n = parseInt(n / 10); ++count; } return count; } // Function to check if N is a // Brilliant number function isBrilliant( n) { let flag = 0; // Generating primes using Sieve let isPrime = Array(n + 1).fill(true); SieveOfEratosthenes(n, isPrime); // Traversing all numbers // to find first pair for ( let i = 2; i < n; i++) { let x = n / i; if (isPrime[i] && isPrime[x] && (x * i) == n) { if (countDigit(i) == countDigit(x)) return true; } } return false; } // Driver Code // Given Number let n = 1711; // Function Call if (isBrilliant(n)) document.write("Yes"); else document.write("No"); // This code contributed by Rajput-Ji </script>
Yes
Time Complexity: O(n)
Auxiliary Space: O(n)
Reference: http://oeis.org/A078972
bansal_rtk_
Code_Mech
sanjoy_62
Rajput-Ji
souravmahato348
Prime Number
series
sieve
Mathematical
Mathematical
Prime Number
series
sieve
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Find all factors of a natural number | Set 1
Check if a number is Palindrome
Program to print prime numbers from 1 to N.
Program to add two binary strings
Fizz Buzz Implementation
Program to multiply two matrices
Find pair with maximum GCD in an array
Find Union and Intersection of two unsorted arrays
Count all possible paths from top left to bottom right of a mXn matrix
Count ways to reach the n'th stair | [
{
"code": null,
"e": 24301,
"s": 24273,
"text": "\n16 Jul, 2021"
},
{
"code": null,
"e": 24426,
"s": 24301,
"text": "Brilliant Number is a number N which is the product of two primes with the same number of digits.Few Brilliant numbers are: "
},
{
"code": null,
"e": 24467,
"s": 24426,
"text": "4, 6, 9, 10, 14, 15, 21, 25, 35, 49.... "
},
{
"code": null,
"e": 24612,
"s": 24467,
"text": "Given a number N, the task is to check if N is a Brilliant Number or not. If N is a Brilliant Number then print “Yes” else print “No”.Examples: "
},
{
"code": null,
"e": 24727,
"s": 24612,
"text": "Input: N = 1711 Output: Yes Explanation: 1711 = 29*59 and both 29 and 59 have two digits.Input: N = 16 Output: No "
},
{
"code": null,
"e": 25152,
"s": 24727,
"text": "Approach: The idea is to find all the primes less than or equal to the given number N using Sieve of Eratosthenes. Once we have an array that tells all primes, we can traverse through this array to find a pair with a given product. We will find Two Prime Numbers with given product using the sieve of Eratosthenes and check if the pair has the same number of digits or not.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25156,
"s": 25152,
"text": "C++"
},
{
"code": null,
"e": 25161,
"s": 25156,
"text": "Java"
},
{
"code": null,
"e": 25169,
"s": 25161,
"text": "Python3"
},
{
"code": null,
"e": 25172,
"s": 25169,
"text": "C#"
},
{
"code": null,
"e": 25183,
"s": 25172,
"text": "Javascript"
},
{
"code": "// C++ implementation for the// above approach #include <bits/stdc++.h>using namespace std; // Function to generate all prime// numbers less than nbool SieveOfEratosthenes(int n, bool isPrime[]){ // Initialize all entries of // boolean array as true. // A value in isPrime[i] // will finally be false // if i is Not a prime isPrime[0] = isPrime[1] = false; for (int i = 2; i <= n; i++) isPrime[i] = true; for (int p = 2; p * p <= n; p++) { // If isPrime[p] is not changed, // then it is a prime if (isPrime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= n; i += p) isPrime[i] = false; } }} // Function to return the number// of digits in a numberint countDigit(long long n){ return floor(log10(n) + 1);} // Function to check if N is a// Brilliant numberbool isBrilliant(int n){ int flag = 0; // Generating primes using Sieve bool isPrime[n + 1]; SieveOfEratosthenes(n, isPrime); // Traversing all numbers // to find first pair for (int i = 2; i < n; i++) { int x = n / i; if (isPrime[i] && isPrime[x] and x * i == n) { if (countDigit(i) == countDigit(x)) return true; } } return false;} // Driver Codeint main(){ // Given Number int n = 1711; // Function Call if (isBrilliant(n)) cout << \"Yes\"; else cout << \"No\"; return 0;}",
"e": 26669,
"s": 25183,
"text": null
},
{
"code": "// Java implementation for the// above approachimport java.util.*;class GFG{ // Function to generate all prime// numbers less than nstatic void SieveOfEratosthenes(int n, boolean isPrime[]){ // Initialize all entries of // boolean array as true. // A value in isPrime[i] // will finally be false // if i is Not a prime isPrime[0] = isPrime[1] = false; for (int i = 2; i <= n; i++) isPrime[i] = true; for (int p = 2; p * p <= n; p++) { // If isPrime[p] is not changed, // then it is a prime if (isPrime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= n; i += p) isPrime[i] = false; } }} // Function to return the number// of digits in a numberstatic int countDigit(int n){ int count = 0; while (n != 0) { n = n / 10; ++count; } return count;} // Function to check if N is a// Brilliant numberstatic boolean isBrilliant(int n){ int flag = 0; // Generating primes using Sieve boolean isPrime[] = new boolean[n + 1]; SieveOfEratosthenes(n, isPrime); // Traversing all numbers // to find first pair for (int i = 2; i < n; i++) { int x = n / i; if (isPrime[i] && isPrime[x] && (x * i) == n) { if (countDigit(i) == countDigit(x)) return true; } } return false;} // Driver Codepublic static void main (String[] args){ // Given Number int n = 1711; // Function Call if (isBrilliant(n)) System.out.print(\"Yes\"); else System.out.print(\"No\");}} // This code is contributed by Ritik Bansal",
"e": 28374,
"s": 26669,
"text": null
},
{
"code": "# Python3 program for the# above approachimport math # Function to generate all prime# numbers less than ndef SieveOfEratosthenes(n, isPrime): # Initialize all entries of # boolean array as true. # A value in isPrime[i] # will finally be false # if i is Not a prime isPrime[0] = isPrime[1] = False for i in range(2, n + 1, 1): isPrime[i] = True p = 2 while(p * p <= n ): # If isPrime[p] is not changed, # then it is a prime if (isPrime[p] == True): # Update all multiples of p for i in range(p * 2, n + 1, p): isPrime[i] = False p += 1 # Function to return the number# of digits in a numberdef countDigit(n): return math.floor(math.log10(n) + 1) # Function to check if N is a# Brilliant numberdef isBrilliant(n): flag = 0 # Generating primes using Sieve isPrime = [0] * (n + 1) SieveOfEratosthenes(n, isPrime) # Traversing all numbers # to find first pair for i in range(2, n, 1): x = n // i if (isPrime[i] and isPrime[x] and x * i == n): if (countDigit(i) == countDigit(x)): return True return False # Driver Code # Given Numbern = 1711 # Function Callif (isBrilliant(n)): print(\"Yes\")else: print(\"No\") # This code is contributed by sanjoy_62",
"e": 29773,
"s": 28374,
"text": null
},
{
"code": "// C# implementation for the// above approachusing System;class GFG{ // Function to generate all prime// numbers less than nstatic void SieveOfEratosthenes(int n, bool []isPrime){ // Initialize all entries of // boolean array as true. // A value in isPrime[i] // will finally be false // if i is Not a prime isPrime[0] = isPrime[1] = false; for(int i = 2; i <= n; i++) isPrime[i] = true; for(int p = 2; p * p <= n; p++) { // If isPrime[p] is not changed, // then it is a prime if (isPrime[p] == true) { // Update all multiples of p for(int i = p * 2; i <= n; i += p) isPrime[i] = false; } }} // Function to return the number// of digits in a numberstatic int countDigit(int n){ int count = 0; while (n != 0) { n = n / 10; ++count; } return count;} // Function to check if N is a// Brilliant numberstatic bool isBrilliant(int n){ //int flag = 0; // Generating primes using Sieve bool []isPrime = new bool[n + 1]; SieveOfEratosthenes(n, isPrime); // Traversing all numbers // to find first pair for(int i = 2; i < n; i++) { int x = n / i; if (isPrime[i] && isPrime[x] && (x * i) == n) { if (countDigit(i) == countDigit(x)) return true; } } return false;} // Driver Codepublic static void Main(){ // Given Number int n = 1711; // Function Call if (isBrilliant(n)) Console.Write(\"Yes\"); else Console.Write(\"No\");}} // This code is contributed by Code_Mech",
"e": 31430,
"s": 29773,
"text": null
},
{
"code": "<script>// Javascript implementation for the// above approach // Function to generate all prime // numbers less than n function SieveOfEratosthenes( n, isPrime) { // Initialize all entries of // let array as true. // A value in isPrime[i] // will finally be false // if i is Not a prime isPrime[0] = isPrime[1] = false; for ( let i = 2; i <= n; i++) isPrime[i] = true; for (let p = 2; p * p <= n; p++) { // If isPrime[p] is not changed, // then it is a prime if (isPrime[p] == true) { // Update all multiples of p for (let i = p * 2; i <= n; i += p) isPrime[i] = false; } } } // Function to return the number // of digits in a number function countDigit( n) { let count = 0; while (n != 0) { n = parseInt(n / 10); ++count; } return count; } // Function to check if N is a // Brilliant number function isBrilliant( n) { let flag = 0; // Generating primes using Sieve let isPrime = Array(n + 1).fill(true); SieveOfEratosthenes(n, isPrime); // Traversing all numbers // to find first pair for ( let i = 2; i < n; i++) { let x = n / i; if (isPrime[i] && isPrime[x] && (x * i) == n) { if (countDigit(i) == countDigit(x)) return true; } } return false; } // Driver Code // Given Number let n = 1711; // Function Call if (isBrilliant(n)) document.write(\"Yes\"); else document.write(\"No\"); // This code contributed by Rajput-Ji </script>",
"e": 33222,
"s": 31430,
"text": null
},
{
"code": null,
"e": 33226,
"s": 33222,
"text": "Yes"
},
{
"code": null,
"e": 33250,
"s": 33228,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 33272,
"s": 33250,
"text": "Auxiliary Space: O(n)"
},
{
"code": null,
"e": 33308,
"s": 33272,
"text": "Reference: http://oeis.org/A078972 "
},
{
"code": null,
"e": 33320,
"s": 33308,
"text": "bansal_rtk_"
},
{
"code": null,
"e": 33330,
"s": 33320,
"text": "Code_Mech"
},
{
"code": null,
"e": 33340,
"s": 33330,
"text": "sanjoy_62"
},
{
"code": null,
"e": 33350,
"s": 33340,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 33366,
"s": 33350,
"text": "souravmahato348"
},
{
"code": null,
"e": 33379,
"s": 33366,
"text": "Prime Number"
},
{
"code": null,
"e": 33386,
"s": 33379,
"text": "series"
},
{
"code": null,
"e": 33392,
"s": 33386,
"text": "sieve"
},
{
"code": null,
"e": 33405,
"s": 33392,
"text": "Mathematical"
},
{
"code": null,
"e": 33418,
"s": 33405,
"text": "Mathematical"
},
{
"code": null,
"e": 33431,
"s": 33418,
"text": "Prime Number"
},
{
"code": null,
"e": 33438,
"s": 33431,
"text": "series"
},
{
"code": null,
"e": 33444,
"s": 33438,
"text": "sieve"
},
{
"code": null,
"e": 33542,
"s": 33444,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33551,
"s": 33542,
"text": "Comments"
},
{
"code": null,
"e": 33564,
"s": 33551,
"text": "Old Comments"
},
{
"code": null,
"e": 33609,
"s": 33564,
"text": "Find all factors of a natural number | Set 1"
},
{
"code": null,
"e": 33641,
"s": 33609,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 33685,
"s": 33641,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 33719,
"s": 33685,
"text": "Program to add two binary strings"
},
{
"code": null,
"e": 33744,
"s": 33719,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 33777,
"s": 33744,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 33816,
"s": 33777,
"text": "Find pair with maximum GCD in an array"
},
{
"code": null,
"e": 33867,
"s": 33816,
"text": "Find Union and Intersection of two unsorted arrays"
},
{
"code": null,
"e": 33938,
"s": 33867,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
}
] |
RequireJS - Module Loading | Modules are loaded using the define() function in js file. The syntax for loading the module in html file is as shown below −
<script data-main = "main" src = "require.js"></script>
In the script tag given above, main is used to set up packages that are relative to require.js, which in this example are the source packages team1 and team2 −
The following example describe how to define and load the module in RequireJS. Create an html file with the name index.html, and place the following code in it.
<!DOCTYPE html>
<html>
<head>
<script data-main = "main" src = "require.js"></script>
</head>
<body>
<h2>RequireJS Example</h2>
</body>
</html>
Create a js file with the name main.js, and place the following code in it.
define(function (require) {
var team1 = require("./team1");
var team2 = require("./team2");
alert("Welcome to Tutorialpoint");
document.write("<h4>Hyderabad Team: </h4>" + "<br>" + " Team:"+team1.team +"<br>
"+"Captain:" +team1.captain +"<br>");
document.write("<h4>Bangalore Team: </h4>" + "<br>" + " Team:"+team2.team +"<br>
"+"Captain:"+team2.captain +"<br>");
});
Create two more js files with the names team1.js and team2.js, and place the following codes respectively.
For team1 −
define({
team: "Sunrisers Hyderabad",
captain : " David Warner"
});
For team2 −
define({
team: "RCB",
captain : "Virat Kohli"
});
Open the HTML file in a browser; you will receive an output as in the following screenshot −
Next, click on the "OK" button, you will get another output from modules as in the following screenshot −
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1968,
"s": 1842,
"text": "Modules are loaded using the define() function in js file. The syntax for loading the module in html file is as shown below −"
},
{
"code": null,
"e": 2024,
"s": 1968,
"text": "<script data-main = \"main\" src = \"require.js\"></script>"
},
{
"code": null,
"e": 2184,
"s": 2024,
"text": "In the script tag given above, main is used to set up packages that are relative to require.js, which in this example are the source packages team1 and team2 −"
},
{
"code": null,
"e": 2345,
"s": 2184,
"text": "The following example describe how to define and load the module in RequireJS. Create an html file with the name index.html, and place the following code in it."
},
{
"code": null,
"e": 2517,
"s": 2345,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <script data-main = \"main\" src = \"require.js\"></script>\n </head>\n \n <body>\n <h2>RequireJS Example</h2>\n </body>\n</html>"
},
{
"code": null,
"e": 2593,
"s": 2517,
"text": "Create a js file with the name main.js, and place the following code in it."
},
{
"code": null,
"e": 2996,
"s": 2593,
"text": "define(function (require) {\n var team1 = require(\"./team1\");\n var team2 = require(\"./team2\");\n\n alert(\"Welcome to Tutorialpoint\");\n document.write(\"<h4>Hyderabad Team: </h4>\" + \"<br>\" + \" Team:\"+team1.team +\"<br>\n \"+\"Captain:\" +team1.captain +\"<br>\");\n \n document.write(\"<h4>Bangalore Team: </h4>\" + \"<br>\" + \" Team:\"+team2.team +\"<br>\n \"+\"Captain:\"+team2.captain +\"<br>\"); \n});"
},
{
"code": null,
"e": 3103,
"s": 2996,
"text": "Create two more js files with the names team1.js and team2.js, and place the following codes respectively."
},
{
"code": null,
"e": 3115,
"s": 3103,
"text": "For team1 −"
},
{
"code": null,
"e": 3189,
"s": 3115,
"text": "define({\n team: \"Sunrisers Hyderabad\",\n captain : \" David Warner\"\n});"
},
{
"code": null,
"e": 3201,
"s": 3189,
"text": "For team2 −"
},
{
"code": null,
"e": 3257,
"s": 3201,
"text": "define({\n team: \"RCB\",\n captain : \"Virat Kohli\"\n});"
},
{
"code": null,
"e": 3350,
"s": 3257,
"text": "Open the HTML file in a browser; you will receive an output as in the following screenshot −"
},
{
"code": null,
"e": 3456,
"s": 3350,
"text": "Next, click on the \"OK\" button, you will get another output from modules as in the following screenshot −"
},
{
"code": null,
"e": 3463,
"s": 3456,
"text": " Print"
},
{
"code": null,
"e": 3474,
"s": 3463,
"text": " Add Notes"
}
] |
Java Program to Implement Playfair Cipher Algorithm - GeeksforGeeks | 11 Nov, 2021
Cipher is an algorithm for encryption and decryption. The cipher text is a process that applies to different types of algorithms to convert plain text to coded text. It is referred to as ciphertext. The Playfair cipher was the first practical digraph substitution cipher. The scheme was invented in 1854 by Charles Wheatstone but was named after Lord Playfair who promoted the use of the cipher. In Playfair cipher unlike traditional cipher, we encrypt a pair of alphabets(digraphs) instead of a single alphabet. It was used for tactical purposes by British forces in the Second Boer War and in World War I and for the same purpose by the Australians during World War II. This was because Playfair is reasonably fast to use and requires no special equipment.
Algorithm:
Create a matrix of 5 cross 5 is made in which all the alphabet of English letters is placed in it. Now, you must be wondering that there are 26 alphabets while the matrix is only having 25 cells. To resolve it alphabets ‘i’ and ‘j’ are placed into a single cell.
Now insert the key and put the remaining alphabets in the matrix. The matrix is made by inserting the value of the key and remaining alphabets into the matrix row-wise from left to right.
Convert the text into pairs of alphabets keeping in mind no two alphabets should repeat consecutively. For example: ‘code’ is written as ‘co’,’de’
If the letter is repeating then add ‘x’ to make as many pair sets as many times the alphabet is repeating. For example: ‘helloh’ is written as ‘he’ ‘lx‘, ‘lx‘, ‘oh’. Here letter ‘l’ was consecutive for 2 times hence two sets and two additions of ‘x”s
Now if after breakdown into pairs, a letter is left alone add ‘z’ to the letter just like we have added ‘x’. For example: ‘hello’ is written as ‘he’ ‘lx’, ‘lx’, ‘oz‘
Solve the matrix or forming code using 3 standard rules
If both the alphabet are in the same row, replace them with alphabets to their immediate right.
If both the alphabets are in the same column, replace them with alphabets immediately below them.
If not in the same row or column, replace them with alphabets in the same row respectively, but at other pair of corners
Create a matrix of 5 cross 5 is made in which all the alphabet of English letters is placed in it. Now, you must be wondering that there are 26 alphabets while the matrix is only having 25 cells. To resolve it alphabets ‘i’ and ‘j’ are placed into a single cell.
Now insert the key and put the remaining alphabets in the matrix. The matrix is made by inserting the value of the key and remaining alphabets into the matrix row-wise from left to right.
Convert the text into pairs of alphabets keeping in mind no two alphabets should repeat consecutively. For example: ‘code’ is written as ‘co’,’de’
If the letter is repeating then add ‘x’ to make as many pair sets as many times the alphabet is repeating. For example: ‘helloh’ is written as ‘he’ ‘lx‘, ‘lx‘, ‘oh’. Here letter ‘l’ was consecutive for 2 times hence two sets and two additions of ‘x”s
Now if after breakdown into pairs, a letter is left alone add ‘z’ to the letter just like we have added ‘x’. For example: ‘hello’ is written as ‘he’ ‘lx’, ‘lx’, ‘oz‘
Solve the matrix or forming code using 3 standard rules
If both the alphabet are in the same row, replace them with alphabets to their immediate right.
If both the alphabets are in the same column, replace them with alphabets immediately below them.
If not in the same row or column, replace them with alphabets in the same row respectively, but at other pair of corners
If both the alphabet are in the same row, replace them with alphabets to their immediate right.
If both the alphabets are in the same column, replace them with alphabets immediately below them.
If not in the same row or column, replace them with alphabets in the same row respectively, but at other pair of corners
Illustration:
Implementation:
Generate the key Square(5×5)
Encrypt the Plaintext
Example
Java
// Java Program for Playfair Cipher Algorithm
// Importing all utility classes
import java.util.*;
// Main class
public class Main {
// Removing the duplicate values from the key
static String removeDuplicate(String s)
{
int j, index = 0, len = s.length();
char c[] = s.toCharArray();
for (int i = 0; i < len; i++) {
for (j = 0; j < i; j++) {
if (c[i] == c[j])
break;
}
if (i == j)
c[index++] = c[i];
}
s = new String((Arrays.copyOf(c, index)));
return s;
}
// Method 1
// Removing the white spaces from string 'st'
// which was replaced by the key as space.
static String removeWhiteSpace(char[] ch, String key)
{
char[] c = key.toCharArray();
// removing character which are input by the user
// from string st
for (int i = 0; i < c.length; i++) {
for (int j = 0; j < ch.length; j++) {
if (c[i] == ch[j])
c[i] = ' ';
}
}
key = new String(c);
key = key.replaceAll(" ", "");
return key;
}
// Method 2
// To make the pair for encryption in plaintext.
static String makePair(String pt)
{
String s = "";
char c = 'a';
for (int i = 0; i < pt.length(); i++) {
if (pt.charAt(i) == ' ')
continue;
else {
c = pt.charAt(i);
s += pt.charAt(i);
}
if (i < pt.length() - 1)
if (pt.charAt(i) == pt.charAt(i + 1))
s += "x";
}
// If plain text length is odd then
// adding x to make length even.
if (s.length() % 2 != 0)
s += "x";
System.out.println(s);
return s;
}
// Method 3
// To find the position of row and column in matrix
// for encryption of the pair.
static int[] findIJ(char a, char b, char x[][])
{
int[] y = new int[4];
if (a == 'j')
a = 'i';
else if (b == 'j')
b = 'i';
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (x[i][j] == a) {
y[0] = i;
y[1] = j;
}
else if (x[i][j] == b) {
y[2] = i;
y[3] = j;
}
}
}
if (y[0] == y[2]) {
y[1] += 1;
y[3] += 1;
}
else if (y[1] == y[3]) {
y[0] += 1;
y[2] += 1;
}
for (int i = 0; i < 4; i++)
y[i] %= 5;
return y;
}
// Method 4
// To encrypt the plaintext
static String encrypt(String pt, char x[][])
{
char ch[] = pt.toCharArray();
int a[] = new int[4];
for (int i = 0; i < pt.length(); i += 2) {
if (i < pt.length() - 1) {
a = findIJ(pt.charAt(i), pt.charAt(i + 1),
x);
if (a[0] == a[2]) {
ch[i] = x[a[0]][a[1]];
ch[i + 1] = x[a[0]][a[3]];
}
else if (a[1] == a[3]) {
ch[i] = x[a[0]][a[1]];
ch[i + 1] = x[a[2]][a[1]];
}
else {
ch[i] = x[a[0]][a[3]];
ch[i + 1] = x[a[2]][a[1]];
}
}
}
pt = new String(ch);
return pt;
}
// Method 5
// Main driver method
public static void main(String[] args)
{
// Creating an Scanner clas object to
// take input from user
Scanner sc = new Scanner(System.in);
String pt = "instruments";
// Key input
String key = "monarchy";
key = removeDuplicate(key);
char[] ch = key.toCharArray();
// Reading string array of Letters of english
// alphabet as Playfair to implement
String st = "abcdefghiklmnopqrstuvwxyz";
st = removeWhiteSpace(ch, st);
char[] c = st.toCharArray();
// Matrix input using above key
char[][] x = new char[5][5];
int indexOfSt = 0, indexOfKey = 0;
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (indexOfKey < key.length())
x[i][j] = ch[indexOfKey++];
else
x[i][j] = c[indexOfSt++];
}
}
// Printing Matrix
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++)
System.out.print(x[i][j] + " ");
System.out.println();
}
// For getting encrypted output
// Calling makePair() method over object created in
// main()
pt = makePair(pt);
// Calling makePair() method over object created in
// main()
pt = encrypt(pt, x);
// Print and display in the console
System.out.println(pt);
}
}
m o n a r
c h y b d
e f g i k
l p q s t
u v w x z
instrumentsx
gatlmzclrqxa
gabaa406
simmytarika5
sagartomar9927
abhishek0719kadiyan
Java
Java Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java? | [
{
"code": null,
"e": 23655,
"s": 23624,
"text": " \n11 Nov, 2021\n"
},
{
"code": null,
"e": 24414,
"s": 23655,
"text": "Cipher is an algorithm for encryption and decryption. The cipher text is a process that applies to different types of algorithms to convert plain text to coded text. It is referred to as ciphertext. The Playfair cipher was the first practical digraph substitution cipher. The scheme was invented in 1854 by Charles Wheatstone but was named after Lord Playfair who promoted the use of the cipher. In Playfair cipher unlike traditional cipher, we encrypt a pair of alphabets(digraphs) instead of a single alphabet. It was used for tactical purposes by British forces in the Second Boer War and in World War I and for the same purpose by the Australians during World War II. This was because Playfair is reasonably fast to use and requires no special equipment."
},
{
"code": null,
"e": 24425,
"s": 24414,
"text": "Algorithm:"
},
{
"code": null,
"e": 25816,
"s": 24425,
"text": "\nCreate a matrix of 5 cross 5 is made in which all the alphabet of English letters is placed in it. Now, you must be wondering that there are 26 alphabets while the matrix is only having 25 cells. To resolve it alphabets ‘i’ and ‘j’ are placed into a single cell.\nNow insert the key and put the remaining alphabets in the matrix. The matrix is made by inserting the value of the key and remaining alphabets into the matrix row-wise from left to right.\nConvert the text into pairs of alphabets keeping in mind no two alphabets should repeat consecutively. For example: ‘code’ is written as ‘co’,’de’\nIf the letter is repeating then add ‘x’ to make as many pair sets as many times the alphabet is repeating. For example: ‘helloh’ is written as ‘he’ ‘lx‘, ‘lx‘, ‘oh’. Here letter ‘l’ was consecutive for 2 times hence two sets and two additions of ‘x”s\nNow if after breakdown into pairs, a letter is left alone add ‘z’ to the letter just like we have added ‘x’. For example: ‘hello’ is written as ‘he’ ‘lx’, ‘lx’, ‘oz‘\nSolve the matrix or forming code using 3 standard rules\n\nIf both the alphabet are in the same row, replace them with alphabets to their immediate right.\nIf both the alphabets are in the same column, replace them with alphabets immediately below them.\nIf not in the same row or column, replace them with alphabets in the same row respectively, but at other pair of corners\n\n\n"
},
{
"code": null,
"e": 26079,
"s": 25816,
"text": "Create a matrix of 5 cross 5 is made in which all the alphabet of English letters is placed in it. Now, you must be wondering that there are 26 alphabets while the matrix is only having 25 cells. To resolve it alphabets ‘i’ and ‘j’ are placed into a single cell."
},
{
"code": null,
"e": 26267,
"s": 26079,
"text": "Now insert the key and put the remaining alphabets in the matrix. The matrix is made by inserting the value of the key and remaining alphabets into the matrix row-wise from left to right."
},
{
"code": null,
"e": 26414,
"s": 26267,
"text": "Convert the text into pairs of alphabets keeping in mind no two alphabets should repeat consecutively. For example: ‘code’ is written as ‘co’,’de’"
},
{
"code": null,
"e": 26665,
"s": 26414,
"text": "If the letter is repeating then add ‘x’ to make as many pair sets as many times the alphabet is repeating. For example: ‘helloh’ is written as ‘he’ ‘lx‘, ‘lx‘, ‘oh’. Here letter ‘l’ was consecutive for 2 times hence two sets and two additions of ‘x”s"
},
{
"code": null,
"e": 26831,
"s": 26665,
"text": "Now if after breakdown into pairs, a letter is left alone add ‘z’ to the letter just like we have added ‘x’. For example: ‘hello’ is written as ‘he’ ‘lx’, ‘lx’, ‘oz‘"
},
{
"code": null,
"e": 27205,
"s": 26831,
"text": "Solve the matrix or forming code using 3 standard rules\n\nIf both the alphabet are in the same row, replace them with alphabets to their immediate right.\nIf both the alphabets are in the same column, replace them with alphabets immediately below them.\nIf not in the same row or column, replace them with alphabets in the same row respectively, but at other pair of corners\n\n"
},
{
"code": null,
"e": 27301,
"s": 27205,
"text": "If both the alphabet are in the same row, replace them with alphabets to their immediate right."
},
{
"code": null,
"e": 27399,
"s": 27301,
"text": "If both the alphabets are in the same column, replace them with alphabets immediately below them."
},
{
"code": null,
"e": 27520,
"s": 27399,
"text": "If not in the same row or column, replace them with alphabets in the same row respectively, but at other pair of corners"
},
{
"code": null,
"e": 27534,
"s": 27520,
"text": "Illustration:"
},
{
"code": null,
"e": 27550,
"s": 27534,
"text": "Implementation:"
},
{
"code": null,
"e": 27579,
"s": 27550,
"text": "Generate the key Square(5×5)"
},
{
"code": null,
"e": 27601,
"s": 27579,
"text": "Encrypt the Plaintext"
},
{
"code": null,
"e": 27609,
"s": 27601,
"text": "Example"
},
{
"code": null,
"e": 27614,
"s": 27609,
"text": "Java"
},
{
"code": "\n\n\n\n\n\n\n// Java Program for Playfair Cipher Algorithm\n \n// Importing all utility classes\nimport java.util.*;\n \n// Main class\npublic class Main {\n \n // Removing the duplicate values from the key\n static String removeDuplicate(String s)\n {\n \n int j, index = 0, len = s.length();\n \n char c[] = s.toCharArray();\n \n for (int i = 0; i < len; i++) {\n \n for (j = 0; j < i; j++) {\n \n if (c[i] == c[j])\n \n break;\n }\n \n if (i == j)\n \n c[index++] = c[i];\n }\n \n s = new String((Arrays.copyOf(c, index)));\n \n return s;\n }\n \n // Method 1\n // Removing the white spaces from string 'st'\n // which was replaced by the key as space.\n static String removeWhiteSpace(char[] ch, String key)\n {\n \n char[] c = key.toCharArray();\n \n // removing character which are input by the user\n // from string st\n \n for (int i = 0; i < c.length; i++) {\n \n for (int j = 0; j < ch.length; j++) {\n \n if (c[i] == ch[j])\n \n c[i] = ' ';\n }\n }\n \n key = new String(c);\n \n key = key.replaceAll(\" \", \"\");\n \n return key;\n }\n \n // Method 2\n // To make the pair for encryption in plaintext.\n static String makePair(String pt)\n {\n \n String s = \"\";\n \n char c = 'a';\n \n for (int i = 0; i < pt.length(); i++) {\n \n if (pt.charAt(i) == ' ')\n \n continue;\n \n else {\n \n c = pt.charAt(i);\n \n s += pt.charAt(i);\n }\n \n if (i < pt.length() - 1)\n \n if (pt.charAt(i) == pt.charAt(i + 1))\n \n s += \"x\";\n }\n \n // If plain text length is odd then\n // adding x to make length even.\n if (s.length() % 2 != 0)\n \n s += \"x\";\n \n System.out.println(s);\n \n return s;\n }\n \n // Method 3\n // To find the position of row and column in matrix\n // for encryption of the pair.\n static int[] findIJ(char a, char b, char x[][])\n {\n \n int[] y = new int[4];\n \n if (a == 'j')\n \n a = 'i';\n \n else if (b == 'j')\n \n b = 'i';\n \n for (int i = 0; i < 5; i++) {\n \n for (int j = 0; j < 5; j++) {\n \n if (x[i][j] == a) {\n \n y[0] = i;\n \n y[1] = j;\n }\n \n else if (x[i][j] == b) {\n \n y[2] = i;\n \n y[3] = j;\n }\n }\n }\n \n if (y[0] == y[2]) {\n \n y[1] += 1;\n \n y[3] += 1;\n }\n \n else if (y[1] == y[3]) {\n \n y[0] += 1;\n \n y[2] += 1;\n }\n \n for (int i = 0; i < 4; i++)\n \n y[i] %= 5;\n \n return y;\n }\n \n // Method 4\n // To encrypt the plaintext\n static String encrypt(String pt, char x[][])\n {\n \n char ch[] = pt.toCharArray();\n \n int a[] = new int[4];\n \n for (int i = 0; i < pt.length(); i += 2) {\n \n if (i < pt.length() - 1) {\n \n a = findIJ(pt.charAt(i), pt.charAt(i + 1),\n x);\n \n if (a[0] == a[2]) {\n \n ch[i] = x[a[0]][a[1]];\n \n ch[i + 1] = x[a[0]][a[3]];\n }\n \n else if (a[1] == a[3]) {\n \n ch[i] = x[a[0]][a[1]];\n \n ch[i + 1] = x[a[2]][a[1]];\n }\n \n else {\n \n ch[i] = x[a[0]][a[3]];\n \n ch[i + 1] = x[a[2]][a[1]];\n }\n }\n }\n \n pt = new String(ch);\n \n return pt;\n }\n \n // Method 5\n // Main driver method\n public static void main(String[] args)\n {\n \n // Creating an Scanner clas object to\n // take input from user\n Scanner sc = new Scanner(System.in);\n \n String pt = \"instruments\";\n \n // Key input\n String key = \"monarchy\";\n \n key = removeDuplicate(key);\n \n char[] ch = key.toCharArray();\n \n // Reading string array of Letters of english\n // alphabet as Playfair to implement\n String st = \"abcdefghiklmnopqrstuvwxyz\";\n \n st = removeWhiteSpace(ch, st);\n \n char[] c = st.toCharArray();\n \n // Matrix input using above key\n char[][] x = new char[5][5];\n \n int indexOfSt = 0, indexOfKey = 0;\n \n for (int i = 0; i < 5; i++) {\n \n for (int j = 0; j < 5; j++) {\n \n if (indexOfKey < key.length())\n \n x[i][j] = ch[indexOfKey++];\n \n else\n \n x[i][j] = c[indexOfSt++];\n }\n }\n \n // Printing Matrix\n \n for (int i = 0; i < 5; i++) {\n \n for (int j = 0; j < 5; j++)\n \n System.out.print(x[i][j] + \" \");\n \n System.out.println();\n }\n \n // For getting encrypted output\n \n // Calling makePair() method over object created in\n // main()\n pt = makePair(pt);\n \n // Calling makePair() method over object created in\n // main()\n pt = encrypt(pt, x);\n \n // Print and display in the console\n System.out.println(pt);\n }\n}\n\n\n\n\n\n",
"e": 32987,
"s": 27624,
"text": null
},
{
"code": null,
"e": 33068,
"s": 32987,
"text": "m o n a r \nc h y b d \ne f g i k \nl p q s t \nu v w x z \ninstrumentsx\ngatlmzclrqxa"
},
{
"code": null,
"e": 33079,
"s": 33070,
"text": "gabaa406"
},
{
"code": null,
"e": 33092,
"s": 33079,
"text": "simmytarika5"
},
{
"code": null,
"e": 33107,
"s": 33092,
"text": "sagartomar9927"
},
{
"code": null,
"e": 33127,
"s": 33107,
"text": "abhishek0719kadiyan"
},
{
"code": null,
"e": 33134,
"s": 33127,
"text": "\nJava\n"
},
{
"code": null,
"e": 33150,
"s": 33134,
"text": "\nJava Programs\n"
},
{
"code": null,
"e": 33355,
"s": 33150,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 33385,
"s": 33355,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 33400,
"s": 33385,
"text": "Stream In Java"
},
{
"code": null,
"e": 33421,
"s": 33400,
"text": "Constructors in Java"
},
{
"code": null,
"e": 33467,
"s": 33421,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 33486,
"s": 33467,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 33530,
"s": 33486,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 33556,
"s": 33530,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 33590,
"s": 33556,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 33637,
"s": 33590,
"text": "Implementing a Linked List in Java using Class"
}
] |
Genshin Impact Social Network Analysis with Python | Towards Data Science | Genshin is an open-world action role-playing game. On top of being named one of Google Play’s best games of 2020, it is also one of the top grossing mobile games in the first half of 2021. Packaged with game is the lore, where the player and other characters weave in and out of story lines.
The way different characters in the game mention each other inspired this analysis of the social network of Genshin Impact’s characters, to answer questions such as:
Who is the most popular character in Teyvet (the world that genshin is set in)?
Who is the most important character in Teyvat?
Data is manually collated from the Genshin Impact fandom wiki
Only playable characters are considered for analysis as they tend to be the characters most players are familiar with
Character A is indicated to be connected to character B if A “mentions” B in either A’s story quest or voice lines (more on later)
Note: the data for this exploration was collected on 28 July 2021, the current banner (newest character) is Kamisato Ayaka. Inazuma characters not currently released are not included (this was written before knowledge of Inazuma’s quest line)
The data and full code used for the analysis can be found here. For brevity, code might be altered or omitted for inclusion in this writing.
Library used for the analysis is NetworkX (imported as nx)
A directed social network means ties between characters are directional and may be not mutual.
The characters are coloured according to their associated nation: green for Mondstadt, orange for Liyue, blue for Snezhnaya, purple for Inazuma, grey for the traveler (player) who is not associated with any one nation
There are a number of ties that are not reciprocated (one-way):
An example: Kadehara Kazuha → Kamisato Ayaka but there does not exist a tie going the other way, suggesting that Kazuha mentions and hence is implied to know Ayaka but Ayaka does not know Kazuha. Similarly for Zhongli → Venti.
Some connections are important bridges to other nations:
The only tie between Liyue and Snezhnaya is between Zhongli and Tartaglia. Beidou’s tie to Kazuha is the only tie between Liyue and Inazuma.
This might predict how the player would be introduced to newer regions — by having the player interact with these bridging characters (e.g. Kazuha, Tartaglia) first.
The Mondstadt characters seems to be a tighter cluster (more ties) than the Liyue cluster, which might suggest that more characters in Mondstadt know each other than the characters in Liyue.
To understand how important, or central a character is in this network, centrality measures are used. Centrality measures determine how central, or important a character is in our network. The difference between each centrality measures is how “importance” is interpreted.
A directed graph has 3 centrality measures that can be applied: in and out-degree centralities and page rank centrality.
In-degree Centrality
refers to how many people are “sending ties” to a particular node. In our network, it refers to how many characters are mentioning a particular character and is a way to measure how popular a particular character is. A higher in-degree means that a character is mentioned a lot by others and is inferred to be more popular.
# putting the chracters into a dataframe
dir_nodes_df = pd.DataFrame(data=nodes, columns=['id', 'nation'])
# calculating each character's in-degree centrality
dir_nodes_df['in_degree'] = dir_nodes_df['id'].apply(lambda n: DG.in_degree(n))
The average in-degree centrality is 7 — each character has about 7 other characters mentioning them.
The most popular characters are mostly from Mondstadt, with Jean, Lisa, Kaeya and Klee nearly doubling the average.
With knowledge of the storyline, this result makes sense. The top 5 most popular characters are part of the governing body of Mondstadt and are frequently seen together.
Out-degree centrality
is the reverse of in-degree centralityt, referring to how many characters a particular character is directly sending ties to. In our network, this is a way to measure how many characters a particular character knows.
# calculating each character's out-degree centrality
dir_nodes_df['out_degree'] = dir_nodes_df['id'].apply(lambda n: DG.out_degree(n))
The average out-degree centrality is 7 — each character mentions about 7 other characters
The most sociable values here do not show variance as drastic as for in-degree
Interestingly, the average (when the decimals are included) in-degree and out-degree for the network are almost exactly the same, but the distribution of in-degree and out-degree counts differ.
Out-degree shows a distribution closer to a normal distribution
Page Rank Centrality
adds an additional consideration for influence — what matters more than the number of characters mentioning a character (in-degree) is how many influential ties are in-coming. A higher page rank centrality value suggests that a character is connected to more influencial characters and has a wider reach beyond their direct ties.
# calculate page rank for each character
pr = nx.pagerank(DG)
dir_nodes_df['page_rank'] = dir_nodes_df['id'].apply(lambda n: pr[n])
Most characters on this list have been previously listed as having some of the highest in-degree centrality values, so they are not only popular but also know other well-known characters
For further analysis of the network, it becomes necessary to convert the directed graph to an undirected one. a major consideration in this process is the treatment of one-way (asymmetrical) ties. An undirected tie implies that a tie is mutual (go both ways), which in our context means that the 2 characters know each other (enough to mention each other). As such, it would be more meaningful to drop all one-way ties in our undirected network and only consider mutual (reciprocated) ties between characters.
Requiring ties to be 2-way caused the graph to have isolates which are characters not connected to other characters (poor traveler)
This network looks sparser in ties compared to the directed one
Isolates are unlikely to be central to this network (mainly because they are not part of it), they will be removed moving forward.
Having the network be undirected allows the usage of centrality measures beyond degree centrality: closeness, betweenness, eigenvector centralities.
Degree Centralityplaces importance on how many characters a character is directly connected to. A simplistic way to gauge a character’s importance in the network — character is important if they know a lot of other characters, but still a good basis for comparison with other measures of importance explained later on.
Diluc was previously ranked on top with having high in-degree centrality is no longer on the list once mutual ties is enforced, suggesting that although he is mentioned by many characters, he doesn’t seem to know them (quite in-character oddly...)
Closeness Centralityplaces importance on how many characters a character is indirectly connected to, by measuring how many times it is in the shortest path between other characters. A more important character here is one that can reach more characters via the shortest path — able to spread information to the most characters in the network the fastest.
Majority of characters on this list do not have the highest degree centrality (know a lot of other characters) but are able to reach the most number of other characters the fastest
Looking back at the undirected network (fig 7), characters with higher closeness centrality values are ties between Mondstadt and Liyue — Diona, Xiangling, Albedo, Xingqiu, Eula, Yanfei, which explains their high importance given that these characters have the connections to spread information to a wider audience beyond their own nation
Betweenness Centralityputs importance on information brokers in the network, the characters who are “in-between” the pairs of characters that want to reach each other. Characters with higher “in-betweenness” allow these characters more control of information flow, which is what makes them important.
Note how compared to closeness centrality, betweenness centrality produces a different ranking list of characters
Once again, characters with higher betweenness centrality values are those that connect Mondstadt to Liyue — Diona, Xiangling, Albedo, Xingqiu, Eula, Yanfei, indicating that they are important brokers of information between the 2 nations
When considered with the undirected graph (fig 7), Hu Tao is the only tie Qiqi has to the rest of the network, implying that Qiqi is dependent on Hu Tao to gain or spread information to the rest of the network
The above point can also be observed for Tartaglia and Zhongli — Tartaglia is dependent on Zhongli to access and distribute information in the wider network
Eigenvector Centralitydefines importance as being connected to other influential characters in the network — being connected to well-connected characters. Higher importance is placed on ties to more well-connected characters rather than simply counting each tie as equal (which degree centrality does).
This ranking looks really similar to the degree centrality one above, except that this list only contains characters from Mondstadt, this implies that these characters do not just have a lot of ties, these ties also tend to be of a higher quality (to characters with a higher level of influence in network)
Similarly, characters who rank high in degree centrality but fail to rank high in eigenvector centrality (e.g. Ningguang) have a lot of ties but these ties are to characters with some distance from centres of power
Who is the most popular person in Teyvet?
Jean
Highest in-degree centrality (directed network)
Highest degree centrality (undirected network)
Difficult to deny that a lot of characters know Jean, enough to talk about her
In the storyline as well, she is one of the first characters the player would hear about before meeting her
Who is the most important character in Teyvat?
Kaeya
This is less easy to answer, what is considered important might be subjective and requires a more holistic look at each node’s role in the social network
A simple way would be to average each character’s rank across the various undirected network centralities, which points to Jean being the most important
However, Kaeya has a more advantageous place in the social network as he is in the top 10 rankings for all the applied character importance measures and is not just popular but also an important character that can control the flow of information in the social network
In Teyvat, you should know Jean, but if you need information, look for Kaeya. | [
{
"code": null,
"e": 463,
"s": 171,
"text": "Genshin is an open-world action role-playing game. On top of being named one of Google Play’s best games of 2020, it is also one of the top grossing mobile games in the first half of 2021. Packaged with game is the lore, where the player and other characters weave in and out of story lines."
},
{
"code": null,
"e": 629,
"s": 463,
"text": "The way different characters in the game mention each other inspired this analysis of the social network of Genshin Impact’s characters, to answer questions such as:"
},
{
"code": null,
"e": 709,
"s": 629,
"text": "Who is the most popular character in Teyvet (the world that genshin is set in)?"
},
{
"code": null,
"e": 756,
"s": 709,
"text": "Who is the most important character in Teyvat?"
},
{
"code": null,
"e": 818,
"s": 756,
"text": "Data is manually collated from the Genshin Impact fandom wiki"
},
{
"code": null,
"e": 936,
"s": 818,
"text": "Only playable characters are considered for analysis as they tend to be the characters most players are familiar with"
},
{
"code": null,
"e": 1067,
"s": 936,
"text": "Character A is indicated to be connected to character B if A “mentions” B in either A’s story quest or voice lines (more on later)"
},
{
"code": null,
"e": 1310,
"s": 1067,
"text": "Note: the data for this exploration was collected on 28 July 2021, the current banner (newest character) is Kamisato Ayaka. Inazuma characters not currently released are not included (this was written before knowledge of Inazuma’s quest line)"
},
{
"code": null,
"e": 1451,
"s": 1310,
"text": "The data and full code used for the analysis can be found here. For brevity, code might be altered or omitted for inclusion in this writing."
},
{
"code": null,
"e": 1510,
"s": 1451,
"text": "Library used for the analysis is NetworkX (imported as nx)"
},
{
"code": null,
"e": 1605,
"s": 1510,
"text": "A directed social network means ties between characters are directional and may be not mutual."
},
{
"code": null,
"e": 1823,
"s": 1605,
"text": "The characters are coloured according to their associated nation: green for Mondstadt, orange for Liyue, blue for Snezhnaya, purple for Inazuma, grey for the traveler (player) who is not associated with any one nation"
},
{
"code": null,
"e": 1887,
"s": 1823,
"text": "There are a number of ties that are not reciprocated (one-way):"
},
{
"code": null,
"e": 2114,
"s": 1887,
"text": "An example: Kadehara Kazuha → Kamisato Ayaka but there does not exist a tie going the other way, suggesting that Kazuha mentions and hence is implied to know Ayaka but Ayaka does not know Kazuha. Similarly for Zhongli → Venti."
},
{
"code": null,
"e": 2171,
"s": 2114,
"text": "Some connections are important bridges to other nations:"
},
{
"code": null,
"e": 2312,
"s": 2171,
"text": "The only tie between Liyue and Snezhnaya is between Zhongli and Tartaglia. Beidou’s tie to Kazuha is the only tie between Liyue and Inazuma."
},
{
"code": null,
"e": 2478,
"s": 2312,
"text": "This might predict how the player would be introduced to newer regions — by having the player interact with these bridging characters (e.g. Kazuha, Tartaglia) first."
},
{
"code": null,
"e": 2669,
"s": 2478,
"text": "The Mondstadt characters seems to be a tighter cluster (more ties) than the Liyue cluster, which might suggest that more characters in Mondstadt know each other than the characters in Liyue."
},
{
"code": null,
"e": 2942,
"s": 2669,
"text": "To understand how important, or central a character is in this network, centrality measures are used. Centrality measures determine how central, or important a character is in our network. The difference between each centrality measures is how “importance” is interpreted."
},
{
"code": null,
"e": 3063,
"s": 2942,
"text": "A directed graph has 3 centrality measures that can be applied: in and out-degree centralities and page rank centrality."
},
{
"code": null,
"e": 3084,
"s": 3063,
"text": "In-degree Centrality"
},
{
"code": null,
"e": 3408,
"s": 3084,
"text": "refers to how many people are “sending ties” to a particular node. In our network, it refers to how many characters are mentioning a particular character and is a way to measure how popular a particular character is. A higher in-degree means that a character is mentioned a lot by others and is inferred to be more popular."
},
{
"code": null,
"e": 3449,
"s": 3408,
"text": "# putting the chracters into a dataframe"
},
{
"code": null,
"e": 3515,
"s": 3449,
"text": "dir_nodes_df = pd.DataFrame(data=nodes, columns=['id', 'nation'])"
},
{
"code": null,
"e": 3517,
"s": 3515,
"text": ""
},
{
"code": null,
"e": 3569,
"s": 3517,
"text": "# calculating each character's in-degree centrality"
},
{
"code": null,
"e": 3649,
"s": 3569,
"text": "dir_nodes_df['in_degree'] = dir_nodes_df['id'].apply(lambda n: DG.in_degree(n))"
},
{
"code": null,
"e": 3750,
"s": 3649,
"text": "The average in-degree centrality is 7 — each character has about 7 other characters mentioning them."
},
{
"code": null,
"e": 3866,
"s": 3750,
"text": "The most popular characters are mostly from Mondstadt, with Jean, Lisa, Kaeya and Klee nearly doubling the average."
},
{
"code": null,
"e": 4036,
"s": 3866,
"text": "With knowledge of the storyline, this result makes sense. The top 5 most popular characters are part of the governing body of Mondstadt and are frequently seen together."
},
{
"code": null,
"e": 4058,
"s": 4036,
"text": "Out-degree centrality"
},
{
"code": null,
"e": 4275,
"s": 4058,
"text": "is the reverse of in-degree centralityt, referring to how many characters a particular character is directly sending ties to. In our network, this is a way to measure how many characters a particular character knows."
},
{
"code": null,
"e": 4328,
"s": 4275,
"text": "# calculating each character's out-degree centrality"
},
{
"code": null,
"e": 4410,
"s": 4328,
"text": "dir_nodes_df['out_degree'] = dir_nodes_df['id'].apply(lambda n: DG.out_degree(n))"
},
{
"code": null,
"e": 4500,
"s": 4410,
"text": "The average out-degree centrality is 7 — each character mentions about 7 other characters"
},
{
"code": null,
"e": 4579,
"s": 4500,
"text": "The most sociable values here do not show variance as drastic as for in-degree"
},
{
"code": null,
"e": 4773,
"s": 4579,
"text": "Interestingly, the average (when the decimals are included) in-degree and out-degree for the network are almost exactly the same, but the distribution of in-degree and out-degree counts differ."
},
{
"code": null,
"e": 4837,
"s": 4773,
"text": "Out-degree shows a distribution closer to a normal distribution"
},
{
"code": null,
"e": 4858,
"s": 4837,
"text": "Page Rank Centrality"
},
{
"code": null,
"e": 5188,
"s": 4858,
"text": "adds an additional consideration for influence — what matters more than the number of characters mentioning a character (in-degree) is how many influential ties are in-coming. A higher page rank centrality value suggests that a character is connected to more influencial characters and has a wider reach beyond their direct ties."
},
{
"code": null,
"e": 5229,
"s": 5188,
"text": "# calculate page rank for each character"
},
{
"code": null,
"e": 5250,
"s": 5229,
"text": "pr = nx.pagerank(DG)"
},
{
"code": null,
"e": 5320,
"s": 5250,
"text": "dir_nodes_df['page_rank'] = dir_nodes_df['id'].apply(lambda n: pr[n])"
},
{
"code": null,
"e": 5507,
"s": 5320,
"text": "Most characters on this list have been previously listed as having some of the highest in-degree centrality values, so they are not only popular but also know other well-known characters"
},
{
"code": null,
"e": 6017,
"s": 5507,
"text": "For further analysis of the network, it becomes necessary to convert the directed graph to an undirected one. a major consideration in this process is the treatment of one-way (asymmetrical) ties. An undirected tie implies that a tie is mutual (go both ways), which in our context means that the 2 characters know each other (enough to mention each other). As such, it would be more meaningful to drop all one-way ties in our undirected network and only consider mutual (reciprocated) ties between characters."
},
{
"code": null,
"e": 6149,
"s": 6017,
"text": "Requiring ties to be 2-way caused the graph to have isolates which are characters not connected to other characters (poor traveler)"
},
{
"code": null,
"e": 6213,
"s": 6149,
"text": "This network looks sparser in ties compared to the directed one"
},
{
"code": null,
"e": 6344,
"s": 6213,
"text": "Isolates are unlikely to be central to this network (mainly because they are not part of it), they will be removed moving forward."
},
{
"code": null,
"e": 6493,
"s": 6344,
"text": "Having the network be undirected allows the usage of centrality measures beyond degree centrality: closeness, betweenness, eigenvector centralities."
},
{
"code": null,
"e": 6812,
"s": 6493,
"text": "Degree Centralityplaces importance on how many characters a character is directly connected to. A simplistic way to gauge a character’s importance in the network — character is important if they know a lot of other characters, but still a good basis for comparison with other measures of importance explained later on."
},
{
"code": null,
"e": 7060,
"s": 6812,
"text": "Diluc was previously ranked on top with having high in-degree centrality is no longer on the list once mutual ties is enforced, suggesting that although he is mentioned by many characters, he doesn’t seem to know them (quite in-character oddly...)"
},
{
"code": null,
"e": 7414,
"s": 7060,
"text": "Closeness Centralityplaces importance on how many characters a character is indirectly connected to, by measuring how many times it is in the shortest path between other characters. A more important character here is one that can reach more characters via the shortest path — able to spread information to the most characters in the network the fastest."
},
{
"code": null,
"e": 7595,
"s": 7414,
"text": "Majority of characters on this list do not have the highest degree centrality (know a lot of other characters) but are able to reach the most number of other characters the fastest"
},
{
"code": null,
"e": 7934,
"s": 7595,
"text": "Looking back at the undirected network (fig 7), characters with higher closeness centrality values are ties between Mondstadt and Liyue — Diona, Xiangling, Albedo, Xingqiu, Eula, Yanfei, which explains their high importance given that these characters have the connections to spread information to a wider audience beyond their own nation"
},
{
"code": null,
"e": 8235,
"s": 7934,
"text": "Betweenness Centralityputs importance on information brokers in the network, the characters who are “in-between” the pairs of characters that want to reach each other. Characters with higher “in-betweenness” allow these characters more control of information flow, which is what makes them important."
},
{
"code": null,
"e": 8349,
"s": 8235,
"text": "Note how compared to closeness centrality, betweenness centrality produces a different ranking list of characters"
},
{
"code": null,
"e": 8587,
"s": 8349,
"text": "Once again, characters with higher betweenness centrality values are those that connect Mondstadt to Liyue — Diona, Xiangling, Albedo, Xingqiu, Eula, Yanfei, indicating that they are important brokers of information between the 2 nations"
},
{
"code": null,
"e": 8797,
"s": 8587,
"text": "When considered with the undirected graph (fig 7), Hu Tao is the only tie Qiqi has to the rest of the network, implying that Qiqi is dependent on Hu Tao to gain or spread information to the rest of the network"
},
{
"code": null,
"e": 8954,
"s": 8797,
"text": "The above point can also be observed for Tartaglia and Zhongli — Tartaglia is dependent on Zhongli to access and distribute information in the wider network"
},
{
"code": null,
"e": 9257,
"s": 8954,
"text": "Eigenvector Centralitydefines importance as being connected to other influential characters in the network — being connected to well-connected characters. Higher importance is placed on ties to more well-connected characters rather than simply counting each tie as equal (which degree centrality does)."
},
{
"code": null,
"e": 9564,
"s": 9257,
"text": "This ranking looks really similar to the degree centrality one above, except that this list only contains characters from Mondstadt, this implies that these characters do not just have a lot of ties, these ties also tend to be of a higher quality (to characters with a higher level of influence in network)"
},
{
"code": null,
"e": 9779,
"s": 9564,
"text": "Similarly, characters who rank high in degree centrality but fail to rank high in eigenvector centrality (e.g. Ningguang) have a lot of ties but these ties are to characters with some distance from centres of power"
},
{
"code": null,
"e": 9821,
"s": 9779,
"text": "Who is the most popular person in Teyvet?"
},
{
"code": null,
"e": 9826,
"s": 9821,
"text": "Jean"
},
{
"code": null,
"e": 9874,
"s": 9826,
"text": "Highest in-degree centrality (directed network)"
},
{
"code": null,
"e": 9921,
"s": 9874,
"text": "Highest degree centrality (undirected network)"
},
{
"code": null,
"e": 10000,
"s": 9921,
"text": "Difficult to deny that a lot of characters know Jean, enough to talk about her"
},
{
"code": null,
"e": 10108,
"s": 10000,
"text": "In the storyline as well, she is one of the first characters the player would hear about before meeting her"
},
{
"code": null,
"e": 10155,
"s": 10108,
"text": "Who is the most important character in Teyvat?"
},
{
"code": null,
"e": 10161,
"s": 10155,
"text": "Kaeya"
},
{
"code": null,
"e": 10315,
"s": 10161,
"text": "This is less easy to answer, what is considered important might be subjective and requires a more holistic look at each node’s role in the social network"
},
{
"code": null,
"e": 10468,
"s": 10315,
"text": "A simple way would be to average each character’s rank across the various undirected network centralities, which points to Jean being the most important"
},
{
"code": null,
"e": 10736,
"s": 10468,
"text": "However, Kaeya has a more advantageous place in the social network as he is in the top 10 rankings for all the applied character importance measures and is not just popular but also an important character that can control the flow of information in the social network"
}
] |
Nan (Not a Number) in Java | 13 Jan, 2017
Can You guess the output of following code fragment:
public class Test{ public static void main(String[] args) { System.out.println(2 % 0); }}
Yes, You guessed it right: ArithmeticExceptionOutput:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at traps.Test.main(Test.java:3)
Now guess the Output of :
public class Test{ public static void main(String[] args) { System.out.println(2.0 % 0); }}
Did you guessed it right ?Output:
NaN
What is NaN?
“NaN” stands for “not a number”. “Nan” is produced if a floating point operation has some input parameters that cause the operation to produce some undefined result. For example, 0.0 divided by 0.0 is arithmetically undefined. Finding out the square root of a negative number too is undefined.
//Java Program to illustrate NaNpublic class Test{ public static void main(String[] args) { System.out.println(2.0 % 0); System.out.println(0.0 / 0); System.out.println(Math.sqrt(-1)); }}
Output:
NaN
NaN
NaN
In javadoc, the constant field NaN is declared as following in the Float and Double Classes respectively.
public static final float NaN = 0f / 0f;
public static final double NaN = 0d / 0d;
How to Compare NaN Values?
All numeric operations with NaN as an operand produce NaN as a result. Reason behind this is that NaN is unordered, so a numeric comparison operation involving one or two NaNs returns false.
The numerical comparison operators <, <=, >, and >= always return false if either or both operands are NaN.(§15.20.1)
The equality operator == returns false if either operand is NaN.
The inequality operator != returns true if either operand is NaN . (§15.21.1)
// Java program to test relational operator on NaNpublic class ComparingNaN{ public static void main(String[] args) { // comparing NaN constant field defined in // Float Class System.out.print("Check if equal :"); System.out.println(Float.NaN == Float.NaN); System.out.print("Check if UNequal: "); System.out.println(Float.NaN != Float.NaN); // comparing NaN constant field defined in Double Class System.out.print("Check if equal: "); System.out.println(Double.NaN == Double.NaN); System.out.print("Check if UNequal: "); System.out.println(Double.NaN != Double.NaN); // More Examples double NaN = 2.1 % 0; System.out.println((2.1%0) == NaN); System.out.println(NaN == NaN); }}
Output:
Check if equal :false
Check if UNequal: true
Check if equal: false
Check if UNequal: true
false
false
isNaN() method
This method returns true if the value represented by this object is NaN; false otherwise.
import java.lang.*; public class isNan{ public static void main(String[] args) { Double x = new Double(-2.0/0.0); Double y = new Double(0.0/0.0); // returns false if this Double value is not a Not-a-Number (NaN) System.out.println(y + " = " + y.isNaN()); // returns true if this Double value is a Not-a-Number (NaN) System.out.println(x + " = " + x.isNaN()); }}
Output:
NaN = true
-Infinity = false
Floating type doesn’t produces Exception while operating with mathematical values
IEEE 754 floating point numbers can represent positive or negative infinity, and NaN (not a number). These three values arise from calculations whose result is undefined or cannot be represented accurately.Java is following known math facts. 1.0 / 0.0 is infinity, but the others are indeterminate forms, which Java represents as NaN (not a number).
// Java program to illustrate output of floating// point number operationspublic class Test{ public static void main(String[] args) { System.out.println(2.0 / 0); System.out.println(-2.0 / 0); System.out.println(9.0E234 / 0.1E-234); }}
Output:
Infinity
-Infinity
Infinity
References:https://docs.oracle.com/javase/7/docs/api/java/lang/Double.htmlhttps://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html
This article is contributed by Pankaj kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
How to iterate any Map in Java
Initialize an ArrayList in Java
Interfaces in Java
ArrayList in Java
Multidimensional Arrays in Java
Stack Class in Java
Singleton Class in Java
LinkedList in Java | [
{
"code": null,
"e": 24081,
"s": 24053,
"text": "\n13 Jan, 2017"
},
{
"code": null,
"e": 24134,
"s": 24081,
"text": "Can You guess the output of following code fragment:"
},
{
"code": "public class Test{ public static void main(String[] args) { System.out.println(2 % 0); }} ",
"e": 24247,
"s": 24134,
"text": null
},
{
"code": null,
"e": 24301,
"s": 24247,
"text": "Yes, You guessed it right: ArithmeticExceptionOutput:"
},
{
"code": null,
"e": 24404,
"s": 24301,
"text": "Exception in thread \"main\" java.lang.ArithmeticException: / by zero\n\tat traps.Test.main(Test.java:3)\n\n"
},
{
"code": null,
"e": 24430,
"s": 24404,
"text": "Now guess the Output of :"
},
{
"code": "public class Test{ public static void main(String[] args) { System.out.println(2.0 % 0); }} ",
"e": 24545,
"s": 24430,
"text": null
},
{
"code": null,
"e": 24579,
"s": 24545,
"text": "Did you guessed it right ?Output:"
},
{
"code": null,
"e": 24584,
"s": 24579,
"text": "NaN\n"
},
{
"code": null,
"e": 24597,
"s": 24584,
"text": "What is NaN?"
},
{
"code": null,
"e": 24891,
"s": 24597,
"text": "“NaN” stands for “not a number”. “Nan” is produced if a floating point operation has some input parameters that cause the operation to produce some undefined result. For example, 0.0 divided by 0.0 is arithmetically undefined. Finding out the square root of a negative number too is undefined."
},
{
"code": "//Java Program to illustrate NaNpublic class Test{ public static void main(String[] args) { System.out.println(2.0 % 0); System.out.println(0.0 / 0); System.out.println(Math.sqrt(-1)); }} ",
"e": 25116,
"s": 24891,
"text": null
},
{
"code": null,
"e": 25124,
"s": 25116,
"text": "Output:"
},
{
"code": null,
"e": 25137,
"s": 25124,
"text": "NaN\nNaN\nNaN\n"
},
{
"code": null,
"e": 25243,
"s": 25137,
"text": "In javadoc, the constant field NaN is declared as following in the Float and Double Classes respectively."
},
{
"code": null,
"e": 25333,
"s": 25243,
"text": "public static final float \tNaN = 0f / 0f;\npublic static final double NaN = 0d / 0d;\n"
},
{
"code": null,
"e": 25360,
"s": 25333,
"text": "How to Compare NaN Values?"
},
{
"code": null,
"e": 25551,
"s": 25360,
"text": "All numeric operations with NaN as an operand produce NaN as a result. Reason behind this is that NaN is unordered, so a numeric comparison operation involving one or two NaNs returns false."
},
{
"code": null,
"e": 25669,
"s": 25551,
"text": "The numerical comparison operators <, <=, >, and >= always return false if either or both operands are NaN.(§15.20.1)"
},
{
"code": null,
"e": 25734,
"s": 25669,
"text": "The equality operator == returns false if either operand is NaN."
},
{
"code": null,
"e": 25812,
"s": 25734,
"text": "The inequality operator != returns true if either operand is NaN . (§15.21.1)"
},
{
"code": "// Java program to test relational operator on NaNpublic class ComparingNaN{ public static void main(String[] args) { // comparing NaN constant field defined in // Float Class System.out.print(\"Check if equal :\"); System.out.println(Float.NaN == Float.NaN); System.out.print(\"Check if UNequal: \"); System.out.println(Float.NaN != Float.NaN); // comparing NaN constant field defined in Double Class System.out.print(\"Check if equal: \"); System.out.println(Double.NaN == Double.NaN); System.out.print(\"Check if UNequal: \"); System.out.println(Double.NaN != Double.NaN); // More Examples double NaN = 2.1 % 0; System.out.println((2.1%0) == NaN); System.out.println(NaN == NaN); }}",
"e": 26630,
"s": 25812,
"text": null
},
{
"code": null,
"e": 26638,
"s": 26630,
"text": "Output:"
},
{
"code": null,
"e": 26741,
"s": 26638,
"text": "Check if equal :false\nCheck if UNequal: true\nCheck if equal: false\nCheck if UNequal: true\nfalse\nfalse\n"
},
{
"code": null,
"e": 26756,
"s": 26741,
"text": "isNaN() method"
},
{
"code": null,
"e": 26846,
"s": 26756,
"text": "This method returns true if the value represented by this object is NaN; false otherwise."
},
{
"code": " import java.lang.*; public class isNan{ public static void main(String[] args) { Double x = new Double(-2.0/0.0); Double y = new Double(0.0/0.0); // returns false if this Double value is not a Not-a-Number (NaN) System.out.println(y + \" = \" + y.isNaN()); // returns true if this Double value is a Not-a-Number (NaN) System.out.println(x + \" = \" + x.isNaN()); }} ",
"e": 27271,
"s": 26846,
"text": null
},
{
"code": null,
"e": 27279,
"s": 27271,
"text": "Output:"
},
{
"code": null,
"e": 27309,
"s": 27279,
"text": "NaN = true\n-Infinity = false\n"
},
{
"code": null,
"e": 27391,
"s": 27309,
"text": "Floating type doesn’t produces Exception while operating with mathematical values"
},
{
"code": null,
"e": 27741,
"s": 27391,
"text": "IEEE 754 floating point numbers can represent positive or negative infinity, and NaN (not a number). These three values arise from calculations whose result is undefined or cannot be represented accurately.Java is following known math facts. 1.0 / 0.0 is infinity, but the others are indeterminate forms, which Java represents as NaN (not a number)."
},
{
"code": "// Java program to illustrate output of floating// point number operationspublic class Test{ public static void main(String[] args) { System.out.println(2.0 / 0); System.out.println(-2.0 / 0); System.out.println(9.0E234 / 0.1E-234); }}",
"e": 28007,
"s": 27741,
"text": null
},
{
"code": null,
"e": 28015,
"s": 28007,
"text": "Output:"
},
{
"code": null,
"e": 28044,
"s": 28015,
"text": "Infinity\n-Infinity\nInfinity\n"
},
{
"code": null,
"e": 28179,
"s": 28044,
"text": "References:https://docs.oracle.com/javase/7/docs/api/java/lang/Double.htmlhttps://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html"
},
{
"code": null,
"e": 28479,
"s": 28179,
"text": "This article is contributed by Pankaj kumar. 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": 28604,
"s": 28479,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 28609,
"s": 28604,
"text": "Java"
},
{
"code": null,
"e": 28614,
"s": 28609,
"text": "Java"
},
{
"code": null,
"e": 28712,
"s": 28614,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28721,
"s": 28712,
"text": "Comments"
},
{
"code": null,
"e": 28734,
"s": 28721,
"text": "Old Comments"
},
{
"code": null,
"e": 28785,
"s": 28734,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 28815,
"s": 28785,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 28846,
"s": 28815,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 28878,
"s": 28846,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 28897,
"s": 28878,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 28915,
"s": 28897,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 28947,
"s": 28915,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 28967,
"s": 28947,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 28991,
"s": 28967,
"text": "Singleton Class in Java"
}
] |
How to get Python exception text? | If a python code throws an exception, we can catch it and print the type, the error message, traceback and get information like file name and line number in python script where the exception occurred.
We can find the type, value, traceback parameters of the error
Type gives the type of exception that has occurred; value contains error message; traceback contains stack snapshot and many other information details about the error message.
The sys.exc_info() function returns a tuple of these three attributes, and the raise statement has a three-argument form accepting these three parts.
Getting exception type, file number and line number in sample code
import sys, os
try:
raise NotImplementedError("No error")
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print(exc_type, fname, exc_tb.tb_lineno | [
{
"code": null,
"e": 1263,
"s": 1062,
"text": "If a python code throws an exception, we can catch it and print the type, the error message, traceback and get information like file name and line number in python script where the exception occurred."
},
{
"code": null,
"e": 1326,
"s": 1263,
"text": "We can find the type, value, traceback parameters of the error"
},
{
"code": null,
"e": 1502,
"s": 1326,
"text": "Type gives the type of exception that has occurred; value contains error message; traceback contains stack snapshot and many other information details about the error message."
},
{
"code": null,
"e": 1652,
"s": 1502,
"text": "The sys.exc_info() function returns a tuple of these three attributes, and the raise statement has a three-argument form accepting these three parts."
},
{
"code": null,
"e": 1719,
"s": 1652,
"text": "Getting exception type, file number and line number in sample code"
},
{
"code": null,
"e": 1945,
"s": 1719,
"text": "import sys, os\ntry:\nraise NotImplementedError(\"No error\")\nexcept Exception as e:\nexc_type, exc_obj, exc_tb = sys.exc_info()\nfname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]\nprint(exc_type, fname, exc_tb.tb_lineno\n"
}
] |
Explain the Union to pointer in C language | A union is called as a memory location, which is shared by several variables of different data types.
The syntax is as follows −
union uniontag{
datatype member 1;
datatype member 2;
----
----
datatype member n;
};
For example,
union sample{
int a;
float b;
char c;
};
Given below are the respective declarations of union variable −
Union sample
{
int a;
float b;
char c;
}s;
Union
{
int a;
float b;
char c;
}s;
Union sample
{
int a;
float b;
char c;
};
union sample s;
When union is declared, the compiler automatically creates a variable which hold the largest variable type in the union.
At any time, only one variable can be referred.
Accessing union member is same as the structure.
Generally, the dot operator is used for accessing members.
The arrow operator ( ->) is used for accessing the members
There is no restriction while using data type in a union.
Following is the C program for union to pointer −
Live Demo
#include<stdio.h>
union abc{
int a;
char b;
};
int main(){
union abc var;
var.a=90;
union abc *p=&var;
printf("%d%c",p->a,p->b);
}
When the above program is executed, it produces the following result −
90Z | [
{
"code": null,
"e": 1164,
"s": 1062,
"text": "A union is called as a memory location, which is shared by several variables of different data types."
},
{
"code": null,
"e": 1191,
"s": 1164,
"text": "The syntax is as follows −"
},
{
"code": null,
"e": 1292,
"s": 1191,
"text": "union uniontag{\n datatype member 1;\n datatype member 2;\n ----\n ----\n datatype member n;\n};"
},
{
"code": null,
"e": 1305,
"s": 1292,
"text": "For example,"
},
{
"code": null,
"e": 1355,
"s": 1305,
"text": "union sample{\n int a;\n float b;\n char c;\n};"
},
{
"code": null,
"e": 1419,
"s": 1355,
"text": "Given below are the respective declarations of union variable −"
},
{
"code": null,
"e": 1432,
"s": 1419,
"text": "Union sample"
},
{
"code": null,
"e": 1471,
"s": 1432,
"text": "{\n int a;\n float b;\n char c;\n}s;"
},
{
"code": null,
"e": 1477,
"s": 1471,
"text": "Union"
},
{
"code": null,
"e": 1516,
"s": 1477,
"text": "{\n int a;\n float b;\n char c;\n}s;"
},
{
"code": null,
"e": 1529,
"s": 1516,
"text": "Union sample"
},
{
"code": null,
"e": 1583,
"s": 1529,
"text": "{\n int a;\n float b;\n char c;\n};\nunion sample s;"
},
{
"code": null,
"e": 1704,
"s": 1583,
"text": "When union is declared, the compiler automatically creates a variable which hold the largest variable type in the union."
},
{
"code": null,
"e": 1752,
"s": 1704,
"text": "At any time, only one variable can be referred."
},
{
"code": null,
"e": 1801,
"s": 1752,
"text": "Accessing union member is same as the structure."
},
{
"code": null,
"e": 1860,
"s": 1801,
"text": "Generally, the dot operator is used for accessing members."
},
{
"code": null,
"e": 1919,
"s": 1860,
"text": "The arrow operator ( ->) is used for accessing the members"
},
{
"code": null,
"e": 1977,
"s": 1919,
"text": "There is no restriction while using data type in a union."
},
{
"code": null,
"e": 2027,
"s": 1977,
"text": "Following is the C program for union to pointer −"
},
{
"code": null,
"e": 2038,
"s": 2027,
"text": " Live Demo"
},
{
"code": null,
"e": 2187,
"s": 2038,
"text": "#include<stdio.h>\nunion abc{\n int a;\n char b;\n};\nint main(){\n union abc var;\n var.a=90;\n union abc *p=&var;\n printf(\"%d%c\",p->a,p->b);\n}"
},
{
"code": null,
"e": 2258,
"s": 2187,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 2262,
"s": 2258,
"text": "90Z"
}
] |
Introduction to Git Data Extraction and Analysis in Python | by Xhentilo Karaj | Towards Data Science | Is there anyone in the software industry who has never used or at least heard of Git?
Git is a revolutionary tool that is quite ubiquitous in software teams nowadays. This article’s purpose is not to provide an introduction to git, there are a ton of resources that can guide you through that. Its purpose is rather to analyze git relevant data in order to get important insights from those data.
Throughout this article, we are going to extract Git related data by using the Github REST API and then analyze those data by leveraging Python’s top data analysis library, Pandas as well as an interactive data visualization library that is gaining massive popularity, Plotly. We are going to take as example data the repository of Apache Spark.
Git repositories are generally stored in source code hosting facilities. The most popular of these are Github and Bitbucket, but many others are available, like Gitea, GitLab, etc. In this article, we shall focus on Github, but the data extraction process should be similar for the other hosting facilities too.
Github provides a REST API that contains endpoints for all git related resources. In order to be able to consume Github APIs, we need to generate an access token at the Developer Settings on the Github Profile page. After having done that, we should be all set. We start our Jupyter Notebook and we begin by importing the necessary libraries:
We store in a separate file, config.pythe configuration parameters, namely the Github username and the access token that we generated earlier. The recommended way of interacting with Github is by creating a session with the API as follows:
Which are the entities related to git that may provide valuable information on how a git repository is going?
Commits are the ones that come first into mind, but there are also others like branches, pull requests, issues, contributors list, etc. Let’s say that we need to retrieve the list of commits for a given git repository. We search the Github API documentation and find the corresponding API endpoint:
GET /repos/:owner/:repo/commits
Here we need to provide as input parameters the owner and the name of the repository. We can call the above API endpoint in Python like this:
The commits variable contains the response returned from the Github API. Then we use the json() method of the json package for deserializing the above response object. However, this API call returns only 30 results, which corresponds to the number of results that are returned through a single Github API response by default. We can supply an extra parameter to our API request, per_page that allows us to increase the number of returned results up to 100, but the Apache Spark repository that we are trying to extract data from has roughly 26K commits!
No worries. The guys of Github have provided a pagination parameter, called page which combined with the per_page parameter, enable us to extract all the commits of any git repository. So now, our API request should look as follows:
We can wrap up our commits extraction process in a function, that takes as parameters the owner and the repository name and returns a list of commits:
In order to control the traversing process, within each iteration, we check the Link parameter in the headers of the response if it contains the rel="Next" attribute value, which tells us that there exists a successive page and we can continue our iteration; otherwise we stop there. In order to learn more about this approach, you can read the Traversing with Pagination guide in the Github docs.
Having extracted our commits in a list, we now can generate a Pandas Dataframe from that list of dictionaries, so we define the following function to handle that task:
The json_normalize function does properly that, it normalizes a semi-structured JSON (a list of dictionaries) into a flat table. We now invoke the above-created function by passing the necessary parameters for the Apache Spark git repository:
The same process is performed for the extraction of other resources, so I am skipping that part and you can go through it in the Github repository of this article. I have also added the possibility of storing the results in a CSV file or an SQLAlchemy supported database so that we can access those data for later analysis.
So we have our commits and branches and the other resources stored in memory (or in CSV files if you like). The next step is preprocessing those data.
Inspecting the structure of the commits dataframe, we get this result:
We are going to drop the majority of these columns and more importantly, we shall generate some time-related columns that are needed for our data analysis process. The following code transforms the commit date field into a datetime field and leverages the dt accessor object for datetimelike properties of a Pandas Series:
After dropping the unnecessary columns, our commits.head method returns:
Now we turn to the beautiful part of the data science field — the data analysis, and data visualization. What is the total number of contributors to the Spark repository?
A nice insight would be the distribution of commits by the hour of the day. We can calculate that metric because we already have generated the hour of the day for each commit of the repository. The Pandas code would be:
Now it is time to visualize some data. The Plotly Python library (plotly.py) is an interactive, open-source plotting library that supports over 40 unique chart types covering a wide range of statistical, financial, geographic, scientific, and 3-dimensional use-cases. Being a declarative programming library, Plotly allows us to write code describing what we want to make rather than how to make it. This reduces dramatically the time spent to build a figure and makes us focus more on presenting and interpreting the results.
The standard plotly imports along with the settings to run offline are:
Returning to our interesting metric of commits by the hour of the day, the plotly code needed for generating a bar chart would be nothing more than the following:
From the chart, we notice that the majority of contributions have been committed during the night :). Less activity is seen during the working hours of the day.
How is the Spark repository going over time? What has been its activity over the years? Let us create a time series chart and check it out.
It turns out that the Spark repository has seen its activity peek during 2015–2016. But can we prove that assumption? Of course, we can! We are going to calculate the daily average number of commits for each year in order to verify if 2015 and 2016 have been the most active years of the Spark repository.
The above chart shows it clearly that the repository has reached its apex in 2015 and the activity has fallen thereafter until 2017. Since that time we see a steady daily average number of commits per year and that constant trend is seen until the moment of this article’s writing.
Who are the top contributors to the Spark repository? Let’s find it out.
Being a very active repository, Spark has a lot of open pull requests too. As usual, pull requests are labeled by some predefined keywords. The following bar chart displays the number of pull requests for each label:
It is obvious that the most active contributors are working on SQL related functionalities. In the end, Spark is the data framework that allows SQL-like operations on multiple petabytes of data.
You have reached the end of this article. In this guide we went through the following important concepts:
Extracting data in Python via Github API
Preprocessing git data
Performing interactive analysis and data visualization with Pandas and Plotly
Here’s the full code for everything we ran through this article:
github.com
Thanks for reading! If you want to get in touch with me, feel free to reach me on [email protected] or my LinkedIn Profile. | [
{
"code": null,
"e": 258,
"s": 172,
"text": "Is there anyone in the software industry who has never used or at least heard of Git?"
},
{
"code": null,
"e": 569,
"s": 258,
"text": "Git is a revolutionary tool that is quite ubiquitous in software teams nowadays. This article’s purpose is not to provide an introduction to git, there are a ton of resources that can guide you through that. Its purpose is rather to analyze git relevant data in order to get important insights from those data."
},
{
"code": null,
"e": 915,
"s": 569,
"text": "Throughout this article, we are going to extract Git related data by using the Github REST API and then analyze those data by leveraging Python’s top data analysis library, Pandas as well as an interactive data visualization library that is gaining massive popularity, Plotly. We are going to take as example data the repository of Apache Spark."
},
{
"code": null,
"e": 1227,
"s": 915,
"text": "Git repositories are generally stored in source code hosting facilities. The most popular of these are Github and Bitbucket, but many others are available, like Gitea, GitLab, etc. In this article, we shall focus on Github, but the data extraction process should be similar for the other hosting facilities too."
},
{
"code": null,
"e": 1570,
"s": 1227,
"text": "Github provides a REST API that contains endpoints for all git related resources. In order to be able to consume Github APIs, we need to generate an access token at the Developer Settings on the Github Profile page. After having done that, we should be all set. We start our Jupyter Notebook and we begin by importing the necessary libraries:"
},
{
"code": null,
"e": 1810,
"s": 1570,
"text": "We store in a separate file, config.pythe configuration parameters, namely the Github username and the access token that we generated earlier. The recommended way of interacting with Github is by creating a session with the API as follows:"
},
{
"code": null,
"e": 1920,
"s": 1810,
"text": "Which are the entities related to git that may provide valuable information on how a git repository is going?"
},
{
"code": null,
"e": 2219,
"s": 1920,
"text": "Commits are the ones that come first into mind, but there are also others like branches, pull requests, issues, contributors list, etc. Let’s say that we need to retrieve the list of commits for a given git repository. We search the Github API documentation and find the corresponding API endpoint:"
},
{
"code": null,
"e": 2251,
"s": 2219,
"text": "GET /repos/:owner/:repo/commits"
},
{
"code": null,
"e": 2393,
"s": 2251,
"text": "Here we need to provide as input parameters the owner and the name of the repository. We can call the above API endpoint in Python like this:"
},
{
"code": null,
"e": 2947,
"s": 2393,
"text": "The commits variable contains the response returned from the Github API. Then we use the json() method of the json package for deserializing the above response object. However, this API call returns only 30 results, which corresponds to the number of results that are returned through a single Github API response by default. We can supply an extra parameter to our API request, per_page that allows us to increase the number of returned results up to 100, but the Apache Spark repository that we are trying to extract data from has roughly 26K commits!"
},
{
"code": null,
"e": 3180,
"s": 2947,
"text": "No worries. The guys of Github have provided a pagination parameter, called page which combined with the per_page parameter, enable us to extract all the commits of any git repository. So now, our API request should look as follows:"
},
{
"code": null,
"e": 3331,
"s": 3180,
"text": "We can wrap up our commits extraction process in a function, that takes as parameters the owner and the repository name and returns a list of commits:"
},
{
"code": null,
"e": 3729,
"s": 3331,
"text": "In order to control the traversing process, within each iteration, we check the Link parameter in the headers of the response if it contains the rel=\"Next\" attribute value, which tells us that there exists a successive page and we can continue our iteration; otherwise we stop there. In order to learn more about this approach, you can read the Traversing with Pagination guide in the Github docs."
},
{
"code": null,
"e": 3897,
"s": 3729,
"text": "Having extracted our commits in a list, we now can generate a Pandas Dataframe from that list of dictionaries, so we define the following function to handle that task:"
},
{
"code": null,
"e": 4140,
"s": 3897,
"text": "The json_normalize function does properly that, it normalizes a semi-structured JSON (a list of dictionaries) into a flat table. We now invoke the above-created function by passing the necessary parameters for the Apache Spark git repository:"
},
{
"code": null,
"e": 4464,
"s": 4140,
"text": "The same process is performed for the extraction of other resources, so I am skipping that part and you can go through it in the Github repository of this article. I have also added the possibility of storing the results in a CSV file or an SQLAlchemy supported database so that we can access those data for later analysis."
},
{
"code": null,
"e": 4615,
"s": 4464,
"text": "So we have our commits and branches and the other resources stored in memory (or in CSV files if you like). The next step is preprocessing those data."
},
{
"code": null,
"e": 4686,
"s": 4615,
"text": "Inspecting the structure of the commits dataframe, we get this result:"
},
{
"code": null,
"e": 5009,
"s": 4686,
"text": "We are going to drop the majority of these columns and more importantly, we shall generate some time-related columns that are needed for our data analysis process. The following code transforms the commit date field into a datetime field and leverages the dt accessor object for datetimelike properties of a Pandas Series:"
},
{
"code": null,
"e": 5082,
"s": 5009,
"text": "After dropping the unnecessary columns, our commits.head method returns:"
},
{
"code": null,
"e": 5253,
"s": 5082,
"text": "Now we turn to the beautiful part of the data science field — the data analysis, and data visualization. What is the total number of contributors to the Spark repository?"
},
{
"code": null,
"e": 5473,
"s": 5253,
"text": "A nice insight would be the distribution of commits by the hour of the day. We can calculate that metric because we already have generated the hour of the day for each commit of the repository. The Pandas code would be:"
},
{
"code": null,
"e": 6000,
"s": 5473,
"text": "Now it is time to visualize some data. The Plotly Python library (plotly.py) is an interactive, open-source plotting library that supports over 40 unique chart types covering a wide range of statistical, financial, geographic, scientific, and 3-dimensional use-cases. Being a declarative programming library, Plotly allows us to write code describing what we want to make rather than how to make it. This reduces dramatically the time spent to build a figure and makes us focus more on presenting and interpreting the results."
},
{
"code": null,
"e": 6072,
"s": 6000,
"text": "The standard plotly imports along with the settings to run offline are:"
},
{
"code": null,
"e": 6235,
"s": 6072,
"text": "Returning to our interesting metric of commits by the hour of the day, the plotly code needed for generating a bar chart would be nothing more than the following:"
},
{
"code": null,
"e": 6396,
"s": 6235,
"text": "From the chart, we notice that the majority of contributions have been committed during the night :). Less activity is seen during the working hours of the day."
},
{
"code": null,
"e": 6536,
"s": 6396,
"text": "How is the Spark repository going over time? What has been its activity over the years? Let us create a time series chart and check it out."
},
{
"code": null,
"e": 6842,
"s": 6536,
"text": "It turns out that the Spark repository has seen its activity peek during 2015–2016. But can we prove that assumption? Of course, we can! We are going to calculate the daily average number of commits for each year in order to verify if 2015 and 2016 have been the most active years of the Spark repository."
},
{
"code": null,
"e": 7124,
"s": 6842,
"text": "The above chart shows it clearly that the repository has reached its apex in 2015 and the activity has fallen thereafter until 2017. Since that time we see a steady daily average number of commits per year and that constant trend is seen until the moment of this article’s writing."
},
{
"code": null,
"e": 7197,
"s": 7124,
"text": "Who are the top contributors to the Spark repository? Let’s find it out."
},
{
"code": null,
"e": 7414,
"s": 7197,
"text": "Being a very active repository, Spark has a lot of open pull requests too. As usual, pull requests are labeled by some predefined keywords. The following bar chart displays the number of pull requests for each label:"
},
{
"code": null,
"e": 7609,
"s": 7414,
"text": "It is obvious that the most active contributors are working on SQL related functionalities. In the end, Spark is the data framework that allows SQL-like operations on multiple petabytes of data."
},
{
"code": null,
"e": 7715,
"s": 7609,
"text": "You have reached the end of this article. In this guide we went through the following important concepts:"
},
{
"code": null,
"e": 7756,
"s": 7715,
"text": "Extracting data in Python via Github API"
},
{
"code": null,
"e": 7779,
"s": 7756,
"text": "Preprocessing git data"
},
{
"code": null,
"e": 7857,
"s": 7779,
"text": "Performing interactive analysis and data visualization with Pandas and Plotly"
},
{
"code": null,
"e": 7922,
"s": 7857,
"text": "Here’s the full code for everything we ran through this article:"
},
{
"code": null,
"e": 7933,
"s": 7922,
"text": "github.com"
}
] |
CoffeeScript - switch statement | A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case. Here is the syntax of switch in JavaScript.
switch (expression){
case condition 1: statement(s)
break;
case condition 2: statement(s)
break;
case condition n: statement(s)
break;
default: statement(s)
}
In JavaScript, after each switch case, we have to use the break statement. If we accidentally forget the break statement, then there is a chance of falling from one switch case to other.
CoffeeScript resolves this problem by using the combination of switch-when-else clauses. Here we have an optional switch expression followed by case statements.
Each case statement have two clauses when and then. The when is followed by condition and then is followed by the set of statements that are to be executed if that particular condition is met. And finally, we have the optional else clause which holds the action for the default condition.
Given below is the syntax of the switch statement in CoffeeScript. We specify the expression without parentheses and we separate the case statements by maintaining proper indentations.
switch expression
when condition1 then statements
when condition2 then statements
when condition3 then statements
else statements
The following example demonstrates the usage of switch statement in CoffeeScript. Save this code in a file with name switch_example.coffee
name="Ramu"
score=75
message = switch
when score>=75 then "Congrats your grade is A"
when score>=60 then "Your grade is B"
when score>=50 then "Your grade is C"
when score>=35 then "Your grade is D"
else "Your grade is F and you are failed in the exam"
console.log message
Open the command prompt and compile the .coffee file as shown below.
c:\> coffee -c switch_exmple.coffee
On compiling, it gives you the following JavaScript.
// Generated by CoffeeScript 1.10.0
(function() {
var message, name, score;
name = "Ramu";
score = 75;
message = (function() {
switch (false) {
case !(score >= 75):
return "Congrats your grade is A";
case !(score >= 60):
return "Your grade is B";
case !(score >= 50):
return "Your grade is C";
case !(score >= 35):
return "Your grade is D";
default:
return "Your grade is F and you are failed in the exam";
}
})();
console.log(message);
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as −
c:\> coffee switch_exmple.coffee
On executing, the CoffeeScript file produces the following output.
Congrats your grade is A
We can also specify multiple values for a single when clause by separating them using commas (,) in the switch cases.
The following example shows how to write a CoffeeScript switch statement by specifying multiple values for the when clause. Save this code in a file with name switch_multiple_example.coffee
name="Ramu"
score=75
message = switch name
when "Ramu","Mohammed" then "You have passed the examination with grade A"
when "John","Julia" then "You have passed the examination with grade is B"
when "Rajan" then "Sorry you failed in the examination"
else "No result"
console.log message
Open the command prompt and compile the .coffee file as shown below.
c:\> coffee -c switch_multiple_example.coffee
On compiling, it gives you the following JavaScript.
// Generated by CoffeeScript 1.10.0
(function() {
var message, name, score;
name = "Ramu";
score = 75;
message = (function() {
switch (name) {
case "Ramu":
case "Mohammed":
return "You have passed the examination with grade A";
case "John":
case "Julia":
return "You have passed the examination with grade is B";
case "Rajan":
return "Sorry you failed in the examination";
default:
return "No result";
}
})();
console.log(message);
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as shown below.
c:\> coffee switch_multiple_example.coffee
On executing, the CoffeeScript file produces the following output.
You have passed the examination with grade A
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2539,
"s": 2309,
"text": "A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case. Here is the syntax of switch in JavaScript."
},
{
"code": null,
"e": 2738,
"s": 2539,
"text": "switch (expression){\n case condition 1: statement(s)\n break; \n \n case condition 2: statement(s)\n break;\n \n case condition n: statement(s)\n break;\n \n default: statement(s)\n}\n"
},
{
"code": null,
"e": 2925,
"s": 2738,
"text": "In JavaScript, after each switch case, we have to use the break statement. If we accidentally forget the break statement, then there is a chance of falling from one switch case to other."
},
{
"code": null,
"e": 3086,
"s": 2925,
"text": "CoffeeScript resolves this problem by using the combination of switch-when-else clauses. Here we have an optional switch expression followed by case statements."
},
{
"code": null,
"e": 3375,
"s": 3086,
"text": "Each case statement have two clauses when and then. The when is followed by condition and then is followed by the set of statements that are to be executed if that particular condition is met. And finally, we have the optional else clause which holds the action for the default condition."
},
{
"code": null,
"e": 3560,
"s": 3375,
"text": "Given below is the syntax of the switch statement in CoffeeScript. We specify the expression without parentheses and we separate the case statements by maintaining proper indentations."
},
{
"code": null,
"e": 3703,
"s": 3560,
"text": "switch expression\n when condition1 then statements\n when condition2 then statements\n when condition3 then statements\n else statements\n"
},
{
"code": null,
"e": 3842,
"s": 3703,
"text": "The following example demonstrates the usage of switch statement in CoffeeScript. Save this code in a file with name switch_example.coffee"
},
{
"code": null,
"e": 4131,
"s": 3842,
"text": "name=\"Ramu\"\nscore=75\nmessage = switch \n when score>=75 then \"Congrats your grade is A\"\n when score>=60 then \"Your grade is B\"\n when score>=50 then \"Your grade is C\"\n when score>=35 then \"Your grade is D\"\n else \"Your grade is F and you are failed in the exam\"\nconsole.log message"
},
{
"code": null,
"e": 4200,
"s": 4131,
"text": "Open the command prompt and compile the .coffee file as shown below."
},
{
"code": null,
"e": 4237,
"s": 4200,
"text": "c:\\> coffee -c switch_exmple.coffee\n"
},
{
"code": null,
"e": 4290,
"s": 4237,
"text": "On compiling, it gives you the following JavaScript."
},
{
"code": null,
"e": 4837,
"s": 4290,
"text": "// Generated by CoffeeScript 1.10.0\n(function() {\n var message, name, score;\n\n name = \"Ramu\";\n\n score = 75;\n\n message = (function() {\n switch (false) {\n case !(score >= 75):\n return \"Congrats your grade is A\";\n case !(score >= 60):\n return \"Your grade is B\";\n case !(score >= 50):\n return \"Your grade is C\";\n case !(score >= 35):\n return \"Your grade is D\";\n default:\n return \"Your grade is F and you are failed in the exam\";\n }\n })();\n\n console.log(message);\n\n}).call(this);"
},
{
"code": null,
"e": 4907,
"s": 4837,
"text": "Now, open the command prompt again and run the CoffeeScript file as −"
},
{
"code": null,
"e": 4941,
"s": 4907,
"text": "c:\\> coffee switch_exmple.coffee\n"
},
{
"code": null,
"e": 5008,
"s": 4941,
"text": "On executing, the CoffeeScript file produces the following output."
},
{
"code": null,
"e": 5034,
"s": 5008,
"text": "Congrats your grade is A\n"
},
{
"code": null,
"e": 5152,
"s": 5034,
"text": "We can also specify multiple values for a single when clause by separating them using commas (,) in the switch cases."
},
{
"code": null,
"e": 5342,
"s": 5152,
"text": "The following example shows how to write a CoffeeScript switch statement by specifying multiple values for the when clause. Save this code in a file with name switch_multiple_example.coffee"
},
{
"code": null,
"e": 5640,
"s": 5342,
"text": "name=\"Ramu\"\nscore=75\nmessage = switch name\n when \"Ramu\",\"Mohammed\" then \"You have passed the examination with grade A\"\n when \"John\",\"Julia\" then \"You have passed the examination with grade is B\"\n when \"Rajan\" then \"Sorry you failed in the examination\"\n else \"No result\"\nconsole.log message"
},
{
"code": null,
"e": 5709,
"s": 5640,
"text": "Open the command prompt and compile the .coffee file as shown below."
},
{
"code": null,
"e": 5756,
"s": 5709,
"text": "c:\\> coffee -c switch_multiple_example.coffee\n"
},
{
"code": null,
"e": 5809,
"s": 5756,
"text": "On compiling, it gives you the following JavaScript."
},
{
"code": null,
"e": 6349,
"s": 5809,
"text": "// Generated by CoffeeScript 1.10.0\n(function() {\n var message, name, score;\n\n name = \"Ramu\";\n\n score = 75;\n\n message = (function() {\n switch (name) {\n case \"Ramu\":\n case \"Mohammed\":\n return \"You have passed the examination with grade A\";\n case \"John\":\n case \"Julia\":\n return \"You have passed the examination with grade is B\";\n case \"Rajan\":\n return \"Sorry you failed in the examination\";\n default:\n return \"No result\";\n }\n })();\n\n console.log(message);\n\n}).call(this);"
},
{
"code": null,
"e": 6430,
"s": 6349,
"text": "Now, open the command prompt again and run the CoffeeScript file as shown below."
},
{
"code": null,
"e": 6474,
"s": 6430,
"text": "c:\\> coffee switch_multiple_example.coffee\n"
},
{
"code": null,
"e": 6541,
"s": 6474,
"text": "On executing, the CoffeeScript file produces the following output."
},
{
"code": null,
"e": 6588,
"s": 6541,
"text": "You have passed the examination with grade A \n"
},
{
"code": null,
"e": 6595,
"s": 6588,
"text": " Print"
},
{
"code": null,
"e": 6606,
"s": 6595,
"text": " Add Notes"
}
] |
Hierarchical Clustering — Explained | by Soner Yıldırım | Towards Data Science | Clustering algorithms are unsupervised machine learning algorithms so there is no label associated with data points. Clustering algorithms look for similarities or dissimilarities among data points so that similar ones can be grouped together. There are many different approaches and algorithms to perform clustering tasks. In this post, I will cover one of the common approaches which is hierarchical clustering.
Clustering simply means grouping similar things together. However, it is not as simple as it sounds. One of challenges associated with clustering is that we almost always do not know the number clusters (or groups) within the data set beforehand.
One of the advantages of hierarchical clustering is that we do not have to specify the number of clusters (but we can). Let’s dive into details after this short introduction.
Hierarchical clustering means creating a tree of clusters by iteratively grouping or separating data points. There are two types of hierarchical clustering:
Agglomerative clustering
Divisive clustering
Agglomerative clustering is kind of a bottom-up approach. Each data point is assumed to be a separate cluster at first. Then the similar clusters are iteratively combined. Let’s go over an example to explain the concept clearly.
We have a dataset consists of 9 samples. I choose numbers associated with these samples to demonstrate the concept of similarity. At each iteration (or level), the closest numbers (i.e. samples) are combined together. As you can see in the figure below, we start with 9 clusters. The closest ones are combined at the first level and then we have 7 clusters. The number of black lines that intersect with blue lines represents the number of clusters.
The figure above is called dendrogram which is a diagram representing tree-based approach. In hierarchical clustering, dendrograms are used to visualize the relationship among clusters.
As we go up, the number of clusters decreases as more samples are combined. After level 6, all samples are combined under one big cluster.
This is a very simple data set to illustrate the purpose but real life data sets are obviously more complex. We mention that “closest data points (or clusters)” are combined together. But how do the algorithms identify closest ones? There are 4 different methods implemented in scikit-learn to measure the similarity:
Ward’s linkage: Minimizes the variance of the clusters being merged. Least increase in total variance around cluster centroids is aimed.Average linkage: Average distance of each data point in two clusters.Complete (maximum) linkage: Maximum distance among all data points in two clusters.Single (minimum) linkage: Maximum distance among all data points in two clusters.
Ward’s linkage: Minimizes the variance of the clusters being merged. Least increase in total variance around cluster centroids is aimed.
Average linkage: Average distance of each data point in two clusters.
Complete (maximum) linkage: Maximum distance among all data points in two clusters.
Single (minimum) linkage: Maximum distance among all data points in two clusters.
The default selection is ward’s linkage which works well on most datasets.
One of the advantages of hierarchical clustering is that we do not have to specify the number of clusters beforehand. However, it is not wise to combine all data points into one cluster. We should stop combining clusters at some point. Scikit-learn provides two options for this:
Stop after a number of clusters is reached (n_clusters)
Set a threshold value for linkage (distance_threshold). If the distance between two clusters are above the threshold, these clusters will not be merged.
Divisive clustering is not commonly used in real life so I will mention it briefly. Simple yet clear explanation is that divisive clustering is the opposite of agglomerative clustering. We start with one giant cluster including all data points. Then data points are separated into different clusters. It is an up to bottom approach.
I will try to explain advantages and disadvantes of hierarchical clustering as well as a comparison with k-means clustering which is another widely used clustering technique.
Pros
Do not have to specify the number of clusters beforehand. The number of clusters must be specified for k-means algorithm.
It is easy to implement and interpretable with the help of dendrograms.
Always generates the same clusters. K-means clustering may result in different clusters depending on the how the centroids (center of cluster) are initiated.
Cons
It is a slower algorithm compared to k-means. Hierarchical clustering takes long time to run especially for large data sets.
Hierarchical clustering is useful and gives better results if the underlying data has some sort of hierarchy.
Some common use cases of hierarchical clustering:
Genetic or other biological data can be used to create a dendrogram to represent mutation or evolution levels. Phylogenetic trees are used to show evolutionary relationships based on similarities and differences. As stated on wikipedia:
A phylogenetic tree or evolutionary tree is a branching diagram or “tree” showing the evolutionary relationships among various biological species or other entities based upon similarities and differences in their physical or genetic characteristics.
These trees are also used to distinguish different types of viruses.
Hierarchical clustering is also used for grouping text documents. However, it is a highly complex task due the high-dimensionality of data.
Another common use case of hierarchical clustering is social network analysis.
Hierarchical clustering is also used for outlier detection.
I will use iris data set that is available under the datasets module of scikit learn. Let’s start with importing the data set:
import pandas as pdimport numpy as npfrom sklearn.datasets import load_irisiris = load_iris()X = iris.data
Iris data set includes 150 data points. I will only use the first 50 data points so that the dendrogram seems more clear.
X = X[:50, :]X.shape(50, 4)
Then we import AgglomerativeClustering class and build a model.
from sklearn.cluster import AgglomerativeClusteringmodel = AgglomerativeClustering(distance_threshold=0, n_clusters=None)
Please keep in mind that if distance_threshold parameter is not None, n_cluster parameter must be None. I do not set any condition just to visualize a complete tree.
Next step is to fit model to the data:
model = model.fit(X)
Before drawing a dendrogram, we can check the details of our model using available methods:
# Number of clustersmodel.n_clusters_50# Distances between clustersdistances = model.distances_distances.min()0.09999999999999964distances.max()3.828052620290243
Scikit learn does not provide dendrograms so we will use the dendrogram of SciPy package.
from scipy.cluster.hierarchy import dendrogramfrom scipy.cluster import hierarchy
We first create a linkage matrix:
Z = hierarchy.linkage(model.children_, 'ward')
We use the children from the model and a linkage criterion which I choose to be ‘ward’ linkage.
plt.figure(figsize=(20,10))dn = hierarchy.dendrogram(Z)
The labels of leafs are the indices of data points.
We can control the number of cluster by adjusting distance_thresold or n_cluster parameters. Let’s check the calculated distances between clusters:
model.distances_array([0.1 , 0.1 , 0.1 , 0.1 , 0.14142136, 0.14142136, 0.14142136, 0.14142136, 0.14142136, 0.14142136, 0.14142136, 0.17320508, 0.17320508, 0.18257419, 0.2 , 0.2081666 , 0.21602469, 0.21602469, 0.25819889, 0.27568098, 0.28284271, 0.29439203, 0.29439203, 0.31358146, 0.31464265, 0.31622777, 0.33166248, 0.33665016, 0.34641016, 0.36968455, 0.40620192, 0.42229532, 0.43969687, 0.43969687, 0.46726153, 0.54772256, 0.59441848, 0.6244998 , 0.6363961 , 0.66269651, 0.77628542, 0.81873887, 0.85556999, 0.90998199, 1.10513951, 1.25399362, 1.37126983, 1.91875287, 3.82805262])
Distances are in ascending order. If we can set the distance_thresold as 0.8, number of clusters will be 9. There are 8 distances greated than 0.8 so, when combined, 9 clusters will be formed.
model = AgglomerativeClustering(distance_threshold=0.8, n_clusters=None)model = model.fit(X)model.n_clusters_9
Thank you for reading. Please let me know if you have any feedback. | [
{
"code": null,
"e": 585,
"s": 171,
"text": "Clustering algorithms are unsupervised machine learning algorithms so there is no label associated with data points. Clustering algorithms look for similarities or dissimilarities among data points so that similar ones can be grouped together. There are many different approaches and algorithms to perform clustering tasks. In this post, I will cover one of the common approaches which is hierarchical clustering."
},
{
"code": null,
"e": 832,
"s": 585,
"text": "Clustering simply means grouping similar things together. However, it is not as simple as it sounds. One of challenges associated with clustering is that we almost always do not know the number clusters (or groups) within the data set beforehand."
},
{
"code": null,
"e": 1007,
"s": 832,
"text": "One of the advantages of hierarchical clustering is that we do not have to specify the number of clusters (but we can). Let’s dive into details after this short introduction."
},
{
"code": null,
"e": 1164,
"s": 1007,
"text": "Hierarchical clustering means creating a tree of clusters by iteratively grouping or separating data points. There are two types of hierarchical clustering:"
},
{
"code": null,
"e": 1189,
"s": 1164,
"text": "Agglomerative clustering"
},
{
"code": null,
"e": 1209,
"s": 1189,
"text": "Divisive clustering"
},
{
"code": null,
"e": 1438,
"s": 1209,
"text": "Agglomerative clustering is kind of a bottom-up approach. Each data point is assumed to be a separate cluster at first. Then the similar clusters are iteratively combined. Let’s go over an example to explain the concept clearly."
},
{
"code": null,
"e": 1888,
"s": 1438,
"text": "We have a dataset consists of 9 samples. I choose numbers associated with these samples to demonstrate the concept of similarity. At each iteration (or level), the closest numbers (i.e. samples) are combined together. As you can see in the figure below, we start with 9 clusters. The closest ones are combined at the first level and then we have 7 clusters. The number of black lines that intersect with blue lines represents the number of clusters."
},
{
"code": null,
"e": 2074,
"s": 1888,
"text": "The figure above is called dendrogram which is a diagram representing tree-based approach. In hierarchical clustering, dendrograms are used to visualize the relationship among clusters."
},
{
"code": null,
"e": 2213,
"s": 2074,
"text": "As we go up, the number of clusters decreases as more samples are combined. After level 6, all samples are combined under one big cluster."
},
{
"code": null,
"e": 2531,
"s": 2213,
"text": "This is a very simple data set to illustrate the purpose but real life data sets are obviously more complex. We mention that “closest data points (or clusters)” are combined together. But how do the algorithms identify closest ones? There are 4 different methods implemented in scikit-learn to measure the similarity:"
},
{
"code": null,
"e": 2901,
"s": 2531,
"text": "Ward’s linkage: Minimizes the variance of the clusters being merged. Least increase in total variance around cluster centroids is aimed.Average linkage: Average distance of each data point in two clusters.Complete (maximum) linkage: Maximum distance among all data points in two clusters.Single (minimum) linkage: Maximum distance among all data points in two clusters."
},
{
"code": null,
"e": 3038,
"s": 2901,
"text": "Ward’s linkage: Minimizes the variance of the clusters being merged. Least increase in total variance around cluster centroids is aimed."
},
{
"code": null,
"e": 3108,
"s": 3038,
"text": "Average linkage: Average distance of each data point in two clusters."
},
{
"code": null,
"e": 3192,
"s": 3108,
"text": "Complete (maximum) linkage: Maximum distance among all data points in two clusters."
},
{
"code": null,
"e": 3274,
"s": 3192,
"text": "Single (minimum) linkage: Maximum distance among all data points in two clusters."
},
{
"code": null,
"e": 3349,
"s": 3274,
"text": "The default selection is ward’s linkage which works well on most datasets."
},
{
"code": null,
"e": 3629,
"s": 3349,
"text": "One of the advantages of hierarchical clustering is that we do not have to specify the number of clusters beforehand. However, it is not wise to combine all data points into one cluster. We should stop combining clusters at some point. Scikit-learn provides two options for this:"
},
{
"code": null,
"e": 3685,
"s": 3629,
"text": "Stop after a number of clusters is reached (n_clusters)"
},
{
"code": null,
"e": 3838,
"s": 3685,
"text": "Set a threshold value for linkage (distance_threshold). If the distance between two clusters are above the threshold, these clusters will not be merged."
},
{
"code": null,
"e": 4171,
"s": 3838,
"text": "Divisive clustering is not commonly used in real life so I will mention it briefly. Simple yet clear explanation is that divisive clustering is the opposite of agglomerative clustering. We start with one giant cluster including all data points. Then data points are separated into different clusters. It is an up to bottom approach."
},
{
"code": null,
"e": 4346,
"s": 4171,
"text": "I will try to explain advantages and disadvantes of hierarchical clustering as well as a comparison with k-means clustering which is another widely used clustering technique."
},
{
"code": null,
"e": 4351,
"s": 4346,
"text": "Pros"
},
{
"code": null,
"e": 4473,
"s": 4351,
"text": "Do not have to specify the number of clusters beforehand. The number of clusters must be specified for k-means algorithm."
},
{
"code": null,
"e": 4545,
"s": 4473,
"text": "It is easy to implement and interpretable with the help of dendrograms."
},
{
"code": null,
"e": 4703,
"s": 4545,
"text": "Always generates the same clusters. K-means clustering may result in different clusters depending on the how the centroids (center of cluster) are initiated."
},
{
"code": null,
"e": 4708,
"s": 4703,
"text": "Cons"
},
{
"code": null,
"e": 4833,
"s": 4708,
"text": "It is a slower algorithm compared to k-means. Hierarchical clustering takes long time to run especially for large data sets."
},
{
"code": null,
"e": 4943,
"s": 4833,
"text": "Hierarchical clustering is useful and gives better results if the underlying data has some sort of hierarchy."
},
{
"code": null,
"e": 4993,
"s": 4943,
"text": "Some common use cases of hierarchical clustering:"
},
{
"code": null,
"e": 5230,
"s": 4993,
"text": "Genetic or other biological data can be used to create a dendrogram to represent mutation or evolution levels. Phylogenetic trees are used to show evolutionary relationships based on similarities and differences. As stated on wikipedia:"
},
{
"code": null,
"e": 5480,
"s": 5230,
"text": "A phylogenetic tree or evolutionary tree is a branching diagram or “tree” showing the evolutionary relationships among various biological species or other entities based upon similarities and differences in their physical or genetic characteristics."
},
{
"code": null,
"e": 5549,
"s": 5480,
"text": "These trees are also used to distinguish different types of viruses."
},
{
"code": null,
"e": 5689,
"s": 5549,
"text": "Hierarchical clustering is also used for grouping text documents. However, it is a highly complex task due the high-dimensionality of data."
},
{
"code": null,
"e": 5768,
"s": 5689,
"text": "Another common use case of hierarchical clustering is social network analysis."
},
{
"code": null,
"e": 5828,
"s": 5768,
"text": "Hierarchical clustering is also used for outlier detection."
},
{
"code": null,
"e": 5955,
"s": 5828,
"text": "I will use iris data set that is available under the datasets module of scikit learn. Let’s start with importing the data set:"
},
{
"code": null,
"e": 6062,
"s": 5955,
"text": "import pandas as pdimport numpy as npfrom sklearn.datasets import load_irisiris = load_iris()X = iris.data"
},
{
"code": null,
"e": 6184,
"s": 6062,
"text": "Iris data set includes 150 data points. I will only use the first 50 data points so that the dendrogram seems more clear."
},
{
"code": null,
"e": 6212,
"s": 6184,
"text": "X = X[:50, :]X.shape(50, 4)"
},
{
"code": null,
"e": 6276,
"s": 6212,
"text": "Then we import AgglomerativeClustering class and build a model."
},
{
"code": null,
"e": 6398,
"s": 6276,
"text": "from sklearn.cluster import AgglomerativeClusteringmodel = AgglomerativeClustering(distance_threshold=0, n_clusters=None)"
},
{
"code": null,
"e": 6564,
"s": 6398,
"text": "Please keep in mind that if distance_threshold parameter is not None, n_cluster parameter must be None. I do not set any condition just to visualize a complete tree."
},
{
"code": null,
"e": 6603,
"s": 6564,
"text": "Next step is to fit model to the data:"
},
{
"code": null,
"e": 6624,
"s": 6603,
"text": "model = model.fit(X)"
},
{
"code": null,
"e": 6716,
"s": 6624,
"text": "Before drawing a dendrogram, we can check the details of our model using available methods:"
},
{
"code": null,
"e": 6878,
"s": 6716,
"text": "# Number of clustersmodel.n_clusters_50# Distances between clustersdistances = model.distances_distances.min()0.09999999999999964distances.max()3.828052620290243"
},
{
"code": null,
"e": 6968,
"s": 6878,
"text": "Scikit learn does not provide dendrograms so we will use the dendrogram of SciPy package."
},
{
"code": null,
"e": 7050,
"s": 6968,
"text": "from scipy.cluster.hierarchy import dendrogramfrom scipy.cluster import hierarchy"
},
{
"code": null,
"e": 7084,
"s": 7050,
"text": "We first create a linkage matrix:"
},
{
"code": null,
"e": 7131,
"s": 7084,
"text": "Z = hierarchy.linkage(model.children_, 'ward')"
},
{
"code": null,
"e": 7227,
"s": 7131,
"text": "We use the children from the model and a linkage criterion which I choose to be ‘ward’ linkage."
},
{
"code": null,
"e": 7283,
"s": 7227,
"text": "plt.figure(figsize=(20,10))dn = hierarchy.dendrogram(Z)"
},
{
"code": null,
"e": 7335,
"s": 7283,
"text": "The labels of leafs are the indices of data points."
},
{
"code": null,
"e": 7483,
"s": 7335,
"text": "We can control the number of cluster by adjusting distance_thresold or n_cluster parameters. Let’s check the calculated distances between clusters:"
},
{
"code": null,
"e": 8158,
"s": 7483,
"text": "model.distances_array([0.1 , 0.1 , 0.1 , 0.1 , 0.14142136, 0.14142136, 0.14142136, 0.14142136, 0.14142136, 0.14142136, 0.14142136, 0.17320508, 0.17320508, 0.18257419, 0.2 , 0.2081666 , 0.21602469, 0.21602469, 0.25819889, 0.27568098, 0.28284271, 0.29439203, 0.29439203, 0.31358146, 0.31464265, 0.31622777, 0.33166248, 0.33665016, 0.34641016, 0.36968455, 0.40620192, 0.42229532, 0.43969687, 0.43969687, 0.46726153, 0.54772256, 0.59441848, 0.6244998 , 0.6363961 , 0.66269651, 0.77628542, 0.81873887, 0.85556999, 0.90998199, 1.10513951, 1.25399362, 1.37126983, 1.91875287, 3.82805262])"
},
{
"code": null,
"e": 8351,
"s": 8158,
"text": "Distances are in ascending order. If we can set the distance_thresold as 0.8, number of clusters will be 9. There are 8 distances greated than 0.8 so, when combined, 9 clusters will be formed."
},
{
"code": null,
"e": 8462,
"s": 8351,
"text": "model = AgglomerativeClustering(distance_threshold=0.8, n_clusters=None)model = model.fit(X)model.n_clusters_9"
}
] |
Set Colorbar Range in matplotlib - GeeksforGeeks | 11 Dec, 2020
Hello Geeks! In this article, we will try to set the color range using the matplotlib Python module. Matplotlib allows us a large range of Colorbar customization. The Colorbar is simply an instance of plt.Axes. It provides a scale for number-to-color ratio based on the data in a graph. Setting a range limits the colors to a subsection, The Colorbar falsely conveys the information that the lower limit of the data is comparable to its upper limit. With the two different limits, you can control the range and legend of the Colorbar.
Requirement: Matplotlib, NumPy
For installation Matplotlib
pip install matplotlib
For installation Numpy.
pip install numpy
Let’s understand with step-wise implementation:
Step 1:
Import required library and set up some generic data.
Python3
import numpy as npimport matplotlib.pyplot as plt # setup some generic dataN = 37x, y = np.mgrid[:N, :N]Z = (np.cos(x*0.2) + np.sin(y*0.3))
Step 2:
Mask out the negative and positive values.
Python3
Zpos = np.ma.masked_less(Z, 0)Zneg = np.ma.masked_greater(Z, 0)
Step 3:
Display data as an image, i.e., on a 2D regular raster.
Python3
# plot just the positive data and save the# color "mappable" object returned by ax1.imshowpos = ax1.imshow(Zpos, cmap = 'Blues', interpolation = 'none')
Step 4:
Plot both positive and negative values between +/- 1.2
Python3
fig, (ax1, ax2, ax3) = plt.subplots(figsize=(13, 3), ncols = 3) pos_neg_clipped = ax3.imshow(Z, cmap = 'RdBu', vmin = -1.2, vmax = 1.2)# Add minorticks on the colorbar to make # it easy to read the values off the colorbar.color_bar = fig.colorbar(pos_neg_clipped, ax = ax3, extend = 'both') color_bar.minorticks_on()plt.show()
Output:
Below is the full implementation:
Python3
import numpy as npimport matplotlib.pyplot as plt # setup some generic dataN = 37x, y = np.mgrid[:N, :N]Z = (np.cos(x*0.2) + np.sin(y*0.3)) # mask out the negative and positive valuesZpositive = np.ma.masked_less(Z, 0)Znegative = np.ma.masked_greater(Z, 0) fig, (ax1, ax2, ax3) = plt.subplots(figsize = (13, 3), ncols = 3) # plot just the positive data and save the# color "mappable" object returned by ax1.imshowpos = ax1.imshow(Zpositive, cmap = 'Blues') # add the colorbar using the figure's method,fig.colorbar(pos, ax = ax1) # repeat everything above for the negative dataneg = ax2.imshow(Znegative, cmap = 'Reds_r')fig.colorbar(neg, ax = ax2) # Plot both positive and negative values between +/- 1.2pos_neg_clipped = ax3.imshow(Z, cmap = 'RdBu', vmin = -1.2, vmax = 1.2) # Add minorticks on the colorbar to make # it easy to read the values off the colorbar.color_bar = fig.colorbar(pos_neg_clipped, ax = ax3, extend = 'both') color_bar.minorticks_on()plt.show()
Output:
Picked
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Selecting rows in pandas DataFrame based on conditions
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Get unique values from a list
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n11 Dec, 2020"
},
{
"code": null,
"e": 24828,
"s": 24292,
"text": "Hello Geeks! In this article, we will try to set the color range using the matplotlib Python module. Matplotlib allows us a large range of Colorbar customization. The Colorbar is simply an instance of plt.Axes. It provides a scale for number-to-color ratio based on the data in a graph. Setting a range limits the colors to a subsection, The Colorbar falsely conveys the information that the lower limit of the data is comparable to its upper limit. With the two different limits, you can control the range and legend of the Colorbar. "
},
{
"code": null,
"e": 24859,
"s": 24828,
"text": "Requirement: Matplotlib, NumPy"
},
{
"code": null,
"e": 24887,
"s": 24859,
"text": "For installation Matplotlib"
},
{
"code": null,
"e": 24910,
"s": 24887,
"text": "pip install matplotlib"
},
{
"code": null,
"e": 24934,
"s": 24910,
"text": "For installation Numpy."
},
{
"code": null,
"e": 24952,
"s": 24934,
"text": "pip install numpy"
},
{
"code": null,
"e": 25000,
"s": 24952,
"text": "Let’s understand with step-wise implementation:"
},
{
"code": null,
"e": 25008,
"s": 25000,
"text": "Step 1:"
},
{
"code": null,
"e": 25063,
"s": 25008,
"text": "Import required library and set up some generic data. "
},
{
"code": null,
"e": 25071,
"s": 25063,
"text": "Python3"
},
{
"code": "import numpy as npimport matplotlib.pyplot as plt # setup some generic dataN = 37x, y = np.mgrid[:N, :N]Z = (np.cos(x*0.2) + np.sin(y*0.3))",
"e": 25212,
"s": 25071,
"text": null
},
{
"code": null,
"e": 25220,
"s": 25212,
"text": "Step 2:"
},
{
"code": null,
"e": 25263,
"s": 25220,
"text": "Mask out the negative and positive values."
},
{
"code": null,
"e": 25271,
"s": 25263,
"text": "Python3"
},
{
"code": "Zpos = np.ma.masked_less(Z, 0)Zneg = np.ma.masked_greater(Z, 0)",
"e": 25335,
"s": 25271,
"text": null
},
{
"code": null,
"e": 25345,
"s": 25337,
"text": "Step 3:"
},
{
"code": null,
"e": 25401,
"s": 25345,
"text": "Display data as an image, i.e., on a 2D regular raster."
},
{
"code": null,
"e": 25409,
"s": 25401,
"text": "Python3"
},
{
"code": "# plot just the positive data and save the# color \"mappable\" object returned by ax1.imshowpos = ax1.imshow(Zpos, cmap = 'Blues', interpolation = 'none')",
"e": 25562,
"s": 25409,
"text": null
},
{
"code": null,
"e": 25570,
"s": 25562,
"text": "Step 4:"
},
{
"code": null,
"e": 25625,
"s": 25570,
"text": "Plot both positive and negative values between +/- 1.2"
},
{
"code": null,
"e": 25633,
"s": 25625,
"text": "Python3"
},
{
"code": "fig, (ax1, ax2, ax3) = plt.subplots(figsize=(13, 3), ncols = 3) pos_neg_clipped = ax3.imshow(Z, cmap = 'RdBu', vmin = -1.2, vmax = 1.2)# Add minorticks on the colorbar to make # it easy to read the values off the colorbar.color_bar = fig.colorbar(pos_neg_clipped, ax = ax3, extend = 'both') color_bar.minorticks_on()plt.show()",
"e": 26133,
"s": 25633,
"text": null
},
{
"code": null,
"e": 26141,
"s": 26133,
"text": "Output:"
},
{
"code": null,
"e": 26175,
"s": 26141,
"text": "Below is the full implementation:"
},
{
"code": null,
"e": 26183,
"s": 26175,
"text": "Python3"
},
{
"code": "import numpy as npimport matplotlib.pyplot as plt # setup some generic dataN = 37x, y = np.mgrid[:N, :N]Z = (np.cos(x*0.2) + np.sin(y*0.3)) # mask out the negative and positive valuesZpositive = np.ma.masked_less(Z, 0)Znegative = np.ma.masked_greater(Z, 0) fig, (ax1, ax2, ax3) = plt.subplots(figsize = (13, 3), ncols = 3) # plot just the positive data and save the# color \"mappable\" object returned by ax1.imshowpos = ax1.imshow(Zpositive, cmap = 'Blues') # add the colorbar using the figure's method,fig.colorbar(pos, ax = ax1) # repeat everything above for the negative dataneg = ax2.imshow(Znegative, cmap = 'Reds_r')fig.colorbar(neg, ax = ax2) # Plot both positive and negative values between +/- 1.2pos_neg_clipped = ax3.imshow(Z, cmap = 'RdBu', vmin = -1.2, vmax = 1.2) # Add minorticks on the colorbar to make # it easy to read the values off the colorbar.color_bar = fig.colorbar(pos_neg_clipped, ax = ax3, extend = 'both') color_bar.minorticks_on()plt.show()",
"e": 27302,
"s": 26183,
"text": null
},
{
"code": null,
"e": 27310,
"s": 27302,
"text": "Output:"
},
{
"code": null,
"e": 27317,
"s": 27310,
"text": "Picked"
},
{
"code": null,
"e": 27324,
"s": 27317,
"text": "Python"
},
{
"code": null,
"e": 27422,
"s": 27324,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27454,
"s": 27422,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27496,
"s": 27454,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27552,
"s": 27496,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27594,
"s": 27552,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27649,
"s": 27594,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 27680,
"s": 27649,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27702,
"s": 27680,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27731,
"s": 27702,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 27770,
"s": 27731,
"text": "Python | Get unique values from a list"
}
] |
How to Find Linux File Creation Time using Debugfs? - GeeksforGeeks | 09 Apr, 2021
Everything is treated as a file in Linux, and all the information about a file is stored in inodes, which includes the crucial metadata about a file such as creation time, last modification, etc. Every file in Linux is identified by its inode number.
In this article, we will be using debugf command to find Linux File Creation Time with the help of stat(utility to find file or file system status) command that is used to get Last Modified Date of File in Linux. Both stat command and Debugfs command together will be used to find actual file creation time in Linux.
Step 1: To find the inode number of the file which we need to know for finding the file creation time and the date we have to use the following command :
$ stat <file name>
Alternatively, ls -i command can also be used that will only show the inode number and skip all the other information.
$ ls -i <file name>
So now we have got the inode number that is “7342019 ” for the file “tithi.jpeg”, copy that to your clipboard because we are going to need this inode number in our further steps.
Step 2: Find out the root filesystem in which the file resides using the following command:
$ df -h
So here, system the root partition is /dev/sda1, that might be different on your system, so make sure to check it properly and note it down.
Step 3: Now lastly, use the debugfs command for finding the creation time of the file called “tithi.jpeg” by using the following command :-
sudo debugfs -R 'stat <inode number>' /dev/sda1
In the above result you can see different prefix such as ctime, atime, mtime, crtime, each of these has its own meaning that is:
ctime: file change time Displayed.
atime: file access time Displayed.
mtime: Shows file modification time.
crtime: Shows file creation time. (This is what we needed)
Picked
How To
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install FFmpeg on Windows?
How to Set Git Username and Password in GitBash?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS?
How to Create and Setup Spring Boot Project in Eclipse IDE?
Sed Command in Linux/Unix with examples
AWK command in Unix/Linux with examples
grep command in Unix/Linux
cut command in Linux with examples
TCP Server-Client implementation in C | [
{
"code": null,
"e": 24952,
"s": 24924,
"text": "\n09 Apr, 2021"
},
{
"code": null,
"e": 25203,
"s": 24952,
"text": "Everything is treated as a file in Linux, and all the information about a file is stored in inodes, which includes the crucial metadata about a file such as creation time, last modification, etc. Every file in Linux is identified by its inode number."
},
{
"code": null,
"e": 25521,
"s": 25203,
"text": "In this article, we will be using debugf command to find Linux File Creation Time with the help of stat(utility to find file or file system status) command that is used to get Last Modified Date of File in Linux. Both stat command and Debugfs command together will be used to find actual file creation time in Linux."
},
{
"code": null,
"e": 25675,
"s": 25521,
"text": "Step 1: To find the inode number of the file which we need to know for finding the file creation time and the date we have to use the following command :"
},
{
"code": null,
"e": 25694,
"s": 25675,
"text": "$ stat <file name>"
},
{
"code": null,
"e": 25813,
"s": 25694,
"text": "Alternatively, ls -i command can also be used that will only show the inode number and skip all the other information."
},
{
"code": null,
"e": 25834,
"s": 25813,
"text": "$ ls -i <file name>"
},
{
"code": null,
"e": 26013,
"s": 25834,
"text": "So now we have got the inode number that is “7342019 ” for the file “tithi.jpeg”, copy that to your clipboard because we are going to need this inode number in our further steps."
},
{
"code": null,
"e": 26105,
"s": 26013,
"text": "Step 2: Find out the root filesystem in which the file resides using the following command:"
},
{
"code": null,
"e": 26113,
"s": 26105,
"text": "$ df -h"
},
{
"code": null,
"e": 26254,
"s": 26113,
"text": "So here, system the root partition is /dev/sda1, that might be different on your system, so make sure to check it properly and note it down."
},
{
"code": null,
"e": 26394,
"s": 26254,
"text": "Step 3: Now lastly, use the debugfs command for finding the creation time of the file called “tithi.jpeg” by using the following command :-"
},
{
"code": null,
"e": 26443,
"s": 26394,
"text": "sudo debugfs -R 'stat <inode number>' /dev/sda1 "
},
{
"code": null,
"e": 26572,
"s": 26443,
"text": "In the above result you can see different prefix such as ctime, atime, mtime, crtime, each of these has its own meaning that is:"
},
{
"code": null,
"e": 26607,
"s": 26572,
"text": "ctime: file change time Displayed."
},
{
"code": null,
"e": 26642,
"s": 26607,
"text": "atime: file access time Displayed."
},
{
"code": null,
"e": 26679,
"s": 26642,
"text": "mtime: Shows file modification time."
},
{
"code": null,
"e": 26738,
"s": 26679,
"text": "crtime: Shows file creation time. (This is what we needed)"
},
{
"code": null,
"e": 26745,
"s": 26738,
"text": "Picked"
},
{
"code": null,
"e": 26752,
"s": 26745,
"text": "How To"
},
{
"code": null,
"e": 26763,
"s": 26752,
"text": "Linux-Unix"
},
{
"code": null,
"e": 26861,
"s": 26763,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26895,
"s": 26861,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 26944,
"s": 26895,
"text": "How to Set Git Username and Password in GitBash?"
},
{
"code": null,
"e": 27002,
"s": 26944,
"text": "How to Add External JAR File to an IntelliJ IDEA Project?"
},
{
"code": null,
"e": 27044,
"s": 27002,
"text": "How to Install Jupyter Notebook on MacOS?"
},
{
"code": null,
"e": 27104,
"s": 27044,
"text": "How to Create and Setup Spring Boot Project in Eclipse IDE?"
},
{
"code": null,
"e": 27144,
"s": 27104,
"text": "Sed Command in Linux/Unix with examples"
},
{
"code": null,
"e": 27184,
"s": 27144,
"text": "AWK command in Unix/Linux with examples"
},
{
"code": null,
"e": 27211,
"s": 27184,
"text": "grep command in Unix/Linux"
},
{
"code": null,
"e": 27246,
"s": 27211,
"text": "cut command in Linux with examples"
}
] |
Python | sympy.is_odd() method - GeeksforGeeks | 12 Oct, 2021
In simpy module, we can test whether a given number n is odd or not using sympy.is_odd() function.
Syntax: sympy.is_odd(n)
Parameter: n; number to be tested
Return: bool value result
Code #1:
# Python program to check odd number# using sympy.is_odd() method # importing sympy modulefrom sympy import * # calling is_odd function on different numbersgeek1 = simplify(30).is_oddgeek2 = simplify(13).is_odd print(geek1)print(geek2)
Output:
False
True
Code #2:
# Python program to check odd number# using sympy.is_odd() method # importing sympy modulefrom sympy import * # calling is_odd function on different numbersgeek = simplify(2).is_odd print(geek)
Output:
False
sumitgumber28
SymPy
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
Selecting rows in pandas DataFrame based on conditions
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n12 Oct, 2021"
},
{
"code": null,
"e": 24391,
"s": 24292,
"text": "In simpy module, we can test whether a given number n is odd or not using sympy.is_odd() function."
},
{
"code": null,
"e": 24480,
"s": 24391,
"text": "Syntax: sympy.is_odd(n)\nParameter: n; number to be tested\nReturn: bool value result \n"
},
{
"code": null,
"e": 24489,
"s": 24480,
"text": "Code #1:"
},
{
"code": "# Python program to check odd number# using sympy.is_odd() method # importing sympy modulefrom sympy import * # calling is_odd function on different numbersgeek1 = simplify(30).is_oddgeek2 = simplify(13).is_odd print(geek1)print(geek2)",
"e": 24728,
"s": 24489,
"text": null
},
{
"code": null,
"e": 24736,
"s": 24728,
"text": "Output:"
},
{
"code": null,
"e": 24748,
"s": 24736,
"text": "False\nTrue\n"
},
{
"code": null,
"e": 24757,
"s": 24748,
"text": "Code #2:"
},
{
"code": "# Python program to check odd number# using sympy.is_odd() method # importing sympy modulefrom sympy import * # calling is_odd function on different numbersgeek = simplify(2).is_odd print(geek)",
"e": 24954,
"s": 24757,
"text": null
},
{
"code": null,
"e": 24962,
"s": 24954,
"text": "Output:"
},
{
"code": null,
"e": 24968,
"s": 24962,
"text": "False"
},
{
"code": null,
"e": 24982,
"s": 24968,
"text": "sumitgumber28"
},
{
"code": null,
"e": 24988,
"s": 24982,
"text": "SymPy"
},
{
"code": null,
"e": 24995,
"s": 24988,
"text": "Python"
},
{
"code": null,
"e": 25093,
"s": 24995,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25102,
"s": 25093,
"text": "Comments"
},
{
"code": null,
"e": 25115,
"s": 25102,
"text": "Old Comments"
},
{
"code": null,
"e": 25147,
"s": 25115,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25203,
"s": 25147,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 25258,
"s": 25203,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 25300,
"s": 25258,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 25342,
"s": 25300,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 25373,
"s": 25342,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 25412,
"s": 25373,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 25441,
"s": 25412,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 25463,
"s": 25441,
"text": "Defaultdict in Python"
}
] |
ML Approaches for Time Series. In this post I play around with some... | by Pablo Ruiz | Towards Data Science | Modeling time series with non conventional models
In this post I play around with some Machine Learning techniques to analyze time series data and explore their potential use in this case of scenarios.
In this first post only the first point of the index is developed. The rest have a separate post which can be accessed from the index.
Note: This work was done by the beginning of 2017 so it is very likely that some libraries have been updated.
1 — Data creation, windows and baseline model2 — Genetic programming: Symbolic Regression3 — Extreme Learning Machines4 — Gaussian Processes5 —Convolutional Neural Network
In this work we will go through the analysis of non-evenly spaced time series data. We will create synthetic data of 3 random variables x1, x2 and x3, and adding some noise to the linear combination of some of the lags of these variables we will determine y, the response.
This way we can make sure that the function is not 100% predictable, the response depends on the predictors, and that there is a time dependency caused by the effect of previous lags of the predictors on the response.
This python script will create windows given a time series data in order to frame the problem in a way where we can provide our models the information the most complete possible.
Let’s see then, in the first place, which is the data we have and what treatment we are going to apply.
N = 600t = np.arange(0, N, 1).reshape(-1,1)t = np.array([t[i] + np.random.rand(1)/4 for i in range(len(t))])t = np.array([t[i] - np.random.rand(1)/7 for i in range(len(t))])t = np.array(np.round(t, 2))x1 = np.round((np.random.random(N) * 5).reshape(-1,1), 2)x2 = np.round((np.random.random(N) * 5).reshape(-1,1), 2)x3 = np.round((np.random.random(N) * 5).reshape(-1,1), 2)n = np.round((np.random.random(N) * 2).reshape(-1,1), 2)y = np.array([((np.log(np.abs(2 + x1[t])) - x2[t-1]**2) + 0.02*x3[t-3]*np.exp(x1[t-1])) for t in range(len(t))])y = np.round(y+n, 2)
Then, we have a function y which is the response of 3 independent random variables and with an added noise. Also, the response is directly correlated with lags of the independent variables, and not only with their values at a given point. This way we ensure time dependency, and we force our models to be able to identify this behavior.
Also, the timestamps are not evenly spaced. This way, we reinforce the idea that we want our models to understand time dependency, as they can not just treat the series by number of observations (rows).
We have included exponentials and logarithmic operators with the intention to induce high non-linearities in the data.
The approach followed for all the models of this work is to reshape the information we have by fixed windows that will give the model the most complete information possible at a given time point from the recent past, in order to achieve an accurate prediction. In addition, we will check how giving previous values of the response itself as an independent variable affects the models.
Let’s see how we are going to do it:
The picture shows only the axes of time and the response. Remember that, in our case, there is 3 more variables which are the responsible for the values of the t.
The picture in the top shows a windows of a chosen (and fixed) size w, which in this case is 4. This means that, the model is going to map the information contained in that windows, with the prediction at point which is at t+1. There is an r in the size of the response, because we could want to predict several time steps in the past. This would be a many-to-many relationship. For simplicity and easier visualization, we will work with r=1.
We can see now the effect of Sliding Window. The next pair of inputs-outputs that the model would have for finding the mapping function is obtained by moving the window one time step to the future, and proceed the same as we did at the previous step.
Ok then. How do we apply this to out current dataset? Let’s look at what we need, and build our helper functions.But first, we don’t want time to be absolutes values, we are more interesting in knowing which is the elapsed time between observations (remember the data is NOT evenly spaced!). Therefore, let’s create a ∆t and take a look at our data.
dataset = pd.DataFrame(np.concatenate((t, x1, x2, x3, y), axis=1), columns=['t', 'x1', 'x2', 'x3', 'y'])deltaT = np.array([(dataset.t[i + 1] - dataset.t[i]) for i in range(len(dataset)-1)])deltaT = np.concatenate((np.array([0]), deltaT))dataset.insert(1, '∆t', deltaT)dataset.head(3)
Now that we know how our dataset will look like that, let’s recreate what we want our helper function to do over a scheme of a table.
For a window of size 4:
What our function will do is to flatten all the information contained in the window, which is all the values inside the W window, and the timestamp(s) of when we want to make the prediction.
This way, we could have 2 different equation to model our system, depending if we include previous values of the responses as new predictors.
The result that the function have to return should look like:
We will be able to create l = n - (w+r) +1 windows, because we lose the first rows, as we don't have previous information for the first value of Y(0).
All the lags we have mentioned acts like new predictors for the model (in this visualization the previous values of Y are not included, they will follow the same as the Xi. Then, the timestamps (elapsed) where we want the prediction to be done ∆t(4), and the corresponding value of what the prediction should be Y(4). Note that all the first ∆t(0) are initialized to 0 as we want to standardize every window to be in the same ranges.
Here is the code created to achieve this process. There is a function WindowSlider from which we can create objects to construct different windows changing the parameters.
“Always do the simple thing first. Only apply intelligence when required” — Thad Starner
Create Windows
w = 5train_constructor = WindowSlider()train_windows = train_constructor.collect_windows(trainset.iloc[:,1:], previous_y=False)test_constructor = WindowSlider()test_windows = test_constructor.collect_windows(testset.iloc[:,1:], previous_y=False)train_constructor_y_inc = WindowSlider()train_windows_y_inc = train_constructor_y_inc.collect_windows(trainset.iloc[:,1:], previous_y=True)test_constructor_y_inc = WindowSlider()test_windows_y_inc = test_constructor_y_inc.collect_windows(testset.iloc[:,1:], previous_y=True)train_windows.head(3)
We can see how the windows brings for every prediction, the records of the (window_length) time steps in the past of the rest of the variables, and the accumulative sum of ∆t.
Prediction = Current
We will first start with a simple model that will give the last value (the current one at each prediction point) as the prediction for the next timestamp.
# ________________ Y_pred = current Y ________________ bl_trainset = cp.deepcopy(trainset)bl_testset = cp.deepcopy(testset)bl_y = pd.DataFrame(bl_testset['y'])bl_y_pred = bl_y.shift(periods=1)bl_residuals = bl_y_pred - bl_ybl_rmse = np.sqrt(np.sum(np.power(bl_residuals,2)) / len(bl_residuals))print('RMSE = %.2f' % bl_rmse)print('Time to train = 0 seconds')## RMSE = 11.28
Conclusion We have already a value to compare our coming results with. We have applied the simple rule of given my current value as the prediction. For time series where the value of the response is more stable (a.k.a stationary), this method can sometimes perfoms better than a ML algorithm surprisingly. In this case, the zig-zag of the data is notorious, leading to a poor predicting power.
Our next approach will be to build a multiple linear regression model
# ______________ MULTIPLE LINEAR REGRESSION ______________ #from sklearn.linear_model import LinearRegressionlr_model = LinearRegression()lr_model.fit(trainset.iloc[:,:-1], trainset.iloc[:,-1])t0 = time.time()lr_y = testset['y'].valueslr_y_fit = lr_model.predict(trainset.iloc[:,:-1])lr_y_pred = lr_model.predict(testset.iloc[:,:-1])tF = time.time()lr_residuals = lr_y_pred - lr_ylr_rmse = np.sqrt(np.sum(np.power(lr_residuals,2)) / len(lr_residuals))print('RMSE = %.2f' % lr_rmse)print('Time to train = %.2f seconds' % (tF - t0))## RMSE = 8.61 ## Time to train = 0.00 seconds
Conclusion
We can see how the multiple linear regression models are not able to capture how the response behaves. This is likely because the non-linearities in the relationship between the response and the independent variables. Also, it is the lags of these variables that affect the response at a given time. Therefore, the values are in different rows for the model that can not find to map this relationship.
I am curious to check now the assumptions we have made when explaining the construction of the windows. We said that we wanted to build a complete information set for every prediction point. Therefore, the prediction power should increase after the construction of the windows... Let’s go for it!
# ___________ MULTIPLE LINEAR REGRESSION ON WINDOWS ___________ from sklearn.linear_model import LinearRegressionlr_model = LinearRegression()lr_model.fit(train_windows.iloc[:,:-1], train_windows.iloc[:,-1])t0 = time.time()lr_y = test_windows['y'].valueslr_y_fit = lr_model.predict(train_windows.iloc[:,:-1])lr_y_pred = lr_model.predict(test_windows.iloc[:,:-1])tF = time.time()lr_residuals = lr_y_pred - lr_ylr_rmse = np.sqrt(np.sum(np.power(lr_residuals,2)) / len(lr_residuals))print('RMSE = %.2f' % lr_rmse)print('Time to train = %.2f seconds' % (tF - t0))## RMSE = 3.84## Time to train = 0.00 seconds
Wow! That was definitely a big improvement.Now we have a very powerful model to defeat. It seems that with the new windows, the model is able to find the relationship between a whole window information and the response.
Symbolic Regression is a type of regression analysis that searches the space of mathematical expressions to find the model that best fits a given dataset.
The base of symbolic regression is genetic programming and, therefore, it is an evolutionary algorithm (a.k.a. Genetic Algorithm — GA)
Summarizing in few words how the algorithm works, first we need to understand that a mathematical expression can be represented as a tree structure, like the figure above.
This way, the algorithm will start with a big population of trees at the first generation that will be measured according to a fitness function, in our case the RMSE. The best individuals of each generation are then cross between them and also some mutations are applied to include exploration and randomness. This iterative algorithms finish when a stopping criterion is met.
This video is a fantastic explanation of Genetic Programming.
We have seen that Symbolic Regression performs incredible good with almost a perfect fit in the validation data.
Surprisingly, I have achieved the best accuracy by including only the four most simple operators (addition, subtraction, multiplication and division), with the drawback of more training time.
I encourage you to try different parameters of the model and improve that results!
Extreme Learning Machines are an important emergent machine learning techniques. The main aspects of these techniques is that they do not need a learning process to calculate the parameters of the models.
Essentially, an EML is a Single-Layer Feed-Forward Neural Network (SLFN). ELM theory show that the value of the weight of this hidden layer need not to be tuned, and be therefore independent of the training data.
The universal approximation property implies that an EML can solve any regression problem with a desired accuracy, if it has enough hidden neurons and training data to learn parameters for all the hidden neurons.
EMLs also benefit from model structure and regularization, which reduces the negatives effects of random initialization and overfitting.
Given a set of N training samples (x, t). A SLFN with L hidden neuron outputs are:
The relation between the target and the inputs and outputs of the network are:
The hidden neurons are transforming the input data into a different representation in two steps. First, the data is projected into the hidden layer through the weights and biases of the input layer, and then applying to the result of that a non-linear activation function.
Practically, ELMs are solved as common Neural Networks in their matrix form. The matrix form is represented here:
And here is where the important part of this method comes. Given that T is the target we want to reach, a unique solution a the system with least squared error cam be found using Moore-Penrose generalized inverse. Therefore, we can compute in one single operation the values of the weights of the hidden layer that will result in the solution with the least error to predict the target T.
This pseudoinverse in calculated using the Singular Value Decomposition
In this article there is a well documented description in detail about how EML works, and a package for High-Performance Toolbox for EML and implementation in MATLAB and Python.
Without taking into account previous values of y as features
RMSE = 3.77Time to train 0.12
Taking into account previous values of y as features
RMSE = 6.37Time to train 0.00
We can see how EMLs have a great predicting power over our data. Also, it got way worse results where we included previous values of the response as predictors.
Definitely EMLs are models to keep on exploring, this was a quick implementation that already shows their great power, they were able to compute that accuracy with simple matrix inversion and few more operations.
Online Learning
The absolutely greatest advantage of EMLs is that they are very cheap computationally for implementing online models. In this article there is more information about the update and downdate operations.
In few lines, we could say that the model becomes adaptative, and if the prediction error goes beyond a stablished threshold, this particular data point is incorporated in the SVD so the model does not required an expensive complete retraining. This way the model can adapts and learn from changes that could happen to the process.
This post is part of a series of posts. The starting post van found here
A Gaussian Processes is a collection of random variables such that every finite collection of those random variables has a multivariate normal distribution, which means that every possible linear combination of them is normally distributed. (Gaussian processes can be seen as an infinite-dimensional generalization of multivariate normal distributions).
The distribution of the GP is the joint distribution of all those random variables. In few words, GPs use the kernel function that determines the similarity between point to predict the value for an unseen point.
This video is a fantastic quick intro to Gaussian Process to predict CO2 levels.This book is the main guide to Gaussian Processes.
One clear advantage of GP is the fact that we obtain a standard deviation at every prediction, that can be easily used to perform a confidence interval around the predictions.
A very simple CNN to play around:
Without taking into account previous values of y as features
RMSE = 2.320005Time to train 4.17
Taking into account previous values of y as features
The performance in the validation is far worse that if we don’t show the model previous values of the response.
Conclusion
We have seen how Gaussian Processes are another wonderful approach with a high predicting power. This model also get worse results where introducing previous values of the response as predictors.
The main point, is that we can play with an almost infinite combination of tuned kernels to look for the combination of random variables which their joint distribution better fits our model. I encourage you to try your own kernel and improve those results!
The idea is that the window of previous values defines as a picture the state of the process at a given time.
Therefore, we use a parallelism to image recognition, as we want to find patterns that map “pictures” to the response value. We include in our timeseries.pya new function, WindowsToPictures().
This functions takes the windows that we have been using as inputs, and creates a picture with all previous values of a window length of all the columns, for each value in the response.
If we remember the reshaping to windows in the chapter 1, this time, the windows won’t be flatten. Instead, they will be stacked in the third dimension of a 3D tensor, where each slice will be a picture to map with a unique response value. Here is an illustration:
Without taking into account previous values of y as features
RMSE = 4.21
Taking into account previous values of y as features
RMSE = 3.59
Taking the previous state of a process as a picture of the process for every time step seems like a reasonable approach for multivariate time-series forecasting.
This approach allows to frame the problem to whatever king of problem, such as financial time-series forecasting, temperature/weather prediction, process variables monitoring...
I still would like to think about new ways of creating the windows and the pictures to improve the results, but for me it looks like a robust module agains overfitting as we can see in the peaks, it never tends to go beyond the real values.
I would love to know what you come up with to improve it! | [
{
"code": null,
"e": 222,
"s": 172,
"text": "Modeling time series with non conventional models"
},
{
"code": null,
"e": 374,
"s": 222,
"text": "In this post I play around with some Machine Learning techniques to analyze time series data and explore their potential use in this case of scenarios."
},
{
"code": null,
"e": 509,
"s": 374,
"text": "In this first post only the first point of the index is developed. The rest have a separate post which can be accessed from the index."
},
{
"code": null,
"e": 619,
"s": 509,
"text": "Note: This work was done by the beginning of 2017 so it is very likely that some libraries have been updated."
},
{
"code": null,
"e": 791,
"s": 619,
"text": "1 — Data creation, windows and baseline model2 — Genetic programming: Symbolic Regression3 — Extreme Learning Machines4 — Gaussian Processes5 —Convolutional Neural Network"
},
{
"code": null,
"e": 1064,
"s": 791,
"text": "In this work we will go through the analysis of non-evenly spaced time series data. We will create synthetic data of 3 random variables x1, x2 and x3, and adding some noise to the linear combination of some of the lags of these variables we will determine y, the response."
},
{
"code": null,
"e": 1282,
"s": 1064,
"text": "This way we can make sure that the function is not 100% predictable, the response depends on the predictors, and that there is a time dependency caused by the effect of previous lags of the predictors on the response."
},
{
"code": null,
"e": 1461,
"s": 1282,
"text": "This python script will create windows given a time series data in order to frame the problem in a way where we can provide our models the information the most complete possible."
},
{
"code": null,
"e": 1565,
"s": 1461,
"text": "Let’s see then, in the first place, which is the data we have and what treatment we are going to apply."
},
{
"code": null,
"e": 2126,
"s": 1565,
"text": "N = 600t = np.arange(0, N, 1).reshape(-1,1)t = np.array([t[i] + np.random.rand(1)/4 for i in range(len(t))])t = np.array([t[i] - np.random.rand(1)/7 for i in range(len(t))])t = np.array(np.round(t, 2))x1 = np.round((np.random.random(N) * 5).reshape(-1,1), 2)x2 = np.round((np.random.random(N) * 5).reshape(-1,1), 2)x3 = np.round((np.random.random(N) * 5).reshape(-1,1), 2)n = np.round((np.random.random(N) * 2).reshape(-1,1), 2)y = np.array([((np.log(np.abs(2 + x1[t])) - x2[t-1]**2) + 0.02*x3[t-3]*np.exp(x1[t-1])) for t in range(len(t))])y = np.round(y+n, 2)"
},
{
"code": null,
"e": 2463,
"s": 2126,
"text": "Then, we have a function y which is the response of 3 independent random variables and with an added noise. Also, the response is directly correlated with lags of the independent variables, and not only with their values at a given point. This way we ensure time dependency, and we force our models to be able to identify this behavior."
},
{
"code": null,
"e": 2666,
"s": 2463,
"text": "Also, the timestamps are not evenly spaced. This way, we reinforce the idea that we want our models to understand time dependency, as they can not just treat the series by number of observations (rows)."
},
{
"code": null,
"e": 2785,
"s": 2666,
"text": "We have included exponentials and logarithmic operators with the intention to induce high non-linearities in the data."
},
{
"code": null,
"e": 3170,
"s": 2785,
"text": "The approach followed for all the models of this work is to reshape the information we have by fixed windows that will give the model the most complete information possible at a given time point from the recent past, in order to achieve an accurate prediction. In addition, we will check how giving previous values of the response itself as an independent variable affects the models."
},
{
"code": null,
"e": 3207,
"s": 3170,
"text": "Let’s see how we are going to do it:"
},
{
"code": null,
"e": 3370,
"s": 3207,
"text": "The picture shows only the axes of time and the response. Remember that, in our case, there is 3 more variables which are the responsible for the values of the t."
},
{
"code": null,
"e": 3813,
"s": 3370,
"text": "The picture in the top shows a windows of a chosen (and fixed) size w, which in this case is 4. This means that, the model is going to map the information contained in that windows, with the prediction at point which is at t+1. There is an r in the size of the response, because we could want to predict several time steps in the past. This would be a many-to-many relationship. For simplicity and easier visualization, we will work with r=1."
},
{
"code": null,
"e": 4064,
"s": 3813,
"text": "We can see now the effect of Sliding Window. The next pair of inputs-outputs that the model would have for finding the mapping function is obtained by moving the window one time step to the future, and proceed the same as we did at the previous step."
},
{
"code": null,
"e": 4414,
"s": 4064,
"text": "Ok then. How do we apply this to out current dataset? Let’s look at what we need, and build our helper functions.But first, we don’t want time to be absolutes values, we are more interesting in knowing which is the elapsed time between observations (remember the data is NOT evenly spaced!). Therefore, let’s create a ∆t and take a look at our data."
},
{
"code": null,
"e": 4721,
"s": 4414,
"text": "dataset = pd.DataFrame(np.concatenate((t, x1, x2, x3, y), axis=1), columns=['t', 'x1', 'x2', 'x3', 'y'])deltaT = np.array([(dataset.t[i + 1] - dataset.t[i]) for i in range(len(dataset)-1)])deltaT = np.concatenate((np.array([0]), deltaT))dataset.insert(1, '∆t', deltaT)dataset.head(3)"
},
{
"code": null,
"e": 4855,
"s": 4721,
"text": "Now that we know how our dataset will look like that, let’s recreate what we want our helper function to do over a scheme of a table."
},
{
"code": null,
"e": 4879,
"s": 4855,
"text": "For a window of size 4:"
},
{
"code": null,
"e": 5070,
"s": 4879,
"text": "What our function will do is to flatten all the information contained in the window, which is all the values inside the W window, and the timestamp(s) of when we want to make the prediction."
},
{
"code": null,
"e": 5212,
"s": 5070,
"text": "This way, we could have 2 different equation to model our system, depending if we include previous values of the responses as new predictors."
},
{
"code": null,
"e": 5274,
"s": 5212,
"text": "The result that the function have to return should look like:"
},
{
"code": null,
"e": 5425,
"s": 5274,
"text": "We will be able to create l = n - (w+r) +1 windows, because we lose the first rows, as we don't have previous information for the first value of Y(0)."
},
{
"code": null,
"e": 5859,
"s": 5425,
"text": "All the lags we have mentioned acts like new predictors for the model (in this visualization the previous values of Y are not included, they will follow the same as the Xi. Then, the timestamps (elapsed) where we want the prediction to be done ∆t(4), and the corresponding value of what the prediction should be Y(4). Note that all the first ∆t(0) are initialized to 0 as we want to standardize every window to be in the same ranges."
},
{
"code": null,
"e": 6031,
"s": 5859,
"text": "Here is the code created to achieve this process. There is a function WindowSlider from which we can create objects to construct different windows changing the parameters."
},
{
"code": null,
"e": 6120,
"s": 6031,
"text": "“Always do the simple thing first. Only apply intelligence when required” — Thad Starner"
},
{
"code": null,
"e": 6135,
"s": 6120,
"text": "Create Windows"
},
{
"code": null,
"e": 6870,
"s": 6135,
"text": "w = 5train_constructor = WindowSlider()train_windows = train_constructor.collect_windows(trainset.iloc[:,1:], previous_y=False)test_constructor = WindowSlider()test_windows = test_constructor.collect_windows(testset.iloc[:,1:], previous_y=False)train_constructor_y_inc = WindowSlider()train_windows_y_inc = train_constructor_y_inc.collect_windows(trainset.iloc[:,1:], previous_y=True)test_constructor_y_inc = WindowSlider()test_windows_y_inc = test_constructor_y_inc.collect_windows(testset.iloc[:,1:], previous_y=True)train_windows.head(3)"
},
{
"code": null,
"e": 7046,
"s": 6870,
"text": "We can see how the windows brings for every prediction, the records of the (window_length) time steps in the past of the rest of the variables, and the accumulative sum of ∆t."
},
{
"code": null,
"e": 7067,
"s": 7046,
"text": "Prediction = Current"
},
{
"code": null,
"e": 7222,
"s": 7067,
"text": "We will first start with a simple model that will give the last value (the current one at each prediction point) as the prediction for the next timestamp."
},
{
"code": null,
"e": 7596,
"s": 7222,
"text": "# ________________ Y_pred = current Y ________________ bl_trainset = cp.deepcopy(trainset)bl_testset = cp.deepcopy(testset)bl_y = pd.DataFrame(bl_testset['y'])bl_y_pred = bl_y.shift(periods=1)bl_residuals = bl_y_pred - bl_ybl_rmse = np.sqrt(np.sum(np.power(bl_residuals,2)) / len(bl_residuals))print('RMSE = %.2f' % bl_rmse)print('Time to train = 0 seconds')## RMSE = 11.28"
},
{
"code": null,
"e": 7990,
"s": 7596,
"text": "Conclusion We have already a value to compare our coming results with. We have applied the simple rule of given my current value as the prediction. For time series where the value of the response is more stable (a.k.a stationary), this method can sometimes perfoms better than a ML algorithm surprisingly. In this case, the zig-zag of the data is notorious, leading to a poor predicting power."
},
{
"code": null,
"e": 8060,
"s": 7990,
"text": "Our next approach will be to build a multiple linear regression model"
},
{
"code": null,
"e": 8637,
"s": 8060,
"text": "# ______________ MULTIPLE LINEAR REGRESSION ______________ #from sklearn.linear_model import LinearRegressionlr_model = LinearRegression()lr_model.fit(trainset.iloc[:,:-1], trainset.iloc[:,-1])t0 = time.time()lr_y = testset['y'].valueslr_y_fit = lr_model.predict(trainset.iloc[:,:-1])lr_y_pred = lr_model.predict(testset.iloc[:,:-1])tF = time.time()lr_residuals = lr_y_pred - lr_ylr_rmse = np.sqrt(np.sum(np.power(lr_residuals,2)) / len(lr_residuals))print('RMSE = %.2f' % lr_rmse)print('Time to train = %.2f seconds' % (tF - t0))## RMSE = 8.61 ## Time to train = 0.00 seconds"
},
{
"code": null,
"e": 8648,
"s": 8637,
"text": "Conclusion"
},
{
"code": null,
"e": 9050,
"s": 8648,
"text": "We can see how the multiple linear regression models are not able to capture how the response behaves. This is likely because the non-linearities in the relationship between the response and the independent variables. Also, it is the lags of these variables that affect the response at a given time. Therefore, the values are in different rows for the model that can not find to map this relationship."
},
{
"code": null,
"e": 9347,
"s": 9050,
"text": "I am curious to check now the assumptions we have made when explaining the construction of the windows. We said that we wanted to build a complete information set for every prediction point. Therefore, the prediction power should increase after the construction of the windows... Let’s go for it!"
},
{
"code": null,
"e": 9952,
"s": 9347,
"text": "# ___________ MULTIPLE LINEAR REGRESSION ON WINDOWS ___________ from sklearn.linear_model import LinearRegressionlr_model = LinearRegression()lr_model.fit(train_windows.iloc[:,:-1], train_windows.iloc[:,-1])t0 = time.time()lr_y = test_windows['y'].valueslr_y_fit = lr_model.predict(train_windows.iloc[:,:-1])lr_y_pred = lr_model.predict(test_windows.iloc[:,:-1])tF = time.time()lr_residuals = lr_y_pred - lr_ylr_rmse = np.sqrt(np.sum(np.power(lr_residuals,2)) / len(lr_residuals))print('RMSE = %.2f' % lr_rmse)print('Time to train = %.2f seconds' % (tF - t0))## RMSE = 3.84## Time to train = 0.00 seconds"
},
{
"code": null,
"e": 10172,
"s": 9952,
"text": "Wow! That was definitely a big improvement.Now we have a very powerful model to defeat. It seems that with the new windows, the model is able to find the relationship between a whole window information and the response."
},
{
"code": null,
"e": 10327,
"s": 10172,
"text": "Symbolic Regression is a type of regression analysis that searches the space of mathematical expressions to find the model that best fits a given dataset."
},
{
"code": null,
"e": 10462,
"s": 10327,
"text": "The base of symbolic regression is genetic programming and, therefore, it is an evolutionary algorithm (a.k.a. Genetic Algorithm — GA)"
},
{
"code": null,
"e": 10634,
"s": 10462,
"text": "Summarizing in few words how the algorithm works, first we need to understand that a mathematical expression can be represented as a tree structure, like the figure above."
},
{
"code": null,
"e": 11011,
"s": 10634,
"text": "This way, the algorithm will start with a big population of trees at the first generation that will be measured according to a fitness function, in our case the RMSE. The best individuals of each generation are then cross between them and also some mutations are applied to include exploration and randomness. This iterative algorithms finish when a stopping criterion is met."
},
{
"code": null,
"e": 11073,
"s": 11011,
"text": "This video is a fantastic explanation of Genetic Programming."
},
{
"code": null,
"e": 11186,
"s": 11073,
"text": "We have seen that Symbolic Regression performs incredible good with almost a perfect fit in the validation data."
},
{
"code": null,
"e": 11378,
"s": 11186,
"text": "Surprisingly, I have achieved the best accuracy by including only the four most simple operators (addition, subtraction, multiplication and division), with the drawback of more training time."
},
{
"code": null,
"e": 11461,
"s": 11378,
"text": "I encourage you to try different parameters of the model and improve that results!"
},
{
"code": null,
"e": 11666,
"s": 11461,
"text": "Extreme Learning Machines are an important emergent machine learning techniques. The main aspects of these techniques is that they do not need a learning process to calculate the parameters of the models."
},
{
"code": null,
"e": 11879,
"s": 11666,
"text": "Essentially, an EML is a Single-Layer Feed-Forward Neural Network (SLFN). ELM theory show that the value of the weight of this hidden layer need not to be tuned, and be therefore independent of the training data."
},
{
"code": null,
"e": 12092,
"s": 11879,
"text": "The universal approximation property implies that an EML can solve any regression problem with a desired accuracy, if it has enough hidden neurons and training data to learn parameters for all the hidden neurons."
},
{
"code": null,
"e": 12229,
"s": 12092,
"text": "EMLs also benefit from model structure and regularization, which reduces the negatives effects of random initialization and overfitting."
},
{
"code": null,
"e": 12312,
"s": 12229,
"text": "Given a set of N training samples (x, t). A SLFN with L hidden neuron outputs are:"
},
{
"code": null,
"e": 12391,
"s": 12312,
"text": "The relation between the target and the inputs and outputs of the network are:"
},
{
"code": null,
"e": 12664,
"s": 12391,
"text": "The hidden neurons are transforming the input data into a different representation in two steps. First, the data is projected into the hidden layer through the weights and biases of the input layer, and then applying to the result of that a non-linear activation function."
},
{
"code": null,
"e": 12778,
"s": 12664,
"text": "Practically, ELMs are solved as common Neural Networks in their matrix form. The matrix form is represented here:"
},
{
"code": null,
"e": 13167,
"s": 12778,
"text": "And here is where the important part of this method comes. Given that T is the target we want to reach, a unique solution a the system with least squared error cam be found using Moore-Penrose generalized inverse. Therefore, we can compute in one single operation the values of the weights of the hidden layer that will result in the solution with the least error to predict the target T."
},
{
"code": null,
"e": 13239,
"s": 13167,
"text": "This pseudoinverse in calculated using the Singular Value Decomposition"
},
{
"code": null,
"e": 13417,
"s": 13239,
"text": "In this article there is a well documented description in detail about how EML works, and a package for High-Performance Toolbox for EML and implementation in MATLAB and Python."
},
{
"code": null,
"e": 13478,
"s": 13417,
"text": "Without taking into account previous values of y as features"
},
{
"code": null,
"e": 13508,
"s": 13478,
"text": "RMSE = 3.77Time to train 0.12"
},
{
"code": null,
"e": 13561,
"s": 13508,
"text": "Taking into account previous values of y as features"
},
{
"code": null,
"e": 13591,
"s": 13561,
"text": "RMSE = 6.37Time to train 0.00"
},
{
"code": null,
"e": 13752,
"s": 13591,
"text": "We can see how EMLs have a great predicting power over our data. Also, it got way worse results where we included previous values of the response as predictors."
},
{
"code": null,
"e": 13965,
"s": 13752,
"text": "Definitely EMLs are models to keep on exploring, this was a quick implementation that already shows their great power, they were able to compute that accuracy with simple matrix inversion and few more operations."
},
{
"code": null,
"e": 13981,
"s": 13965,
"text": "Online Learning"
},
{
"code": null,
"e": 14183,
"s": 13981,
"text": "The absolutely greatest advantage of EMLs is that they are very cheap computationally for implementing online models. In this article there is more information about the update and downdate operations."
},
{
"code": null,
"e": 14515,
"s": 14183,
"text": "In few lines, we could say that the model becomes adaptative, and if the prediction error goes beyond a stablished threshold, this particular data point is incorporated in the SVD so the model does not required an expensive complete retraining. This way the model can adapts and learn from changes that could happen to the process."
},
{
"code": null,
"e": 14588,
"s": 14515,
"text": "This post is part of a series of posts. The starting post van found here"
},
{
"code": null,
"e": 14942,
"s": 14588,
"text": "A Gaussian Processes is a collection of random variables such that every finite collection of those random variables has a multivariate normal distribution, which means that every possible linear combination of them is normally distributed. (Gaussian processes can be seen as an infinite-dimensional generalization of multivariate normal distributions)."
},
{
"code": null,
"e": 15155,
"s": 14942,
"text": "The distribution of the GP is the joint distribution of all those random variables. In few words, GPs use the kernel function that determines the similarity between point to predict the value for an unseen point."
},
{
"code": null,
"e": 15286,
"s": 15155,
"text": "This video is a fantastic quick intro to Gaussian Process to predict CO2 levels.This book is the main guide to Gaussian Processes."
},
{
"code": null,
"e": 15462,
"s": 15286,
"text": "One clear advantage of GP is the fact that we obtain a standard deviation at every prediction, that can be easily used to perform a confidence interval around the predictions."
},
{
"code": null,
"e": 15496,
"s": 15462,
"text": "A very simple CNN to play around:"
},
{
"code": null,
"e": 15557,
"s": 15496,
"text": "Without taking into account previous values of y as features"
},
{
"code": null,
"e": 15591,
"s": 15557,
"text": "RMSE = 2.320005Time to train 4.17"
},
{
"code": null,
"e": 15644,
"s": 15591,
"text": "Taking into account previous values of y as features"
},
{
"code": null,
"e": 15756,
"s": 15644,
"text": "The performance in the validation is far worse that if we don’t show the model previous values of the response."
},
{
"code": null,
"e": 15767,
"s": 15756,
"text": "Conclusion"
},
{
"code": null,
"e": 15963,
"s": 15767,
"text": "We have seen how Gaussian Processes are another wonderful approach with a high predicting power. This model also get worse results where introducing previous values of the response as predictors."
},
{
"code": null,
"e": 16220,
"s": 15963,
"text": "The main point, is that we can play with an almost infinite combination of tuned kernels to look for the combination of random variables which their joint distribution better fits our model. I encourage you to try your own kernel and improve those results!"
},
{
"code": null,
"e": 16330,
"s": 16220,
"text": "The idea is that the window of previous values defines as a picture the state of the process at a given time."
},
{
"code": null,
"e": 16523,
"s": 16330,
"text": "Therefore, we use a parallelism to image recognition, as we want to find patterns that map “pictures” to the response value. We include in our timeseries.pya new function, WindowsToPictures()."
},
{
"code": null,
"e": 16709,
"s": 16523,
"text": "This functions takes the windows that we have been using as inputs, and creates a picture with all previous values of a window length of all the columns, for each value in the response."
},
{
"code": null,
"e": 16974,
"s": 16709,
"text": "If we remember the reshaping to windows in the chapter 1, this time, the windows won’t be flatten. Instead, they will be stacked in the third dimension of a 3D tensor, where each slice will be a picture to map with a unique response value. Here is an illustration:"
},
{
"code": null,
"e": 17035,
"s": 16974,
"text": "Without taking into account previous values of y as features"
},
{
"code": null,
"e": 17047,
"s": 17035,
"text": "RMSE = 4.21"
},
{
"code": null,
"e": 17100,
"s": 17047,
"text": "Taking into account previous values of y as features"
},
{
"code": null,
"e": 17112,
"s": 17100,
"text": "RMSE = 3.59"
},
{
"code": null,
"e": 17274,
"s": 17112,
"text": "Taking the previous state of a process as a picture of the process for every time step seems like a reasonable approach for multivariate time-series forecasting."
},
{
"code": null,
"e": 17452,
"s": 17274,
"text": "This approach allows to frame the problem to whatever king of problem, such as financial time-series forecasting, temperature/weather prediction, process variables monitoring..."
},
{
"code": null,
"e": 17693,
"s": 17452,
"text": "I still would like to think about new ways of creating the windows and the pictures to improve the results, but for me it looks like a robust module agains overfitting as we can see in the peaks, it never tends to go beyond the real values."
}
] |
Explain division operation in relational algebra (DBMS)? | Query is a question or requesting information. Query language is a language which is used to retrieve information from a database.
Query language is divided into two types −
Procedural language
Procedural language
Non-procedural language
Non-procedural language
Information is retrieved from the database by specifying the sequence of operations to be performed.
For Example: Relational algebra.
Structure Query language (SQL) is based on relational algebra.
Relational algebra consists of a set of operations that take one or two relations as an input and produces a new relation as output.
The different types of relational algebra operations are as follows −
Select operation
Select operation
Project operation
Project operation
Rename operation
Rename operation
Union operation
Union operation
Intersection operation
Intersection operation
Difference operation
Difference operation
Cartesian product operation
Cartesian product operation
Join operation
Join operation
Division operation
Division operation
Union, intersection, difference, cartesian, join, division comes under binary operation (operate on two table).
The division operator is used for queries which involve the ‘all’.
R1 ÷ R2 = tuples of R1 associated with all tuples of R2.
Retrieve the name of the subject that is taught in all courses.
÷
=
The resulting operation must have all combinations of tuples of relation S that are present in the first relation or R.
Retrieve name of employees who work on all the projects that John Smith works on.
Consider the Employee table given below −
÷
Works on the following −
=
The result is as follows
The expression is as follows
Smith <- ΠPno(σEname = ‘john smith’ (employee * works on Pno=Eno)) | [
{
"code": null,
"e": 1193,
"s": 1062,
"text": "Query is a question or requesting information. Query language is a language which is used to retrieve information from a database."
},
{
"code": null,
"e": 1236,
"s": 1193,
"text": "Query language is divided into two types −"
},
{
"code": null,
"e": 1256,
"s": 1236,
"text": "Procedural language"
},
{
"code": null,
"e": 1276,
"s": 1256,
"text": "Procedural language"
},
{
"code": null,
"e": 1300,
"s": 1276,
"text": "Non-procedural language"
},
{
"code": null,
"e": 1324,
"s": 1300,
"text": "Non-procedural language"
},
{
"code": null,
"e": 1425,
"s": 1324,
"text": "Information is retrieved from the database by specifying the sequence of operations to be performed."
},
{
"code": null,
"e": 1458,
"s": 1425,
"text": "For Example: Relational algebra."
},
{
"code": null,
"e": 1521,
"s": 1458,
"text": "Structure Query language (SQL) is based on relational algebra."
},
{
"code": null,
"e": 1654,
"s": 1521,
"text": "Relational algebra consists of a set of operations that take one or two relations as an input and produces a new relation as output."
},
{
"code": null,
"e": 1724,
"s": 1654,
"text": "The different types of relational algebra operations are as follows −"
},
{
"code": null,
"e": 1741,
"s": 1724,
"text": "Select operation"
},
{
"code": null,
"e": 1758,
"s": 1741,
"text": "Select operation"
},
{
"code": null,
"e": 1776,
"s": 1758,
"text": "Project operation"
},
{
"code": null,
"e": 1794,
"s": 1776,
"text": "Project operation"
},
{
"code": null,
"e": 1811,
"s": 1794,
"text": "Rename operation"
},
{
"code": null,
"e": 1828,
"s": 1811,
"text": "Rename operation"
},
{
"code": null,
"e": 1844,
"s": 1828,
"text": "Union operation"
},
{
"code": null,
"e": 1860,
"s": 1844,
"text": "Union operation"
},
{
"code": null,
"e": 1883,
"s": 1860,
"text": "Intersection operation"
},
{
"code": null,
"e": 1906,
"s": 1883,
"text": "Intersection operation"
},
{
"code": null,
"e": 1927,
"s": 1906,
"text": "Difference operation"
},
{
"code": null,
"e": 1948,
"s": 1927,
"text": "Difference operation"
},
{
"code": null,
"e": 1976,
"s": 1948,
"text": "Cartesian product operation"
},
{
"code": null,
"e": 2004,
"s": 1976,
"text": "Cartesian product operation"
},
{
"code": null,
"e": 2019,
"s": 2004,
"text": "Join operation"
},
{
"code": null,
"e": 2034,
"s": 2019,
"text": "Join operation"
},
{
"code": null,
"e": 2053,
"s": 2034,
"text": "Division operation"
},
{
"code": null,
"e": 2072,
"s": 2053,
"text": "Division operation"
},
{
"code": null,
"e": 2184,
"s": 2072,
"text": "Union, intersection, difference, cartesian, join, division comes under binary operation (operate on two table)."
},
{
"code": null,
"e": 2251,
"s": 2184,
"text": "The division operator is used for queries which involve the ‘all’."
},
{
"code": null,
"e": 2308,
"s": 2251,
"text": "R1 ÷ R2 = tuples of R1 associated with all tuples of R2."
},
{
"code": null,
"e": 2372,
"s": 2308,
"text": "Retrieve the name of the subject that is taught in all courses."
},
{
"code": null,
"e": 2374,
"s": 2372,
"text": "÷"
},
{
"code": null,
"e": 2376,
"s": 2374,
"text": "="
},
{
"code": null,
"e": 2496,
"s": 2376,
"text": "The resulting operation must have all combinations of tuples of relation S that are present in the first relation or R."
},
{
"code": null,
"e": 2578,
"s": 2496,
"text": "Retrieve name of employees who work on all the projects that John Smith works on."
},
{
"code": null,
"e": 2620,
"s": 2578,
"text": "Consider the Employee table given below −"
},
{
"code": null,
"e": 2622,
"s": 2620,
"text": "÷"
},
{
"code": null,
"e": 2647,
"s": 2622,
"text": "Works on the following −"
},
{
"code": null,
"e": 2649,
"s": 2647,
"text": "="
},
{
"code": null,
"e": 2674,
"s": 2649,
"text": "The result is as follows"
},
{
"code": null,
"e": 2703,
"s": 2674,
"text": "The expression is as follows"
},
{
"code": null,
"e": 2770,
"s": 2703,
"text": "Smith <- ΠPno(σEname = ‘john smith’ (employee * works on Pno=Eno))"
}
] |
UInt16.ToString Method in C# with Examples | The UInt16.ToString() method in C# is used to convert the numeric value of the current UInt16 instance to its equivalent string representation.
Following is the syntax −
public override string ToString();
Let us now see an example to implement the UInt16.ToString() method −
using System;
public class Demo {
public static void Main(){
ushort val1 = 100;
ushort val2 = 80;
Console.WriteLine("Value1 (String representation) = "+val1.ToString());
Console.WriteLine("Value2 (String representation) = "+val2.ToString());
bool res = val1.Equals(val2);
Console.WriteLine("Return value (comparison) = "+res);
if (res)
Console.WriteLine("val1 = val2");
else
Console.WriteLine("val1 != val2");
}
}
This will produce the following output −
Value1 (String representation) = 100
Value2 (String representation) = 80
Return value (comparison) = False
val1 != val2
Let us now see another example to implement the UInt16.ToString() method −
using System;
public class Demo {
public static void Main(){
ushort val1 = 0;
ushort val2 = UInt16.MaxValue;
Console.WriteLine("Value1 (String representation) = "+val1.ToString());
Console.WriteLine("Value2 (String representation) = "+val2.ToString());
bool res = val1.Equals(val2);
Console.WriteLine("Return value (comparison) = "+res);
if (res)
Console.WriteLine("val1 = val2");
else
Console.WriteLine("val1 != val2");
}
}
This will produce the following output −
Value1 (String representation) = 0
Value2 (String representation) = 65535
Return value (comparison) = False
val1 != val2 | [
{
"code": null,
"e": 1206,
"s": 1062,
"text": "The UInt16.ToString() method in C# is used to convert the numeric value of the current UInt16 instance to its equivalent string representation."
},
{
"code": null,
"e": 1232,
"s": 1206,
"text": "Following is the syntax −"
},
{
"code": null,
"e": 1267,
"s": 1232,
"text": "public override string ToString();"
},
{
"code": null,
"e": 1337,
"s": 1267,
"text": "Let us now see an example to implement the UInt16.ToString() method −"
},
{
"code": null,
"e": 1823,
"s": 1337,
"text": "using System;\npublic class Demo {\n public static void Main(){\n ushort val1 = 100;\n ushort val2 = 80;\n Console.WriteLine(\"Value1 (String representation) = \"+val1.ToString());\n Console.WriteLine(\"Value2 (String representation) = \"+val2.ToString());\n bool res = val1.Equals(val2);\n Console.WriteLine(\"Return value (comparison) = \"+res);\n if (res)\n Console.WriteLine(\"val1 = val2\");\n else\n Console.WriteLine(\"val1 != val2\");\n }\n}"
},
{
"code": null,
"e": 1864,
"s": 1823,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1984,
"s": 1864,
"text": "Value1 (String representation) = 100\nValue2 (String representation) = 80\nReturn value (comparison) = False\nval1 != val2"
},
{
"code": null,
"e": 2059,
"s": 1984,
"text": "Let us now see another example to implement the UInt16.ToString() method −"
},
{
"code": null,
"e": 2556,
"s": 2059,
"text": "using System;\npublic class Demo {\n public static void Main(){\n ushort val1 = 0;\n ushort val2 = UInt16.MaxValue;\n Console.WriteLine(\"Value1 (String representation) = \"+val1.ToString());\n Console.WriteLine(\"Value2 (String representation) = \"+val2.ToString());\n bool res = val1.Equals(val2);\n Console.WriteLine(\"Return value (comparison) = \"+res);\n if (res)\n Console.WriteLine(\"val1 = val2\");\n else\n Console.WriteLine(\"val1 != val2\");\n }\n}"
},
{
"code": null,
"e": 2597,
"s": 2556,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2718,
"s": 2597,
"text": "Value1 (String representation) = 0\nValue2 (String representation) = 65535\nReturn value (comparison) = False\nval1 != val2"
}
] |
How to get the IP address of android device programmatically? | This example demonstrates how do I get the IP address of android device programmatically.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="16dp"
android:orientation="vertical">
<TextView
android:id="@+id/getIPAddress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="IP address of your Device"
android:textStyle="bold"
android:textSize="25sp" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.net.wifi.WifiManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.format.Formatter;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.getIPAddress);
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
String ipAddress = Formatter.formatIpAddress(wifiManager.getConnectionInfo().getIpAddress());
textView.setText("Your Device IP Address: " + ipAddress);
}
}
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">
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".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": 1152,
"s": 1062,
"text": "This example demonstrates how do I get the IP address of android device programmatically."
},
{
"code": null,
"e": 1281,
"s": 1152,
"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": 1346,
"s": 1281,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1913,
"s": 1346,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:layout_margin=\"16dp\"\n android:orientation=\"vertical\">\n <TextView\n android:id=\"@+id/getIPAddress\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:text=\"IP address of your Device\"\n android:textStyle=\"bold\"\n android:textSize=\"25sp\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 1970,
"s": 1913,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 2708,
"s": 1970,
"text": "import android.net.wifi.WifiManager;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.text.format.Formatter;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n TextView textView;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n textView = findViewById(R.id.getIPAddress);\n WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);\n String ipAddress = Formatter.formatIpAddress(wifiManager.getConnectionInfo().getIpAddress());\n textView.setText(\"Your Device IP Address: \" + ipAddress);\n }\n}"
},
{
"code": null,
"e": 2763,
"s": 2708,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3507,
"s": 2763,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <uses-permission android:name=\"android.permission.ACCESS_WIFI_STATE\"/>\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".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": 3854,
"s": 3507,
"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": 3895,
"s": 3854,
"text": "Click here to download the project code."
}
] |
Address Calculation Sort using Hashing - GeeksforGeeks | 10 Oct, 2018
In this sorting algorithm, Hash Function f is used with the property of Order Preserving Function which states that if .
Hash Function:
f(x) = floor( (x/maximum) * SIZE )
where maximum => maximum value in the array,
SIZE => size of the address table (10 in our case),
floor => floor function
This algorithm uses an address table to store the values which is simply a list (or array) of Linked lists. The Hash function is applied to each value in the array to find its corresponding address in the address table. Then the values are inserted at their corresponding addresses in a sorted manner by comparing them to the values which are already present at that address.
Examples:
Input : arr = [29, 23, 14, 5, 15, 10, 3, 18, 1]
Output:
After inserting all the values in the address table, the address table looks like this:
ADDRESS 0: 1 --> 3
ADDRESS 1: 5
ADDRESS 2:
ADDRESS 3: 10
ADDRESS 4: 14 --> 15
ADDRESS 5: 18
ADDRESS 6:
ADDRESS 7: 23
ADDRESS 8:
ADDRESS 9: 29
The below figure shows the representation of the address table for the example discussed above:
After insertion, the values at each address in the address table are sorted. Hence we iterate through each address one by one and insert the values at that address in the input array.
Below is the implementation of the above approach
# Python3 code for implementation of # Address Calculation Sorting using Hashing # Size of the address table (In this case 0-9)SIZE = 10 class Node(object): def __init__(self, data = None): self.data = data self.nextNode = None class LinkedList(object): def __init__(self): self.head = None # Insert values in such a way that the list remains sorted def insert(self, data): newNode = Node(data) # If there is no node or new Node's value # is smaller than the first value in the list, # Insert new Node in the first place if self.head == None or data < self.head.data: newNode.nextNode = self.head self.head = newNode else: current = self.head # If the next node is null or its value # is greater than the new Node's value, # Insert new Node in that place while current.nextNode != None \ and \ current.nextNode.data < data: current = current.nextNode newNode.nextNode = current.nextNode current.nextNode = newNode # This function sorts the given list # using Address Calculation Sorting using Hashingdef addressCalculationSort(arr): # Declare a list of Linked Lists of given SIZE listOfLinkedLists = [] for i in range(SIZE): listOfLinkedLists.append(LinkedList()) # Calculate maximum value in the array maximum = max(arr) # Find the address of each value # in the address table # and insert it in that list for val in arr: address = hashFunction(val, maximum) listOfLinkedLists[address].insert(val) # Print the address table # after all the values have been inserted for i in range(SIZE): current = listOfLinkedLists[i].head print("ADDRESS " + str(i), end = ": ") while current != None: print(current.data, end = " ") current = current.nextNode print() # Assign the sorted values to the input array index = 0 for i in range(SIZE): current = listOfLinkedLists[i].head while current != None: arr[index] = current.data index += 1 current = current.nextNode # This function returns the corresponding address# of given value in the address tabledef hashFunction(num, maximum): # Scale the value such that address is between 0 to 9 address = int((num * 1.0 / maximum) * (SIZE-1)) return address # -------------------------------------------------------# Driver code # giving the input address as followsarr = [29, 23, 14, 5, 15, 10, 3, 18, 1] # Printing the Input arrayprint("\nInput array: " + " ".join([str(x) for x in arr])) # Performing address calculation sortaddressCalculationSort(arr) # printing the result sorted arrayprint("\nSorted array: " + " ".join([str(x) for x in arr]))
Input array: 29 23 14 5 15 10 3 18 1
ADDRESS 0: 1 3
ADDRESS 1: 5
ADDRESS 2:
ADDRESS 3: 10
ADDRESS 4: 14 15
ADDRESS 5: 18
ADDRESS 6:
ADDRESS 7: 23
ADDRESS 8:
ADDRESS 9: 29
Sorted array: 1 3 5 10 14 15 18 23 29
Time Complexity:The time complexity of this algorithm is in the best case. This happens when the values in the array are uniformly distributed within a specific range.
Whereas the worst case time complexity is . This happens when most of the values occupy 1 or 2 addresses because then significant work is required to insert each value at its proper place.
Picked
Technical Scripter 2018
Hash
Linked List
Python
Sorting
Linked List
Hash
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Most frequent element in an array
Sort string of characters
Counting frequencies of array elements
Sorting a Map by value in C++ STL
C++ program for hashing with chaining
Linked List | Set 1 (Introduction)
Linked List | Set 2 (Inserting a node)
Reverse a linked list
Stack Data Structure (Introduction and Program)
Linked List | Set 3 (Deleting a node) | [
{
"code": null,
"e": 24744,
"s": 24716,
"text": "\n10 Oct, 2018"
},
{
"code": null,
"e": 24865,
"s": 24744,
"text": "In this sorting algorithm, Hash Function f is used with the property of Order Preserving Function which states that if ."
},
{
"code": null,
"e": 24880,
"s": 24865,
"text": "Hash Function:"
},
{
"code": null,
"e": 25049,
"s": 24880,
"text": "f(x) = floor( (x/maximum) * SIZE )\nwhere maximum => maximum value in the array,\n SIZE => size of the address table (10 in our case),\n floor => floor function\n"
},
{
"code": null,
"e": 25425,
"s": 25049,
"text": "This algorithm uses an address table to store the values which is simply a list (or array) of Linked lists. The Hash function is applied to each value in the array to find its corresponding address in the address table. Then the values are inserted at their corresponding addresses in a sorted manner by comparing them to the values which are already present at that address."
},
{
"code": null,
"e": 25435,
"s": 25425,
"text": "Examples:"
},
{
"code": null,
"e": 25734,
"s": 25435,
"text": "Input : arr = [29, 23, 14, 5, 15, 10, 3, 18, 1] \nOutput:\nAfter inserting all the values in the address table, the address table looks like this:\n\nADDRESS 0: 1 --> 3 \nADDRESS 1: 5 \nADDRESS 2: \nADDRESS 3: 10 \nADDRESS 4: 14 --> 15 \nADDRESS 5: 18 \nADDRESS 6: \nADDRESS 7: 23 \nADDRESS 8: \nADDRESS 9: 29\n\n"
},
{
"code": null,
"e": 25830,
"s": 25734,
"text": "The below figure shows the representation of the address table for the example discussed above:"
},
{
"code": null,
"e": 26014,
"s": 25830,
"text": "After insertion, the values at each address in the address table are sorted. Hence we iterate through each address one by one and insert the values at that address in the input array."
},
{
"code": null,
"e": 26064,
"s": 26014,
"text": "Below is the implementation of the above approach"
},
{
"code": "# Python3 code for implementation of # Address Calculation Sorting using Hashing # Size of the address table (In this case 0-9)SIZE = 10 class Node(object): def __init__(self, data = None): self.data = data self.nextNode = None class LinkedList(object): def __init__(self): self.head = None # Insert values in such a way that the list remains sorted def insert(self, data): newNode = Node(data) # If there is no node or new Node's value # is smaller than the first value in the list, # Insert new Node in the first place if self.head == None or data < self.head.data: newNode.nextNode = self.head self.head = newNode else: current = self.head # If the next node is null or its value # is greater than the new Node's value, # Insert new Node in that place while current.nextNode != None \\ and \\ current.nextNode.data < data: current = current.nextNode newNode.nextNode = current.nextNode current.nextNode = newNode # This function sorts the given list # using Address Calculation Sorting using Hashingdef addressCalculationSort(arr): # Declare a list of Linked Lists of given SIZE listOfLinkedLists = [] for i in range(SIZE): listOfLinkedLists.append(LinkedList()) # Calculate maximum value in the array maximum = max(arr) # Find the address of each value # in the address table # and insert it in that list for val in arr: address = hashFunction(val, maximum) listOfLinkedLists[address].insert(val) # Print the address table # after all the values have been inserted for i in range(SIZE): current = listOfLinkedLists[i].head print(\"ADDRESS \" + str(i), end = \": \") while current != None: print(current.data, end = \" \") current = current.nextNode print() # Assign the sorted values to the input array index = 0 for i in range(SIZE): current = listOfLinkedLists[i].head while current != None: arr[index] = current.data index += 1 current = current.nextNode # This function returns the corresponding address# of given value in the address tabledef hashFunction(num, maximum): # Scale the value such that address is between 0 to 9 address = int((num * 1.0 / maximum) * (SIZE-1)) return address # -------------------------------------------------------# Driver code # giving the input address as followsarr = [29, 23, 14, 5, 15, 10, 3, 18, 1] # Printing the Input arrayprint(\"\\nInput array: \" + \" \".join([str(x) for x in arr])) # Performing address calculation sortaddressCalculationSort(arr) # printing the result sorted arrayprint(\"\\nSorted array: \" + \" \".join([str(x) for x in arr]))",
"e": 29039,
"s": 26064,
"text": null
},
{
"code": null,
"e": 29261,
"s": 29039,
"text": "Input array: 29 23 14 5 15 10 3 18 1\n\nADDRESS 0: 1 3 \nADDRESS 1: 5 \nADDRESS 2: \nADDRESS 3: 10 \nADDRESS 4: 14 15 \nADDRESS 5: 18 \nADDRESS 6: \nADDRESS 7: 23 \nADDRESS 8: \nADDRESS 9: 29 \n\nSorted array: 1 3 5 10 14 15 18 23 29\n"
},
{
"code": null,
"e": 29430,
"s": 29261,
"text": "Time Complexity:The time complexity of this algorithm is in the best case. This happens when the values in the array are uniformly distributed within a specific range."
},
{
"code": null,
"e": 29619,
"s": 29430,
"text": "Whereas the worst case time complexity is . This happens when most of the values occupy 1 or 2 addresses because then significant work is required to insert each value at its proper place."
},
{
"code": null,
"e": 29626,
"s": 29619,
"text": "Picked"
},
{
"code": null,
"e": 29650,
"s": 29626,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 29655,
"s": 29650,
"text": "Hash"
},
{
"code": null,
"e": 29667,
"s": 29655,
"text": "Linked List"
},
{
"code": null,
"e": 29674,
"s": 29667,
"text": "Python"
},
{
"code": null,
"e": 29682,
"s": 29674,
"text": "Sorting"
},
{
"code": null,
"e": 29694,
"s": 29682,
"text": "Linked List"
},
{
"code": null,
"e": 29699,
"s": 29694,
"text": "Hash"
},
{
"code": null,
"e": 29707,
"s": 29699,
"text": "Sorting"
},
{
"code": null,
"e": 29805,
"s": 29707,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29839,
"s": 29805,
"text": "Most frequent element in an array"
},
{
"code": null,
"e": 29865,
"s": 29839,
"text": "Sort string of characters"
},
{
"code": null,
"e": 29904,
"s": 29865,
"text": "Counting frequencies of array elements"
},
{
"code": null,
"e": 29938,
"s": 29904,
"text": "Sorting a Map by value in C++ STL"
},
{
"code": null,
"e": 29976,
"s": 29938,
"text": "C++ program for hashing with chaining"
},
{
"code": null,
"e": 30011,
"s": 29976,
"text": "Linked List | Set 1 (Introduction)"
},
{
"code": null,
"e": 30050,
"s": 30011,
"text": "Linked List | Set 2 (Inserting a node)"
},
{
"code": null,
"e": 30072,
"s": 30050,
"text": "Reverse a linked list"
},
{
"code": null,
"e": 30120,
"s": 30072,
"text": "Stack Data Structure (Introduction and Program)"
}
] |
Find the next greater element in a Circular Array - GeeksforGeeks | 20 Apr, 2022
Given a circular array arr[] of N integers such that the last element of the given array is adjacent to the first element of the array, the task is to print the Next Greater Element in this circular array. Elements for which no greater element exist, consider the next greater element as “-1”.
Examples:
Input: arr[] = {5, 6, 7} Output: {6, 7, -1} Explanation: Next Greater Element for 5 is 6, for 6 is 7, and for 7 is -1 as we don’t have any element greater than itself so its -1.
Input: arr[] = {4, -2, 5, 8} Output: {5, 5, 8, -1} Explanation: Next Greater Element for 4 is 5, for -2 its 5, for 5 is 8, and for 8 is -1 as we don’t have any element greater than itself so its -1, and for 3 its 4.
Approach: This problem can be solved using Greedy Approach. Below are the steps:
For the property of the circular array to be valid append the given array elements to the same array once again.
For Example:
Let arr[] = {1, 4, 3} After appending the same set of elements arr[] becomes arr[] = {1, 4, 3, 1, 4, 3}
Find the next greater element till N elements in the above array formed.
If any greater element is found then print that element, else print “-1”.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the NGEvoid printNGE(int A[], int n){ // Formation of circular array int arr[2 * n]; // Append the given array element twice for (int i = 0; i < 2 * n; i++) arr[i] = A[i % n]; int next, i, j; // Iterate for all the // elements of the array for (i = 0; i < n; i++) { // Initialise NGE as -1 next = -1; for (j = i + 1; j < 2 * n; j++) { // Checking for next // greater element if (arr[i] < arr[j]) { next = arr[j]; break; } } // Print the updated NGE cout << next << ", "; }} // Driver Codeint main(){ // Given array arr[] int arr[] = { 1, 2, 1 }; int N = sizeof(arr) / sizeof(arr[0]); // Function call printNGE(arr, N); return 0;}
// Java program for the above approachimport java.util.*;class GFG{ // Function to find the NGEstatic void printNGE(int []A, int n){ // Formation of circular array int []arr = new int[2 * n]; // Append the given array element twice for(int i = 0; i < 2 * n; i++) arr[i] = A[i % n]; int next; // Iterate for all the // elements of the array for(int i = 0; i < n; i++) { // Initialise NGE as -1 next = -1; for(int j = i + 1; j < 2 * n; j++) { // Checking for next // greater element if (arr[i] < arr[j]) { next = arr[j]; break; } } // Print the updated NGE System.out.print(next + ", "); }} // Driver Codepublic static void main(String args[]){ // Given array arr[] int []arr = { 1, 2, 1 }; int N = arr.length; // Function call printNGE(arr, N);}} // This code is contributed by Code_Mech
# Python3 program for the above approach # Function to find the NGEdef printNGE(A, n): # Formation of circular array arr = [0] * (2 * n) # Append the given array # element twice for i in range(2 * n): arr[i] = A[i % n] # Iterate for all the # elements of the array for i in range(n): # Initialise NGE as -1 next = -1 for j in range(i + 1, 2 * n): # Checking for next # greater element if(arr[i] < arr[j]): next = arr[j] break # Print the updated NGE print(next, end = ", ") # Driver codeif __name__ == '__main__': # Given array arr[] arr = [ 1, 2, 1 ] N = len(arr) # Function call printNGE(arr, N) # This code is contributed by Shivam Singh
// C# program for the above approachusing System;class GFG{ // Function to find the NGEstatic void printNGE(int []A, int n){ // Formation of circular array int []arr = new int[2 * n]; // Append the given array element twice for(int i = 0; i < 2 * n; i++) arr[i] = A[i % n]; int next; // Iterate for all the // elements of the array for(int i = 0; i < n; i++) { // Initialise NGE as -1 next = -1; for(int j = i + 1; j < 2 * n; j++) { // Checking for next // greater element if (arr[i] < arr[j]) { next = arr[j]; break; } } // Print the updated NGE Console.Write(next + ", "); }} // Driver Codepublic static void Main(){ // Given array arr[] int []arr = { 1, 2, 1 }; int N = arr.Length; // Function call printNGE(arr, N);}} // This code is contributed by Code_Mech
<script> // JavaScript program for the above approach // Function to find the NGEfunction printNGE(A, n){ // Formation of circular array let arr = Array.from({length: 2 * n}, (_, i) => 0); // Append the given array element twice for(let i = 0; i < 2 * n; i++) arr[i] = A[i % n]; let next; // Iterate for all the // elements of the array for(let i = 0; i < n; i++) { // Initialise NGE as -1 next = -1; for(let j = i + 1; j < 2 * n; j++) { // Checking for next // greater element if (arr[i] < arr[j]) { next = arr[j]; break; } } // Print the updated NGE document.write(next + ", "); }} // Driver Code // Given array arr[] let arr = [ 1, 2, 1 ]; let N = arr.length; // Function call printNGE(arr, N); </script>
2, -1, 2,
This approach takes of O(n2) time but takes extra space of order O(n)
A space-efficient solution is to deal with circular arrays using the same array. If a careful observation is run through the array, then after the n-th index, the next index always starts from 0 so using the mod operator, we can easily access the elements of the circular list, if we use (i)%n and run the loop from i-th index to n+i-th index, and apply mod we can do the traversal in a circular array within the given array without using any extra space.
Below is the implementation of the above approach:
C++
C
Java
Python3
C#
Javascript
// C++ program to demonstrate the use of circular// array without using extra memory space#include <bits/stdc++.h>using namespace std; // Function to find the Next Greater Element(NGE)void printNGE(int A[], int n){ int k; for(int i = 0; i < n; i++) { // Initialise k as -1 which is printed // when no NGE found k = -1; for(int j = i + 1; j < n + i; j++) { if (A[i] < A[j % n]) { cout <<" "<< A[j % n]; k = 1; break; } } // Gets executed when no NGE found if (k == -1) cout << "-1 "; }} // Driver Codeint main(){ // Given array arr[] int arr[] = { 8, 6, 7 }; int N = sizeof(arr) / sizeof(arr[0]); // Function call printNGE(arr, N); return 0;} // This code is contributed by shivanisinghss2110
// C program to demonstrate the use of circular// array without using extra memory space #include <stdio.h> // Function to find the Next Greater Element(NGE)void printNGE(int A[], int n){ int k; for (int i = 0; i < n; i++) { // Initialise k as -1 which is printed when no NGE // found k = -1; // for (int j = i + 1; j < n + i; j++) { if (A[i] < A[j % n]) { printf("%d ", A[j % n]); k = 1; break; } } if (k == -1) // Gets executed when no NGE found printf("-1 "); }} // Driver Codeint main(){ // Given array arr[] int arr[] = { 8, 6, 7 }; int N = sizeof(arr) / sizeof(arr[0]); // Function call printNGE(arr, N); return 0;}
// Java program to demonstrate the// use of circular array without// using extra memory spaceimport java.io.*; class GFG{ // Function to find the Next// Greater Element(NGE)static void printNGE(int A[], int n){ int k; for(int i = 0; i < n; i++) { // Initialise k as -1 which is // printed when no NGE found k = -1; for(int j = i + 1; j < n + i; j++) { if (A[i] < A[j % n]) { System.out.print(A[j % n] + " "); k = 1; break; } } // Gets executed when no NGE found if (k == -1) System.out.print("-1 "); }} // Driver Codepublic static void main(String[] args){ // Given array arr[] int[] arr = { 8, 6, 7 }; int N = arr.length; // Function call printNGE(arr, N);}} // This code is contributed by yashbeersingh42
# Python3 program to demonstrate the use of circular# array without using extra memory space # Function to find the Next Greater Element(NGE)def printNGE(A, n) : for i in range(n) : # Initialise k as -1 which is printed when no NGE # found k = -1 for j in range(i + 1, n + i) : if (A[i] < A[j % n]) : print(A[j % n], end = " ") k = 1 break if (k == -1) : # Gets executed when no NGE found print("-1 ", end = "") # Given array arr[]arr = [ 8, 6, 7 ] N = len(arr) # Function callprintNGE(arr, N) # This code is contributed by divyeshrabadia07
// C# program to demonstrate the// use of circular array without// using extra memory spaceusing System;class GFG { // Function to find the Next // Greater Element(NGE) static void printNGE(int[] A, int n) { int k; for(int i = 0; i < n; i++) { // Initialise k as -1 which is // printed when no NGE found k = -1; for(int j = i + 1; j < n + i; j++) { if (A[i] < A[j % n]) { Console.Write(A[j % n] + " "); k = 1; break; } } // Gets executed when no NGE found if (k == -1) Console.Write("-1 "); } } static void Main() { // Given array arr[] int[] arr = { 8, 6, 7 }; int N = arr.Length; // Function call printNGE(arr, N); }} // This code is contributed by divyesh072019
<script> // JavaScript program to demonstrate the // use of circular array without // using extra memory space // Function to find the Next // Greater Element(NGE) function printNGE(A, n) { let k; for(let i = 0; i < n; i++) { // Initialise k as -1 which is // printed when no NGE found k = -1; for(let j = i + 1; j < n + i; j++) { if (A[i] < A[j % n]) { document.write(A[j % n] + " "); k = 1; break; } } // Gets executed when no NGE found if (k == -1) document.write("-1 "); } } // Given array arr[] let arr = [ 8, 6, 7 ]; let N = arr.length; // Function call printNGE(arr, N); </script>
-1 7 8
Time Complexity: O(n2) Auxiliary Space: O(1)
Method 3rd: The method uses the same concept used in method 2 for circular Array but uses Stack to find out the next greater element in O(n) time complexity where n is the size of the array. For better understanding, you can see the next greater element.
C++
Java
Python3
Javascript
#include <bits/stdc++.h>using namespace std; // Function to find the Next Greater Element(NGE)void printNGE(int a[], int n){ stack<int> s; vector<int> ans(n); for (int i = 2 * n - 1; i >= 0; i--) { while (!s.empty() && a[i % n] >= s.top()) s.pop(); if (i < n) { if (!s.empty()) ans[i] = s.top(); else ans[i] = -1; } s.push(a[i % n]); } for (int i = 0; i < n; i++) cout << ans[i] << " ";} // Driver Codeint main(){ int arr[] = { 8, 6, 7 }; int N = sizeof(arr) / sizeof(arr[0]); printNGE(arr, N); return 0;}
/*package whatever //do not write package name here */import java.io.*;import java.util.*;class GFG { public static void printNGE(int[] arr) { Stack<Integer> stack = new Stack<>(); int n = arr.length; int[] result = new int[n]; for(int i = 2*n - 1; i >= 0; i--) { // Remove all the elements in Stack that are less than arr[i%n] while(!stack.isEmpty() && arr[i % n] >= stack.peek()){ stack.pop(); } if(i < n) { if(!stack.isEmpty()) result[i] = stack.peek(); else result[i] = -1; // When none of elements in Stack are greater than arr[i%n] } stack.push(arr[i % n]); } for(int i:result) { System.out.print(i + " "); } } // Driver code public static void main (String[] args) { int[] arr = {8, 6 , 7}; printNGE(arr); }} // This code is contributed by vaibhavpatel1904.
# Function to find the Next Greater Element(NGE)def printNGE(a, n): s = [] ans = [0] * n for i in range(2 * n - 1, -1, -1): while s and a[i % n] >= s[-1]: s.pop() if i < n: if s: ans[i] = s[-1] else: ans[i] = -1 s.append(a[i % n]) for i in range(n): print(ans[i], end=" ") # Driver Codeif __name__ == "__main__": # Given array arr[] arr = [8, 6, 7] N = len(arr) # Function call printNGE(arr, N)
<script> // Function to find the Next Greater Element(NGE)function printNGE(a, n){ let s = [] let ans = new Array(n).fill(0) for(let i=2 * n - 1;i>=0;i--){ while(s.length>0 && a[i % n] >= s[s.length - 1]) s.pop() if(i < n){ if(s.length>0) ans[i] = s[s.length-1] else ans[i] = -1 } s.push(a[i % n]) } for(let i=0;i<n;i++){ document.write(ans[i]," ") }} // Driver Code // Given array arr[]let arr = [8, 6, 7] let N = arr.length // Function callprintNGE(arr, N) // code is contributed by shinjanpatra </script>
-1 7 8
Time Complexity: O(N)Auxiliary Space: O(N)
Method :- 4 In method 3, next greater element is calculated by traversing the array from backward (end) but we can also do the same in forward (start) traversal.
C++
Javascript
// C++ code to find the next greater element// in circular array.#include <bits/stdc++.h>using namespace std; // Function to find the Next Greater Element(NGE)void printNGE(int nums[], int n){ // Stores the next greater element for index i. vector<int> ans(n, -1); stack<int> s; for (int i = 0; i < 2 * n; i++) { while (!s.empty() && nums[s.top()] < nums[i % n]) { ans[s.top()] = nums[i % n]; s.pop(); } if (i < n) s.push(i); } for (auto it : ans) cout << it << " ";} // Driver Codeint main(){ int arr[] = { 8, 6, 7 }; int N = sizeof(arr) / sizeof(arr[0]); printNGE(arr, N); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
<script> // JavaScript code to find the next greater element// in circular array. // Function to find the Next Greater Element(NGE)function printNGE(nums, n){ // Stores the next greater element for index i. let ans = new Array(n).fill(-1); let s = []; for (let i = 0; i < 2 * n; i++) { while (s.length > 0 && nums[s[s.length - 1]] < nums[i % n]) { ans[s[s.length - 1]] = nums[i % n]; s.pop(); } if (i < n) s.push(i); } for (let it of ans) document.write(it , " ");} // Driver Codelet arr = [ 8, 6, 7 ];let N = arr.length;printNGE(arr, N); // This code is contributed by shinjanpatra </script>
-1 7 8
Time Complexity: O(N)Auxiliary Space: O(N)
SHIVAMSINGH67
Code_Mech
tushar1247
yashbeersingh42
divyesh072019
divyeshrabadiya07
susmitakundugoaldanga
suresh07
CoderSaty
shivanisinghss2110
varshagumber28
surindertarika1234
vaibhavpatel1904
khushboogoyal499
amartyaghoshgfg
adityakumar129
shinjanpatra
circular-array
Greedy Algorithms
Algorithms
Arrays
Articles
Arrays
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
Introduction to Algorithms
Converting Roman Numerals to Decimal lying between 1 to 3999
Quick Sort vs Merge Sort
Arrays in Java
Arrays in C/C++
Program for array rotation
Stack Data Structure (Introduction and Program)
Largest Sum Contiguous Subarray | [
{
"code": null,
"e": 24984,
"s": 24956,
"text": "\n20 Apr, 2022"
},
{
"code": null,
"e": 25278,
"s": 24984,
"text": "Given a circular array arr[] of N integers such that the last element of the given array is adjacent to the first element of the array, the task is to print the Next Greater Element in this circular array. Elements for which no greater element exist, consider the next greater element as “-1”."
},
{
"code": null,
"e": 25288,
"s": 25278,
"text": "Examples:"
},
{
"code": null,
"e": 25466,
"s": 25288,
"text": "Input: arr[] = {5, 6, 7} Output: {6, 7, -1} Explanation: Next Greater Element for 5 is 6, for 6 is 7, and for 7 is -1 as we don’t have any element greater than itself so its -1."
},
{
"code": null,
"e": 25683,
"s": 25466,
"text": "Input: arr[] = {4, -2, 5, 8} Output: {5, 5, 8, -1} Explanation: Next Greater Element for 4 is 5, for -2 its 5, for 5 is 8, and for 8 is -1 as we don’t have any element greater than itself so its -1, and for 3 its 4. "
},
{
"code": null,
"e": 25765,
"s": 25683,
"text": "Approach: This problem can be solved using Greedy Approach. Below are the steps: "
},
{
"code": null,
"e": 25878,
"s": 25765,
"text": "For the property of the circular array to be valid append the given array elements to the same array once again."
},
{
"code": null,
"e": 25892,
"s": 25878,
"text": "For Example: "
},
{
"code": null,
"e": 25997,
"s": 25892,
"text": "Let arr[] = {1, 4, 3} After appending the same set of elements arr[] becomes arr[] = {1, 4, 3, 1, 4, 3} "
},
{
"code": null,
"e": 26070,
"s": 25997,
"text": "Find the next greater element till N elements in the above array formed."
},
{
"code": null,
"e": 26144,
"s": 26070,
"text": "If any greater element is found then print that element, else print “-1”."
},
{
"code": null,
"e": 26196,
"s": 26144,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26200,
"s": 26196,
"text": "C++"
},
{
"code": null,
"e": 26205,
"s": 26200,
"text": "Java"
},
{
"code": null,
"e": 26213,
"s": 26205,
"text": "Python3"
},
{
"code": null,
"e": 26216,
"s": 26213,
"text": "C#"
},
{
"code": null,
"e": 26227,
"s": 26216,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the NGEvoid printNGE(int A[], int n){ // Formation of circular array int arr[2 * n]; // Append the given array element twice for (int i = 0; i < 2 * n; i++) arr[i] = A[i % n]; int next, i, j; // Iterate for all the // elements of the array for (i = 0; i < n; i++) { // Initialise NGE as -1 next = -1; for (j = i + 1; j < 2 * n; j++) { // Checking for next // greater element if (arr[i] < arr[j]) { next = arr[j]; break; } } // Print the updated NGE cout << next << \", \"; }} // Driver Codeint main(){ // Given array arr[] int arr[] = { 1, 2, 1 }; int N = sizeof(arr) / sizeof(arr[0]); // Function call printNGE(arr, N); return 0;}",
"e": 27139,
"s": 26227,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*;class GFG{ // Function to find the NGEstatic void printNGE(int []A, int n){ // Formation of circular array int []arr = new int[2 * n]; // Append the given array element twice for(int i = 0; i < 2 * n; i++) arr[i] = A[i % n]; int next; // Iterate for all the // elements of the array for(int i = 0; i < n; i++) { // Initialise NGE as -1 next = -1; for(int j = i + 1; j < 2 * n; j++) { // Checking for next // greater element if (arr[i] < arr[j]) { next = arr[j]; break; } } // Print the updated NGE System.out.print(next + \", \"); }} // Driver Codepublic static void main(String args[]){ // Given array arr[] int []arr = { 1, 2, 1 }; int N = arr.length; // Function call printNGE(arr, N);}} // This code is contributed by Code_Mech",
"e": 28167,
"s": 27139,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to find the NGEdef printNGE(A, n): # Formation of circular array arr = [0] * (2 * n) # Append the given array # element twice for i in range(2 * n): arr[i] = A[i % n] # Iterate for all the # elements of the array for i in range(n): # Initialise NGE as -1 next = -1 for j in range(i + 1, 2 * n): # Checking for next # greater element if(arr[i] < arr[j]): next = arr[j] break # Print the updated NGE print(next, end = \", \") # Driver codeif __name__ == '__main__': # Given array arr[] arr = [ 1, 2, 1 ] N = len(arr) # Function call printNGE(arr, N) # This code is contributed by Shivam Singh",
"e": 28962,
"s": 28167,
"text": null
},
{
"code": "// C# program for the above approachusing System;class GFG{ // Function to find the NGEstatic void printNGE(int []A, int n){ // Formation of circular array int []arr = new int[2 * n]; // Append the given array element twice for(int i = 0; i < 2 * n; i++) arr[i] = A[i % n]; int next; // Iterate for all the // elements of the array for(int i = 0; i < n; i++) { // Initialise NGE as -1 next = -1; for(int j = i + 1; j < 2 * n; j++) { // Checking for next // greater element if (arr[i] < arr[j]) { next = arr[j]; break; } } // Print the updated NGE Console.Write(next + \", \"); }} // Driver Codepublic static void Main(){ // Given array arr[] int []arr = { 1, 2, 1 }; int N = arr.Length; // Function call printNGE(arr, N);}} // This code is contributed by Code_Mech",
"e": 29929,
"s": 28962,
"text": null
},
{
"code": "<script> // JavaScript program for the above approach // Function to find the NGEfunction printNGE(A, n){ // Formation of circular array let arr = Array.from({length: 2 * n}, (_, i) => 0); // Append the given array element twice for(let i = 0; i < 2 * n; i++) arr[i] = A[i % n]; let next; // Iterate for all the // elements of the array for(let i = 0; i < n; i++) { // Initialise NGE as -1 next = -1; for(let j = i + 1; j < 2 * n; j++) { // Checking for next // greater element if (arr[i] < arr[j]) { next = arr[j]; break; } } // Print the updated NGE document.write(next + \", \"); }} // Driver Code // Given array arr[] let arr = [ 1, 2, 1 ]; let N = arr.length; // Function call printNGE(arr, N); </script>",
"e": 30879,
"s": 29929,
"text": null
},
{
"code": null,
"e": 30890,
"s": 30879,
"text": "2, -1, 2, "
},
{
"code": null,
"e": 30960,
"s": 30890,
"text": "This approach takes of O(n2) time but takes extra space of order O(n)"
},
{
"code": null,
"e": 31416,
"s": 30960,
"text": "A space-efficient solution is to deal with circular arrays using the same array. If a careful observation is run through the array, then after the n-th index, the next index always starts from 0 so using the mod operator, we can easily access the elements of the circular list, if we use (i)%n and run the loop from i-th index to n+i-th index, and apply mod we can do the traversal in a circular array within the given array without using any extra space."
},
{
"code": null,
"e": 31468,
"s": 31416,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 31472,
"s": 31468,
"text": "C++"
},
{
"code": null,
"e": 31474,
"s": 31472,
"text": "C"
},
{
"code": null,
"e": 31479,
"s": 31474,
"text": "Java"
},
{
"code": null,
"e": 31487,
"s": 31479,
"text": "Python3"
},
{
"code": null,
"e": 31490,
"s": 31487,
"text": "C#"
},
{
"code": null,
"e": 31501,
"s": 31490,
"text": "Javascript"
},
{
"code": "// C++ program to demonstrate the use of circular// array without using extra memory space#include <bits/stdc++.h>using namespace std; // Function to find the Next Greater Element(NGE)void printNGE(int A[], int n){ int k; for(int i = 0; i < n; i++) { // Initialise k as -1 which is printed // when no NGE found k = -1; for(int j = i + 1; j < n + i; j++) { if (A[i] < A[j % n]) { cout <<\" \"<< A[j % n]; k = 1; break; } } // Gets executed when no NGE found if (k == -1) cout << \"-1 \"; }} // Driver Codeint main(){ // Given array arr[] int arr[] = { 8, 6, 7 }; int N = sizeof(arr) / sizeof(arr[0]); // Function call printNGE(arr, N); return 0;} // This code is contributed by shivanisinghss2110",
"e": 32403,
"s": 31501,
"text": null
},
{
"code": "// C program to demonstrate the use of circular// array without using extra memory space #include <stdio.h> // Function to find the Next Greater Element(NGE)void printNGE(int A[], int n){ int k; for (int i = 0; i < n; i++) { // Initialise k as -1 which is printed when no NGE // found k = -1; // for (int j = i + 1; j < n + i; j++) { if (A[i] < A[j % n]) { printf(\"%d \", A[j % n]); k = 1; break; } } if (k == -1) // Gets executed when no NGE found printf(\"-1 \"); }} // Driver Codeint main(){ // Given array arr[] int arr[] = { 8, 6, 7 }; int N = sizeof(arr) / sizeof(arr[0]); // Function call printNGE(arr, N); return 0;}",
"e": 33175,
"s": 32403,
"text": null
},
{
"code": "// Java program to demonstrate the// use of circular array without// using extra memory spaceimport java.io.*; class GFG{ // Function to find the Next// Greater Element(NGE)static void printNGE(int A[], int n){ int k; for(int i = 0; i < n; i++) { // Initialise k as -1 which is // printed when no NGE found k = -1; for(int j = i + 1; j < n + i; j++) { if (A[i] < A[j % n]) { System.out.print(A[j % n] + \" \"); k = 1; break; } } // Gets executed when no NGE found if (k == -1) System.out.print(\"-1 \"); }} // Driver Codepublic static void main(String[] args){ // Given array arr[] int[] arr = { 8, 6, 7 }; int N = arr.length; // Function call printNGE(arr, N);}} // This code is contributed by yashbeersingh42",
"e": 34083,
"s": 33175,
"text": null
},
{
"code": "# Python3 program to demonstrate the use of circular# array without using extra memory space # Function to find the Next Greater Element(NGE)def printNGE(A, n) : for i in range(n) : # Initialise k as -1 which is printed when no NGE # found k = -1 for j in range(i + 1, n + i) : if (A[i] < A[j % n]) : print(A[j % n], end = \" \") k = 1 break if (k == -1) : # Gets executed when no NGE found print(\"-1 \", end = \"\") # Given array arr[]arr = [ 8, 6, 7 ] N = len(arr) # Function callprintNGE(arr, N) # This code is contributed by divyeshrabadia07",
"e": 34738,
"s": 34083,
"text": null
},
{
"code": "// C# program to demonstrate the// use of circular array without// using extra memory spaceusing System;class GFG { // Function to find the Next // Greater Element(NGE) static void printNGE(int[] A, int n) { int k; for(int i = 0; i < n; i++) { // Initialise k as -1 which is // printed when no NGE found k = -1; for(int j = i + 1; j < n + i; j++) { if (A[i] < A[j % n]) { Console.Write(A[j % n] + \" \"); k = 1; break; } } // Gets executed when no NGE found if (k == -1) Console.Write(\"-1 \"); } } static void Main() { // Given array arr[] int[] arr = { 8, 6, 7 }; int N = arr.Length; // Function call printNGE(arr, N); }} // This code is contributed by divyesh072019",
"e": 35714,
"s": 34738,
"text": null
},
{
"code": "<script> // JavaScript program to demonstrate the // use of circular array without // using extra memory space // Function to find the Next // Greater Element(NGE) function printNGE(A, n) { let k; for(let i = 0; i < n; i++) { // Initialise k as -1 which is // printed when no NGE found k = -1; for(let j = i + 1; j < n + i; j++) { if (A[i] < A[j % n]) { document.write(A[j % n] + \" \"); k = 1; break; } } // Gets executed when no NGE found if (k == -1) document.write(\"-1 \"); } } // Given array arr[] let arr = [ 8, 6, 7 ]; let N = arr.length; // Function call printNGE(arr, N); </script>",
"e": 36591,
"s": 35714,
"text": null
},
{
"code": null,
"e": 36599,
"s": 36591,
"text": "-1 7 8"
},
{
"code": null,
"e": 36645,
"s": 36599,
"text": " Time Complexity: O(n2) Auxiliary Space: O(1)"
},
{
"code": null,
"e": 36900,
"s": 36645,
"text": "Method 3rd: The method uses the same concept used in method 2 for circular Array but uses Stack to find out the next greater element in O(n) time complexity where n is the size of the array. For better understanding, you can see the next greater element."
},
{
"code": null,
"e": 36904,
"s": 36900,
"text": "C++"
},
{
"code": null,
"e": 36909,
"s": 36904,
"text": "Java"
},
{
"code": null,
"e": 36917,
"s": 36909,
"text": "Python3"
},
{
"code": null,
"e": 36928,
"s": 36917,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std; // Function to find the Next Greater Element(NGE)void printNGE(int a[], int n){ stack<int> s; vector<int> ans(n); for (int i = 2 * n - 1; i >= 0; i--) { while (!s.empty() && a[i % n] >= s.top()) s.pop(); if (i < n) { if (!s.empty()) ans[i] = s.top(); else ans[i] = -1; } s.push(a[i % n]); } for (int i = 0; i < n; i++) cout << ans[i] << \" \";} // Driver Codeint main(){ int arr[] = { 8, 6, 7 }; int N = sizeof(arr) / sizeof(arr[0]); printNGE(arr, N); return 0;}",
"e": 37559,
"s": 36928,
"text": null
},
{
"code": "/*package whatever //do not write package name here */import java.io.*;import java.util.*;class GFG { public static void printNGE(int[] arr) { Stack<Integer> stack = new Stack<>(); int n = arr.length; int[] result = new int[n]; for(int i = 2*n - 1; i >= 0; i--) { // Remove all the elements in Stack that are less than arr[i%n] while(!stack.isEmpty() && arr[i % n] >= stack.peek()){ stack.pop(); } if(i < n) { if(!stack.isEmpty()) result[i] = stack.peek(); else result[i] = -1; // When none of elements in Stack are greater than arr[i%n] } stack.push(arr[i % n]); } for(int i:result) { System.out.print(i + \" \"); } } // Driver code public static void main (String[] args) { int[] arr = {8, 6 , 7}; printNGE(arr); }} // This code is contributed by vaibhavpatel1904.",
"e": 38608,
"s": 37559,
"text": null
},
{
"code": "# Function to find the Next Greater Element(NGE)def printNGE(a, n): s = [] ans = [0] * n for i in range(2 * n - 1, -1, -1): while s and a[i % n] >= s[-1]: s.pop() if i < n: if s: ans[i] = s[-1] else: ans[i] = -1 s.append(a[i % n]) for i in range(n): print(ans[i], end=\" \") # Driver Codeif __name__ == \"__main__\": # Given array arr[] arr = [8, 6, 7] N = len(arr) # Function call printNGE(arr, N)",
"e": 39127,
"s": 38608,
"text": null
},
{
"code": "<script> // Function to find the Next Greater Element(NGE)function printNGE(a, n){ let s = [] let ans = new Array(n).fill(0) for(let i=2 * n - 1;i>=0;i--){ while(s.length>0 && a[i % n] >= s[s.length - 1]) s.pop() if(i < n){ if(s.length>0) ans[i] = s[s.length-1] else ans[i] = -1 } s.push(a[i % n]) } for(let i=0;i<n;i++){ document.write(ans[i],\" \") }} // Driver Code // Given array arr[]let arr = [8, 6, 7] let N = arr.length // Function callprintNGE(arr, N) // code is contributed by shinjanpatra </script>",
"e": 39755,
"s": 39127,
"text": null
},
{
"code": null,
"e": 39763,
"s": 39755,
"text": "-1 7 8 "
},
{
"code": null,
"e": 39806,
"s": 39763,
"text": "Time Complexity: O(N)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 39968,
"s": 39806,
"text": "Method :- 4 In method 3, next greater element is calculated by traversing the array from backward (end) but we can also do the same in forward (start) traversal."
},
{
"code": null,
"e": 39972,
"s": 39968,
"text": "C++"
},
{
"code": null,
"e": 39983,
"s": 39972,
"text": "Javascript"
},
{
"code": "// C++ code to find the next greater element// in circular array.#include <bits/stdc++.h>using namespace std; // Function to find the Next Greater Element(NGE)void printNGE(int nums[], int n){ // Stores the next greater element for index i. vector<int> ans(n, -1); stack<int> s; for (int i = 0; i < 2 * n; i++) { while (!s.empty() && nums[s.top()] < nums[i % n]) { ans[s.top()] = nums[i % n]; s.pop(); } if (i < n) s.push(i); } for (auto it : ans) cout << it << \" \";} // Driver Codeint main(){ int arr[] = { 8, 6, 7 }; int N = sizeof(arr) / sizeof(arr[0]); printNGE(arr, N); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 40721,
"s": 39983,
"text": null
},
{
"code": "<script> // JavaScript code to find the next greater element// in circular array. // Function to find the Next Greater Element(NGE)function printNGE(nums, n){ // Stores the next greater element for index i. let ans = new Array(n).fill(-1); let s = []; for (let i = 0; i < 2 * n; i++) { while (s.length > 0 && nums[s[s.length - 1]] < nums[i % n]) { ans[s[s.length - 1]] = nums[i % n]; s.pop(); } if (i < n) s.push(i); } for (let it of ans) document.write(it , \" \");} // Driver Codelet arr = [ 8, 6, 7 ];let N = arr.length;printNGE(arr, N); // This code is contributed by shinjanpatra </script>",
"e": 41394,
"s": 40721,
"text": null
},
{
"code": null,
"e": 41402,
"s": 41394,
"text": "-1 7 8 "
},
{
"code": null,
"e": 41445,
"s": 41402,
"text": "Time Complexity: O(N)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 41459,
"s": 41445,
"text": "SHIVAMSINGH67"
},
{
"code": null,
"e": 41469,
"s": 41459,
"text": "Code_Mech"
},
{
"code": null,
"e": 41480,
"s": 41469,
"text": "tushar1247"
},
{
"code": null,
"e": 41496,
"s": 41480,
"text": "yashbeersingh42"
},
{
"code": null,
"e": 41510,
"s": 41496,
"text": "divyesh072019"
},
{
"code": null,
"e": 41528,
"s": 41510,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 41550,
"s": 41528,
"text": "susmitakundugoaldanga"
},
{
"code": null,
"e": 41559,
"s": 41550,
"text": "suresh07"
},
{
"code": null,
"e": 41569,
"s": 41559,
"text": "CoderSaty"
},
{
"code": null,
"e": 41588,
"s": 41569,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 41603,
"s": 41588,
"text": "varshagumber28"
},
{
"code": null,
"e": 41622,
"s": 41603,
"text": "surindertarika1234"
},
{
"code": null,
"e": 41639,
"s": 41622,
"text": "vaibhavpatel1904"
},
{
"code": null,
"e": 41656,
"s": 41639,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 41672,
"s": 41656,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 41687,
"s": 41672,
"text": "adityakumar129"
},
{
"code": null,
"e": 41700,
"s": 41687,
"text": "shinjanpatra"
},
{
"code": null,
"e": 41715,
"s": 41700,
"text": "circular-array"
},
{
"code": null,
"e": 41733,
"s": 41715,
"text": "Greedy Algorithms"
},
{
"code": null,
"e": 41744,
"s": 41733,
"text": "Algorithms"
},
{
"code": null,
"e": 41751,
"s": 41744,
"text": "Arrays"
},
{
"code": null,
"e": 41760,
"s": 41751,
"text": "Articles"
},
{
"code": null,
"e": 41767,
"s": 41760,
"text": "Arrays"
},
{
"code": null,
"e": 41778,
"s": 41767,
"text": "Algorithms"
},
{
"code": null,
"e": 41876,
"s": 41778,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 41925,
"s": 41876,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 41950,
"s": 41925,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 41977,
"s": 41950,
"text": "Introduction to Algorithms"
},
{
"code": null,
"e": 42038,
"s": 41977,
"text": "Converting Roman Numerals to Decimal lying between 1 to 3999"
},
{
"code": null,
"e": 42063,
"s": 42038,
"text": "Quick Sort vs Merge Sort"
},
{
"code": null,
"e": 42078,
"s": 42063,
"text": "Arrays in Java"
},
{
"code": null,
"e": 42094,
"s": 42078,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 42121,
"s": 42094,
"text": "Program for array rotation"
},
{
"code": null,
"e": 42169,
"s": 42121,
"text": "Stack Data Structure (Introduction and Program)"
}
] |
Check if list contains consecutive numbers in Python | Depending on the needs of our data analysis we may need to check for presence of sequential numbers in a python data container. In the below programs we find out if among the elements of Alist, there are any consecutive numbers.
The sorted function will rearrange the elements of the list in a sorted order. We then apply the range function taking the lowest and highest numbers form the list using min and max functions. We store the results of above operations in two lists and compare them for equality.
Live Demo
listA = [23,20,22,21,24]
sorted_list = sorted(listA)
#sorted(l) ==
range_list=list(range(min(listA), max(listA)+1))
if sorted_list == range_list:
print("listA has consecutive numbers")
else:
print("listA has no consecutive numbers")
# Checking again
listB = [23,20,13,21,24]
sorted_list = sorted(listB)
#sorted(l) ==
range_list=list(range(min(listB), max(listB)+1))
if sorted_list == range_list:
print("ListB has consecutive numbers")
else:
print("ListB has no consecutive numbers")
Running the above code gives us the following result −
listA has consecutive numbers
ListB has no consecutive numbers
The diff function in numpy can find the difference between each of the numbers after they are sorted. We take a sum of this differences. That will match the length of the list if all numbers are consecutive.
Live Demo
import numpy as np
listA = [23,20,22,21,24]
sorted_list_diffs = sum(np.diff(sorted(listA)))
if sorted_list_diffs == (len(listA) - 1):
print("listA has consecutive numbers")
else:
print("listA has no consecutive numbers")
# Checking again
listB = [23,20,13,21,24]
sorted_list_diffs = sum(np.diff(sorted(listB)))
if sorted_list_diffs == (len(listB) - 1):
print("ListB has consecutive numbers")
else:
print("ListB has no consecutive numbers")
Running the above code gives us the following result −
listA has consecutive numbers
ListB has no consecutive numbers | [
{
"code": null,
"e": 1291,
"s": 1062,
"text": "Depending on the needs of our data analysis we may need to check for presence of sequential numbers in a python data container. In the below programs we find out if among the elements of Alist, there are any consecutive numbers."
},
{
"code": null,
"e": 1569,
"s": 1291,
"text": "The sorted function will rearrange the elements of the list in a sorted order. We then apply the range function taking the lowest and highest numbers form the list using min and max functions. We store the results of above operations in two lists and compare them for equality."
},
{
"code": null,
"e": 1580,
"s": 1569,
"text": " Live Demo"
},
{
"code": null,
"e": 2076,
"s": 1580,
"text": "listA = [23,20,22,21,24]\nsorted_list = sorted(listA)\n#sorted(l) ==\nrange_list=list(range(min(listA), max(listA)+1))\nif sorted_list == range_list:\n print(\"listA has consecutive numbers\")\nelse:\n print(\"listA has no consecutive numbers\")\n\n# Checking again\nlistB = [23,20,13,21,24]\nsorted_list = sorted(listB)\n#sorted(l) ==\nrange_list=list(range(min(listB), max(listB)+1))\nif sorted_list == range_list:\n print(\"ListB has consecutive numbers\")\nelse:\n print(\"ListB has no consecutive numbers\")"
},
{
"code": null,
"e": 2131,
"s": 2076,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2194,
"s": 2131,
"text": "listA has consecutive numbers\nListB has no consecutive numbers"
},
{
"code": null,
"e": 2402,
"s": 2194,
"text": "The diff function in numpy can find the difference between each of the numbers after they are sorted. We take a sum of this differences. That will match the length of the list if all numbers are consecutive."
},
{
"code": null,
"e": 2413,
"s": 2402,
"text": " Live Demo"
},
{
"code": null,
"e": 2867,
"s": 2413,
"text": "import numpy as np\nlistA = [23,20,22,21,24]\n\nsorted_list_diffs = sum(np.diff(sorted(listA)))\nif sorted_list_diffs == (len(listA) - 1):\n print(\"listA has consecutive numbers\")\nelse:\n print(\"listA has no consecutive numbers\")\n\n# Checking again\nlistB = [23,20,13,21,24]\nsorted_list_diffs = sum(np.diff(sorted(listB)))\nif sorted_list_diffs == (len(listB) - 1):\n print(\"ListB has consecutive numbers\")\nelse:\n print(\"ListB has no consecutive numbers\")"
},
{
"code": null,
"e": 2922,
"s": 2867,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2985,
"s": 2922,
"text": "listA has consecutive numbers\nListB has no consecutive numbers"
}
] |
What are the different types of keywords in C language? | Keywords are generally called as pre-defined or reserved words in a programming language. Every keyword in C language performs a specific function in a program.
Keywords cannot be used as variable names.
Keywords cannot be used as variable names.
Keywords have fixed meanings, and that meaning cannot be changed.
Keywords have fixed meanings, and that meaning cannot be changed.
They are the building block of a 'C' program.
They are the building block of a 'C' program.
C supports 32 keywords.
C supports 32 keywords.
All the keywords are written in lowercase letters.
All the keywords are written in lowercase letters.
The different types of keywords are as follows −
Given below is the C program for the Simple Calculator by using the Switch Case −
Live Demo
#include <stdio.h>
int main(){
char Operator;
float num1, num2, result = 0;
printf("\n Try to Enter an Operator (+, -, *, /) : ");
scanf("%c", &Operator);
printf("\n Enter the Values for two Operands: ");
scanf("%f%f", &num1, &num2);
switch(Operator){
case '+': result = num1 + num2;
break;
case '-': result = num1 - num2;
break;
case '*': result = num1 * num2;
break;
case '/': result = num1 / num2;
break;
default: printf("\n entered operator is invalid ");
}
printf("\n The result of %.2f %c %.2f = %.2f", num1, Operator, num2, result);
return 0;
}
When the above program is executed, it produces the following result −
Enter an Operator (+, -, *, /) : *
Enter the Values for two Operands: 34 12
The result of 34.00 * 12.00 = 408.00
In the above example, the keywords that are used to perform a simple calculator program are as follows −
Int, char, switch, case, break, float, default, return
These words cannot be used as variables while writing the program. | [
{
"code": null,
"e": 1223,
"s": 1062,
"text": "Keywords are generally called as pre-defined or reserved words in a programming language. Every keyword in C language performs a specific function in a program."
},
{
"code": null,
"e": 1266,
"s": 1223,
"text": "Keywords cannot be used as variable names."
},
{
"code": null,
"e": 1309,
"s": 1266,
"text": "Keywords cannot be used as variable names."
},
{
"code": null,
"e": 1375,
"s": 1309,
"text": "Keywords have fixed meanings, and that meaning cannot be changed."
},
{
"code": null,
"e": 1441,
"s": 1375,
"text": "Keywords have fixed meanings, and that meaning cannot be changed."
},
{
"code": null,
"e": 1487,
"s": 1441,
"text": "They are the building block of a 'C' program."
},
{
"code": null,
"e": 1533,
"s": 1487,
"text": "They are the building block of a 'C' program."
},
{
"code": null,
"e": 1557,
"s": 1533,
"text": "C supports 32 keywords."
},
{
"code": null,
"e": 1581,
"s": 1557,
"text": "C supports 32 keywords."
},
{
"code": null,
"e": 1632,
"s": 1581,
"text": "All the keywords are written in lowercase letters."
},
{
"code": null,
"e": 1683,
"s": 1632,
"text": "All the keywords are written in lowercase letters."
},
{
"code": null,
"e": 1732,
"s": 1683,
"text": "The different types of keywords are as follows −"
},
{
"code": null,
"e": 1814,
"s": 1732,
"text": "Given below is the C program for the Simple Calculator by using the Switch Case −"
},
{
"code": null,
"e": 1825,
"s": 1814,
"text": " Live Demo"
},
{
"code": null,
"e": 2461,
"s": 1825,
"text": "#include <stdio.h>\nint main(){\n char Operator;\n float num1, num2, result = 0;\n printf(\"\\n Try to Enter an Operator (+, -, *, /) : \");\n scanf(\"%c\", &Operator);\n printf(\"\\n Enter the Values for two Operands: \");\n scanf(\"%f%f\", &num1, &num2);\n switch(Operator){\n case '+': result = num1 + num2;\n break;\n case '-': result = num1 - num2;\n break;\n case '*': result = num1 * num2;\n break;\n case '/': result = num1 / num2;\n break;\n default: printf(\"\\n entered operator is invalid \");\n }\n printf(\"\\n The result of %.2f %c %.2f = %.2f\", num1, Operator, num2, result);\n return 0;\n}"
},
{
"code": null,
"e": 2532,
"s": 2461,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 2645,
"s": 2532,
"text": "Enter an Operator (+, -, *, /) : *\nEnter the Values for two Operands: 34 12\nThe result of 34.00 * 12.00 = 408.00"
},
{
"code": null,
"e": 2750,
"s": 2645,
"text": "In the above example, the keywords that are used to perform a simple calculator program are as follows −"
},
{
"code": null,
"e": 2805,
"s": 2750,
"text": "Int, char, switch, case, break, float, default, return"
},
{
"code": null,
"e": 2872,
"s": 2805,
"text": "These words cannot be used as variables while writing the program."
}
] |
Guide on AWS Textract set-up. On how to accurately process PDF files... | by Daulet Nurmanbetov | Towards Data Science | How to accurately process PDF files with OCR-as-a-service from AWS
Recently a new paradigm of async API responses has become prominent. It works by returning Job-ID rather than an API response. Then, to check the status, the user would need to submit a second call to the API with the Job ID. Here’s an excellent guide on it.
Async API response is typically used for heavyweight machine learning applications or applications that move large volumes of data, i.e. anything that would take forever to get the results synchronously back to the user.
AWS Textract can detect and analyze the text in multi-page documents that are in PDF format. Textract uses asynchronous responses for its API. Behind the scene, each PDF is separated into a single-page format and sent to the processing engine so that each page can be handled independently of the PDF document and the system can be scaled horizontally. Besides, the async operation allows the user to submit a PDF file with over 1,000 pages to be processed and to return later to check results rather than waiting on request.
Let’s go over the steps required to set up an EC2 machine to call Textract in Python:
1 — Set up an AWS role to access Amazon Textract from EC2 instance.
a) On the Create role page the service that will use this role — Select EC2 and go to Next: Permissions
b) We will need to grant the following 4 permissions to set up Textract — AmazonTextractFullAccessAmazonS3ReadOnlyAccessAmazonSNSFullAccessAmazonSQSFullAccess
(You may want to reduce access permissions once SNS, SQS and Textract configs have been set)
c) Skip Tags and go to Review. Call it something snappy.
d) Go to EC2 page and under Instances select the machine that will be calling Textract and attach the role you have created from a) like in the picture below —
2 — Log in to the EC2 Machine that you’ve added the role to and Install the required AWS SDK for Python — boto3
> pip install boto3
3 — Create an IAM service role to give Amazon Textract access to your Amazon SNS topics. This will allow Textract to notify you when the document is completed analyzing. See Giving Amazon Textract Access to Your Amazon SNS Topic for detailed access rights. Save the Amazon Resource Name (ARN) of the service role as you will need to supply it to Textract.
Following the above reference, the role you create will indicate the following in the policy statement —
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "ec2.amazonaws.com" }, "Action": "sts:AssumeRole" } ]}
you will need to replace it with —
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "textract.amazonaws.com" }, "Action": "sts:AssumeRole" } ]}
4 — Run the following code in the EC2 instance to analyze PDFs with Textract. The PDFs must be located in your S3 bucket.
We’ve covered how to use AWS Textract on images and PDFs in your S3 via the code provided above.
Setting up Textract is a bit complex, but if you look at the code you will see why that is the case. The code creates both a new SQS Queue and a new SNS Topic and subscribes the queue to the topic we created.
Next, in the code we instruct Textract location of the desired PDF to be processed as well as the SNS Channel to communicate over. | [
{
"code": null,
"e": 113,
"s": 46,
"text": "How to accurately process PDF files with OCR-as-a-service from AWS"
},
{
"code": null,
"e": 372,
"s": 113,
"text": "Recently a new paradigm of async API responses has become prominent. It works by returning Job-ID rather than an API response. Then, to check the status, the user would need to submit a second call to the API with the Job ID. Here’s an excellent guide on it."
},
{
"code": null,
"e": 593,
"s": 372,
"text": "Async API response is typically used for heavyweight machine learning applications or applications that move large volumes of data, i.e. anything that would take forever to get the results synchronously back to the user."
},
{
"code": null,
"e": 1119,
"s": 593,
"text": "AWS Textract can detect and analyze the text in multi-page documents that are in PDF format. Textract uses asynchronous responses for its API. Behind the scene, each PDF is separated into a single-page format and sent to the processing engine so that each page can be handled independently of the PDF document and the system can be scaled horizontally. Besides, the async operation allows the user to submit a PDF file with over 1,000 pages to be processed and to return later to check results rather than waiting on request."
},
{
"code": null,
"e": 1205,
"s": 1119,
"text": "Let’s go over the steps required to set up an EC2 machine to call Textract in Python:"
},
{
"code": null,
"e": 1273,
"s": 1205,
"text": "1 — Set up an AWS role to access Amazon Textract from EC2 instance."
},
{
"code": null,
"e": 1377,
"s": 1273,
"text": "a) On the Create role page the service that will use this role — Select EC2 and go to Next: Permissions"
},
{
"code": null,
"e": 1536,
"s": 1377,
"text": "b) We will need to grant the following 4 permissions to set up Textract — AmazonTextractFullAccessAmazonS3ReadOnlyAccessAmazonSNSFullAccessAmazonSQSFullAccess"
},
{
"code": null,
"e": 1629,
"s": 1536,
"text": "(You may want to reduce access permissions once SNS, SQS and Textract configs have been set)"
},
{
"code": null,
"e": 1686,
"s": 1629,
"text": "c) Skip Tags and go to Review. Call it something snappy."
},
{
"code": null,
"e": 1846,
"s": 1686,
"text": "d) Go to EC2 page and under Instances select the machine that will be calling Textract and attach the role you have created from a) like in the picture below —"
},
{
"code": null,
"e": 1958,
"s": 1846,
"text": "2 — Log in to the EC2 Machine that you’ve added the role to and Install the required AWS SDK for Python — boto3"
},
{
"code": null,
"e": 1978,
"s": 1958,
"text": "> pip install boto3"
},
{
"code": null,
"e": 2335,
"s": 1978,
"text": "3 — Create an IAM service role to give Amazon Textract access to your Amazon SNS topics. This will allow Textract to notify you when the document is completed analyzing. See Giving Amazon Textract Access to Your Amazon SNS Topic for detailed access rights. Save the Amazon Resource Name (ARN) of the service role as you will need to supply it to Textract."
},
{
"code": null,
"e": 2440,
"s": 2335,
"text": "Following the above reference, the role you create will indicate the following in the policy statement —"
},
{
"code": null,
"e": 2620,
"s": 2440,
"text": "{ \"Version\": \"2012-10-17\", \"Statement\": [ { \"Effect\": \"Allow\", \"Principal\": { \"Service\": \"ec2.amazonaws.com\" }, \"Action\": \"sts:AssumeRole\" } ]}"
},
{
"code": null,
"e": 2655,
"s": 2620,
"text": "you will need to replace it with —"
},
{
"code": null,
"e": 2840,
"s": 2655,
"text": "{ \"Version\": \"2012-10-17\", \"Statement\": [ { \"Effect\": \"Allow\", \"Principal\": { \"Service\": \"textract.amazonaws.com\" }, \"Action\": \"sts:AssumeRole\" } ]}"
},
{
"code": null,
"e": 2962,
"s": 2840,
"text": "4 — Run the following code in the EC2 instance to analyze PDFs with Textract. The PDFs must be located in your S3 bucket."
},
{
"code": null,
"e": 3059,
"s": 2962,
"text": "We’ve covered how to use AWS Textract on images and PDFs in your S3 via the code provided above."
},
{
"code": null,
"e": 3268,
"s": 3059,
"text": "Setting up Textract is a bit complex, but if you look at the code you will see why that is the case. The code creates both a new SQS Queue and a new SNS Topic and subscribes the queue to the topic we created."
}
] |
Testing and Building Angular7 Projects | In this chapter will discuss the following topics −
To test Angular 7 Project
To build Angular 7 Project
During the project setup, the required packages for testing are already installed. There is a .spec.ts file created for every new component, service, directive, etc. We are going to use jasmine to write our test cases.
For any changes added to your component, services, directives or any other files created, you can include your test cases in the respective .spec.ts files. So most of the unit testing can be covered at the beginning itself.
To run the test cases, the command used is as follows−
ng test
Below is the app.component.spec.ts file for app.component.ts −
import { TestBed, async } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule
],
declarations: [
AppComponent
],
}).compileComponents();
}));
it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy();
});
it(`should have as title 'angular7-app'`, () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app.title).toEqual('angular7-app');
});
it('should render title in a h1 tag', () => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.debugElement.nativeElement;
expect(compiled.querySelector('h1').textContent).toContain(
'Welcome to angular7-app!');
})
});
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'angular7-app';
}
Now let us run the command to see the test cases running.
The test cases status is shown in the command line as shown above and will also open up in the browser as shown below −
Incase of any failure, it will show the details as follows −
To do that, let us change the app.component.spec.ts as follows −
import { TestBed, async } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule
],
declarations: [
AppComponent
],
}).compileComponents();
}));
it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy();
});
it(`should have as title 'angular7-app'`, () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app.title).toEqual('Angular 7'); // change the
title from angular7-app to Angular 7
});
it('should render title in a h1 tag', () => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.debugElement.nativeElement;
expect(compiled.querySelector('h1').textContent).toContain(
'Welcome to angular7-app!');
});
});
In the above file, the test cases check for the title, Angular 7. But in app.component.ts, we have the title, angular7-app as shown below −
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'angular7-app';
}
Here the test case will fail and below are the details shown in command line and browser.
Following screen is displayed in command line −
Following screen is displayed in the browser −
All the failed test-cases for your project will be displayed as shown above in command line and browser.
Similarly, you can write test cases for your services, directives and the new components which will be added to your project.
Once you are done with the project in Angular, we need to build it so that it can be used in production or stating.
The configuration for build, i.e., production, staging, development, testing needs to be defined in your src/environments.
At present, we have the following environments defined in src/environment −
You can add files based on your build to src/environment, i.e., environment.staging.ts, enviornment.testing.ts, etc.
At present, we will try to build for production environment. The file environment.ts contains default environment settings and details of the file as follows −
export const environment = {
production: false
};
To build the file for production, we need to make the production: true in environment.ts as follows −
export const environment = {
production: true
};
The default environment file has to be imported inside components as follows −
app.component.ts
import { Component } from '@angular/core';
import { environment } from './../environments/environment';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'angular7-app';
}
The environment replacement from default to production which we are trying to do are defined inside angular.json fileReplacements section as follows −
"production": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],
}
When the command for build runs, the file gets replaced to src/environments/environment.prod.ts. The additional configuration like staging or testing can be added here as shown in the below example −
"configurations": {
"production": { ... },
"staging": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.staging.ts"
}
]
}
}
So the command to run the build is as follows −
ng build --configuration = production // for production environmnet
ng build --configuration = staging // for stating enviroment
Now let us run the build command for production, the command will create a dist folder inside our project which will have the final files after build.
The final files are build inside dist/ folder which can be hosted on the production server at your end.
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": 2113,
"s": 2061,
"text": "In this chapter will discuss the following topics −"
},
{
"code": null,
"e": 2139,
"s": 2113,
"text": "To test Angular 7 Project"
},
{
"code": null,
"e": 2166,
"s": 2139,
"text": "To build Angular 7 Project"
},
{
"code": null,
"e": 2385,
"s": 2166,
"text": "During the project setup, the required packages for testing are already installed. There is a .spec.ts file created for every new component, service, directive, etc. We are going to use jasmine to write our test cases."
},
{
"code": null,
"e": 2609,
"s": 2385,
"text": "For any changes added to your component, services, directives or any other files created, you can include your test cases in the respective .spec.ts files. So most of the unit testing can be covered at the beginning itself."
},
{
"code": null,
"e": 2664,
"s": 2609,
"text": "To run the test cases, the command used is as follows−"
},
{
"code": null,
"e": 2673,
"s": 2664,
"text": "ng test\n"
},
{
"code": null,
"e": 2736,
"s": 2673,
"text": "Below is the app.component.spec.ts file for app.component.ts −"
},
{
"code": null,
"e": 3907,
"s": 2736,
"text": "import { TestBed, async } from '@angular/core/testing';\nimport { RouterTestingModule } from '@angular/router/testing';\nimport { AppComponent } from './app.component';\n\ndescribe('AppComponent', () => {\n beforeEach(async(() => {\n TestBed.configureTestingModule({\n imports: [\n RouterTestingModule\n ],\n declarations: [\n AppComponent\n ],\n }).compileComponents();\n }));\n it('should create the app', () => {\n const fixture = TestBed.createComponent(AppComponent);\n const app = fixture.debugElement.componentInstance;\n expect(app).toBeTruthy();\n });\n it(`should have as title 'angular7-app'`, () => {\n const fixture = TestBed.createComponent(AppComponent);\n const app = fixture.debugElement.componentInstance;\n expect(app.title).toEqual('angular7-app');\n });\n it('should render title in a h1 tag', () => {\n const fixture = TestBed.createComponent(AppComponent);\n fixture.detectChanges();\n const compiled = fixture.debugElement.nativeElement;\n expect(compiled.querySelector('h1').textContent).toContain(\n 'Welcome to angular7-app!');\n })\n});"
},
{
"code": null,
"e": 3924,
"s": 3907,
"text": "app.component.ts"
},
{
"code": null,
"e": 4143,
"s": 3924,
"text": "import { Component } from '@angular/core';\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\nexport class AppComponent {\n title = 'angular7-app';\n}"
},
{
"code": null,
"e": 4201,
"s": 4143,
"text": "Now let us run the command to see the test cases running."
},
{
"code": null,
"e": 4321,
"s": 4201,
"text": "The test cases status is shown in the command line as shown above and will also open up in the browser as shown below −"
},
{
"code": null,
"e": 4382,
"s": 4321,
"text": "Incase of any failure, it will show the details as follows −"
},
{
"code": null,
"e": 4447,
"s": 4382,
"text": "To do that, let us change the app.component.spec.ts as follows −"
},
{
"code": null,
"e": 5674,
"s": 4447,
"text": "import { TestBed, async } from '@angular/core/testing';\nimport { RouterTestingModule } from '@angular/router/testing';\nimport { AppComponent } from './app.component';\n\ndescribe('AppComponent', () => {\n beforeEach(async(() => {\n TestBed.configureTestingModule({\n imports: [\n RouterTestingModule\n ],\n declarations: [\n AppComponent\n ],\n }).compileComponents();\n }));\n it('should create the app', () => {\n const fixture = TestBed.createComponent(AppComponent);\n const app = fixture.debugElement.componentInstance;\n expect(app).toBeTruthy();\n });\n it(`should have as title 'angular7-app'`, () => {\n const fixture = TestBed.createComponent(AppComponent);\n const app = fixture.debugElement.componentInstance;\n expect(app.title).toEqual('Angular 7'); // change the \n title from angular7-app to Angular 7\n });\n it('should render title in a h1 tag', () => {\n const fixture = TestBed.createComponent(AppComponent);\n fixture.detectChanges();\n const compiled = fixture.debugElement.nativeElement;\n expect(compiled.querySelector('h1').textContent).toContain(\n 'Welcome to angular7-app!');\n });\n});"
},
{
"code": null,
"e": 5814,
"s": 5674,
"text": "In the above file, the test cases check for the title, Angular 7. But in app.component.ts, we have the title, angular7-app as shown below −"
},
{
"code": null,
"e": 6033,
"s": 5814,
"text": "import { Component } from '@angular/core';\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\nexport class AppComponent {\n title = 'angular7-app';\n}"
},
{
"code": null,
"e": 6123,
"s": 6033,
"text": "Here the test case will fail and below are the details shown in command line and browser."
},
{
"code": null,
"e": 6171,
"s": 6123,
"text": "Following screen is displayed in command line −"
},
{
"code": null,
"e": 6218,
"s": 6171,
"text": "Following screen is displayed in the browser −"
},
{
"code": null,
"e": 6323,
"s": 6218,
"text": "All the failed test-cases for your project will be displayed as shown above in command line and browser."
},
{
"code": null,
"e": 6449,
"s": 6323,
"text": "Similarly, you can write test cases for your services, directives and the new components which will be added to your project."
},
{
"code": null,
"e": 6565,
"s": 6449,
"text": "Once you are done with the project in Angular, we need to build it so that it can be used in production or stating."
},
{
"code": null,
"e": 6688,
"s": 6565,
"text": "The configuration for build, i.e., production, staging, development, testing needs to be defined in your src/environments."
},
{
"code": null,
"e": 6764,
"s": 6688,
"text": "At present, we have the following environments defined in src/environment −"
},
{
"code": null,
"e": 6881,
"s": 6764,
"text": "You can add files based on your build to src/environment, i.e., environment.staging.ts, enviornment.testing.ts, etc."
},
{
"code": null,
"e": 7041,
"s": 6881,
"text": "At present, we will try to build for production environment. The file environment.ts contains default environment settings and details of the file as follows −"
},
{
"code": null,
"e": 7095,
"s": 7041,
"text": "export const environment = {\n production: false\n};\n"
},
{
"code": null,
"e": 7197,
"s": 7095,
"text": "To build the file for production, we need to make the production: true in environment.ts as follows −"
},
{
"code": null,
"e": 7250,
"s": 7197,
"text": "export const environment = {\n production: true\n};\n"
},
{
"code": null,
"e": 7329,
"s": 7250,
"text": "The default environment file has to be imported inside components as follows −"
},
{
"code": null,
"e": 7346,
"s": 7329,
"text": "app.component.ts"
},
{
"code": null,
"e": 7627,
"s": 7346,
"text": "import { Component } from '@angular/core';\nimport { environment } from './../environments/environment';\n\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\nexport class AppComponent {\n title = 'angular7-app';\n}"
},
{
"code": null,
"e": 7778,
"s": 7627,
"text": "The environment replacement from default to production which we are trying to do are defined inside angular.json fileReplacements section as follows −"
},
{
"code": null,
"e": 7954,
"s": 7778,
"text": "\"production\": {\n \"fileReplacements\": [\n {\n \"replace\": \"src/environments/environment.ts\",\n \"with\": \"src/environments/environment.prod.ts\"\n }\n ],\n}"
},
{
"code": null,
"e": 8154,
"s": 7954,
"text": "When the command for build runs, the file gets replaced to src/environments/environment.prod.ts. The additional configuration like staging or testing can be added here as shown in the below example −"
},
{
"code": null,
"e": 8401,
"s": 8154,
"text": "\"configurations\": {\n \"production\": { ... },\n \"staging\": {\n \"fileReplacements\": [\n {\n \"replace\": \"src/environments/environment.ts\",\n \"with\": \"src/environments/environment.staging.ts\"\n }\n ]\n }\n}"
},
{
"code": null,
"e": 8449,
"s": 8401,
"text": "So the command to run the build is as follows −"
},
{
"code": null,
"e": 8579,
"s": 8449,
"text": "ng build --configuration = production // for production environmnet\nng build --configuration = staging // for stating enviroment\n"
},
{
"code": null,
"e": 8730,
"s": 8579,
"text": "Now let us run the build command for production, the command will create a dist folder inside our project which will have the final files after build."
},
{
"code": null,
"e": 8834,
"s": 8730,
"text": "The final files are build inside dist/ folder which can be hosted on the production server at your end."
},
{
"code": null,
"e": 8869,
"s": 8834,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 8883,
"s": 8869,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 8918,
"s": 8883,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8932,
"s": 8918,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 8967,
"s": 8932,
"text": "\n 11 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 8987,
"s": 8967,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 9022,
"s": 8987,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 9039,
"s": 9022,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 9072,
"s": 9039,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 9084,
"s": 9072,
"text": " Senol Atac"
},
{
"code": null,
"e": 9119,
"s": 9084,
"text": "\n 53 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 9131,
"s": 9119,
"text": " Senol Atac"
},
{
"code": null,
"e": 9138,
"s": 9131,
"text": " Print"
},
{
"code": null,
"e": 9149,
"s": 9138,
"text": " Add Notes"
}
] |
How to use wildcard in Python regular expression? | The following code uses the Python regex .()dot character for wildcard which stands for any character other than newline.
import re
rex = re.compile('th.s')
l = "this, thus, just, then"
print rex.findall(l)
This gives the output
['this', 'thus'] | [
{
"code": null,
"e": 1184,
"s": 1062,
"text": "The following code uses the Python regex .()dot character for wildcard which stands for any character other than newline."
},
{
"code": null,
"e": 1269,
"s": 1184,
"text": "import re\nrex = re.compile('th.s')\nl = \"this, thus, just, then\"\nprint rex.findall(l)"
},
{
"code": null,
"e": 1291,
"s": 1269,
"text": "This gives the output"
},
{
"code": null,
"e": 1308,
"s": 1291,
"text": "['this', 'thus']"
}
] |
How your data is stored on disk and memory? | by Guangyuan(Frank) Li | Towards Data Science | I consider myself as an applied programmer, I use high-level programming languages like Python to manipulate the data frames, build simple pipelines to facilitate the data analysis of certain tasks. However, at the atomic level, the computer itself doesn’t understand what “pandas.read_csv()” means or what the “write.table()” function actually does. It makes me wonder about the intermediate steps involved in converting our commands to 0/1 binary bits and prompts me to write this article.
In this article, I am hoping to give you a rough and intuitive image of what the disk actually looks like, how your data lays out on the disk, and what’s the information exchanges between your disk and memory. This is not meant to be a strictly technical blog but more like relaxing reading material. Being aware of the physical hardware structure can help us to get a better understanding of the tasks and problems we may encounter in our work:
memory leakage? indexing file? memory overhead? I/O streaming?
So brace up yourself and let’s get into that!
When you are on your PC or Mac, you open the Computer or Finder, all the files that appear there are stored on the disk, sometime the disk is also referred to as storage. Nowadays, nearly most personal computers are using Solid State Disk (SSD), however, to convey some intuition, I am going to use Hard Disk (HD) to illustrate the physical structure of the disk.
The structure of a typical hard disk looks like a CD player, it has an arm that can rotate and changes to a selected track, the head of the arm is able to read, write or erase the data stored in each track of the surface.
The surface is also referred to as a platter, and a platter can be split into a set of physical units called a sector. There are gaps between each sector and several sectors constitute a block, the block is the logical unit.
If I tell you one track in a platter has a maximum capacity of 1024Kb (1Mb), then you know your Excel file, which let’s imagine is 2Mb, will occupy two platters to store it in the disk.
If the rotation speed is known, then you can easily compute how fast the files/bits can be transferred from the disk to memory or vice versus. It also becomes clear that why a large file needs more time to read because it needs longer time to rotate the arms and arms also take longer to read since the storage area will be bigger.
Solid State Disk (SSD) will have faster accessing time, and the architecture is quite different from the hard disk (HD) example that I showed you above. But hopefully, that can provide you a clear image that where your files lie on, and next I will show you how the data actually lies on the disk.
In a Database Management System (DBMS), each record (a record is basically a row in a data frame) lies on disk in some particular manner to speed up the search, insert, and deletion. Imagine if every record is scattered around the disk without any rules or organizations, there will be no way to perform the query, indexing, and any manipulations.
Simply speaking, you can store all the data in a row-wise manner, meaning to say that similar records/rows will be gathered together. In doing so, row-wise indexing can be very efficient with the cost of adding column operation or column-wise indexing can be relatively slow. If you go along the column-wise manner, things would become exactly the opposite.
Let’s imagine each row will be stored in a coalesced space on disk, as shown in the figure. The physical address or pointer is associated with this record. In addition to that, a search key is usually present to serve as a proxy in the index file. An index file is basically pairs of search key and pointer combinations. So having a search key aims to expedite the searching and avoid the overhead. With the presence of the search keys, scientists have developed a wide array of efficient schemas to represent and organize all the search keys. Prominent examples include:
B+ tree: self-balanced tree such that the distance from the root to all leaf nodes is equal.B tree: Similar to B+ tree but it has record stored on non-leaf nodesExtensible hashing: a directory together with buckets, buckets store the hashing key computed by hash table or hash function.Linear hashing: Similar to extensible hashing without directory but multiple levels of hash functions.
B+ tree: self-balanced tree such that the distance from the root to all leaf nodes is equal.
B tree: Similar to B+ tree but it has record stored on non-leaf nodes
Extensible hashing: a directory together with buckets, buckets store the hashing key computed by hash table or hash function.
Linear hashing: Similar to extensible hashing without directory but multiple levels of hash functions.
Since it is not a technical blog, I would like to refer you to some wonderful youtube videos (link above) that explain what each indexing schema is and how they enable quick and efficient insertion and deletion. But the take-home message from this section is, data is laid out on disk in a well-designed manner that enables us to efficiently fetch and manipulates them.
First, I am hoping to instill a little bit of non-intuitive fact that a file is actually a stream of bits/bytes. When you read a file into memory, you are dealing with a series of 0/1s and you are hoping to load a specific portion of files correctly.
Now we have to use some low-level language like C:
# declare file pointerFile *fp;# initialize file pointer with a binary file stored on diskfp = fopen('./test_file.bin','r');# set the reading pointer from starting point (SEEK_SET) to 4 bits forward (offset = 4)fseek(fp,4,SEEK_SET);# declare a pointer to store the file in memoryph = (char) malloc(128);# read the file, read 128 bits to the pointer in memoryfread(ph,sizeof(char),128,fp)# free the memoryfree(ph)
As shown in the figure and the code snippet, fseek function has a built-in variable SEEK_SET which is the starting position of the file stream. We set offset=4 to instruct the function to read from the position that 4 bits ahead of the SEEK_SET . Then we declare a char pointer in memory, using fread function to specifically read into 128 bits of file stream into a specific memory space that we just defined. This is how reading from disk to memory actually works.
Also, make sure to allocate the memory space first by using malloc function in C. It is also important to release the memory space whenever you manually allocate the space before, using free function. Neglecting this step can cause a memory leakage problem which is caused by not-in-use memory that hasn’t been correctly released properly.
Like I said in the beginning, in most cases, the low-level realization is not our main concern as an applied programmer. However, I always think it is not an excuse to stop us from learning a bit about the underpinnings of the computer system. I hope you find this article interesting and useful, thanks for reading! If you like this article, follow me on medium, thank you so much for your support. Connect me on my Twitter or LinkedIn, also please let me know if you have any questions or what kind of tutorials you would like to see In the future! | [
{
"code": null,
"e": 663,
"s": 171,
"text": "I consider myself as an applied programmer, I use high-level programming languages like Python to manipulate the data frames, build simple pipelines to facilitate the data analysis of certain tasks. However, at the atomic level, the computer itself doesn’t understand what “pandas.read_csv()” means or what the “write.table()” function actually does. It makes me wonder about the intermediate steps involved in converting our commands to 0/1 binary bits and prompts me to write this article."
},
{
"code": null,
"e": 1109,
"s": 663,
"text": "In this article, I am hoping to give you a rough and intuitive image of what the disk actually looks like, how your data lays out on the disk, and what’s the information exchanges between your disk and memory. This is not meant to be a strictly technical blog but more like relaxing reading material. Being aware of the physical hardware structure can help us to get a better understanding of the tasks and problems we may encounter in our work:"
},
{
"code": null,
"e": 1172,
"s": 1109,
"text": "memory leakage? indexing file? memory overhead? I/O streaming?"
},
{
"code": null,
"e": 1218,
"s": 1172,
"text": "So brace up yourself and let’s get into that!"
},
{
"code": null,
"e": 1582,
"s": 1218,
"text": "When you are on your PC or Mac, you open the Computer or Finder, all the files that appear there are stored on the disk, sometime the disk is also referred to as storage. Nowadays, nearly most personal computers are using Solid State Disk (SSD), however, to convey some intuition, I am going to use Hard Disk (HD) to illustrate the physical structure of the disk."
},
{
"code": null,
"e": 1804,
"s": 1582,
"text": "The structure of a typical hard disk looks like a CD player, it has an arm that can rotate and changes to a selected track, the head of the arm is able to read, write or erase the data stored in each track of the surface."
},
{
"code": null,
"e": 2029,
"s": 1804,
"text": "The surface is also referred to as a platter, and a platter can be split into a set of physical units called a sector. There are gaps between each sector and several sectors constitute a block, the block is the logical unit."
},
{
"code": null,
"e": 2215,
"s": 2029,
"text": "If I tell you one track in a platter has a maximum capacity of 1024Kb (1Mb), then you know your Excel file, which let’s imagine is 2Mb, will occupy two platters to store it in the disk."
},
{
"code": null,
"e": 2547,
"s": 2215,
"text": "If the rotation speed is known, then you can easily compute how fast the files/bits can be transferred from the disk to memory or vice versus. It also becomes clear that why a large file needs more time to read because it needs longer time to rotate the arms and arms also take longer to read since the storage area will be bigger."
},
{
"code": null,
"e": 2845,
"s": 2547,
"text": "Solid State Disk (SSD) will have faster accessing time, and the architecture is quite different from the hard disk (HD) example that I showed you above. But hopefully, that can provide you a clear image that where your files lie on, and next I will show you how the data actually lies on the disk."
},
{
"code": null,
"e": 3193,
"s": 2845,
"text": "In a Database Management System (DBMS), each record (a record is basically a row in a data frame) lies on disk in some particular manner to speed up the search, insert, and deletion. Imagine if every record is scattered around the disk without any rules or organizations, there will be no way to perform the query, indexing, and any manipulations."
},
{
"code": null,
"e": 3551,
"s": 3193,
"text": "Simply speaking, you can store all the data in a row-wise manner, meaning to say that similar records/rows will be gathered together. In doing so, row-wise indexing can be very efficient with the cost of adding column operation or column-wise indexing can be relatively slow. If you go along the column-wise manner, things would become exactly the opposite."
},
{
"code": null,
"e": 4123,
"s": 3551,
"text": "Let’s imagine each row will be stored in a coalesced space on disk, as shown in the figure. The physical address or pointer is associated with this record. In addition to that, a search key is usually present to serve as a proxy in the index file. An index file is basically pairs of search key and pointer combinations. So having a search key aims to expedite the searching and avoid the overhead. With the presence of the search keys, scientists have developed a wide array of efficient schemas to represent and organize all the search keys. Prominent examples include:"
},
{
"code": null,
"e": 4512,
"s": 4123,
"text": "B+ tree: self-balanced tree such that the distance from the root to all leaf nodes is equal.B tree: Similar to B+ tree but it has record stored on non-leaf nodesExtensible hashing: a directory together with buckets, buckets store the hashing key computed by hash table or hash function.Linear hashing: Similar to extensible hashing without directory but multiple levels of hash functions."
},
{
"code": null,
"e": 4605,
"s": 4512,
"text": "B+ tree: self-balanced tree such that the distance from the root to all leaf nodes is equal."
},
{
"code": null,
"e": 4675,
"s": 4605,
"text": "B tree: Similar to B+ tree but it has record stored on non-leaf nodes"
},
{
"code": null,
"e": 4801,
"s": 4675,
"text": "Extensible hashing: a directory together with buckets, buckets store the hashing key computed by hash table or hash function."
},
{
"code": null,
"e": 4904,
"s": 4801,
"text": "Linear hashing: Similar to extensible hashing without directory but multiple levels of hash functions."
},
{
"code": null,
"e": 5274,
"s": 4904,
"text": "Since it is not a technical blog, I would like to refer you to some wonderful youtube videos (link above) that explain what each indexing schema is and how they enable quick and efficient insertion and deletion. But the take-home message from this section is, data is laid out on disk in a well-designed manner that enables us to efficiently fetch and manipulates them."
},
{
"code": null,
"e": 5525,
"s": 5274,
"text": "First, I am hoping to instill a little bit of non-intuitive fact that a file is actually a stream of bits/bytes. When you read a file into memory, you are dealing with a series of 0/1s and you are hoping to load a specific portion of files correctly."
},
{
"code": null,
"e": 5576,
"s": 5525,
"text": "Now we have to use some low-level language like C:"
},
{
"code": null,
"e": 5989,
"s": 5576,
"text": "# declare file pointerFile *fp;# initialize file pointer with a binary file stored on diskfp = fopen('./test_file.bin','r');# set the reading pointer from starting point (SEEK_SET) to 4 bits forward (offset = 4)fseek(fp,4,SEEK_SET);# declare a pointer to store the file in memoryph = (char) malloc(128);# read the file, read 128 bits to the pointer in memoryfread(ph,sizeof(char),128,fp)# free the memoryfree(ph)"
},
{
"code": null,
"e": 6456,
"s": 5989,
"text": "As shown in the figure and the code snippet, fseek function has a built-in variable SEEK_SET which is the starting position of the file stream. We set offset=4 to instruct the function to read from the position that 4 bits ahead of the SEEK_SET . Then we declare a char pointer in memory, using fread function to specifically read into 128 bits of file stream into a specific memory space that we just defined. This is how reading from disk to memory actually works."
},
{
"code": null,
"e": 6796,
"s": 6456,
"text": "Also, make sure to allocate the memory space first by using malloc function in C. It is also important to release the memory space whenever you manually allocate the space before, using free function. Neglecting this step can cause a memory leakage problem which is caused by not-in-use memory that hasn’t been correctly released properly."
}
] |
Function Annotations in Python | Function annotations introduced in Python 3.0 adds a feature that allows you to add arbitrary metadata to function parameters and return value. Since python 3, function annotations have been officially added to python (PEP-3107). The primary purpose was to have a standard way to link metadata to function parameters and return value.
Let’s understand some basics of function annotations −
Function annotations are completely optional both for parameters and return value.
Function annotations are completely optional both for parameters and return value.
Function annotations provide a way of associating various parts of a function with arbitrary python expressions at compile time.
Function annotations provide a way of associating various parts of a function with arbitrary python expressions at compile time.
The PEP-3107 makes no attempt to introduce any kind of standard semantics, even for the built-in types. All this work left to the third-party libraries.
The PEP-3107 makes no attempt to introduce any kind of standard semantics, even for the built-in types. All this work left to the third-party libraries.
Annotations of simple parameters
The annotations for parameters take the following form −
def foo(x: expression, y: expression = 20):
....
Whereas the annotations for excess parameters are as −
def foo(**args: expression, **kwargs: expression):
.....
In the case of nested parameters, annotations always follow the name of the parameters and not till the last parenthesis. It is not required to annotate all the parameters of a nested parameter.
def foo(x1, y1: expression), (x2: expression, y2: expression)=(None, None)):
......
It’s important to understand that python doesn’t provide any semantics with annotations. It only provides nice syntactic support for associating metadata as well as an easy way to access it. Also, annotations are not mandatory.
>>> def func(x:'annotating x', y: 'annotating y', z: int) -> float: print(x + y + z)
In the above example, function func() takes three parameters called x,y and z, finally prints their sum. The first argument x is annotated with string ‘annotating x’, second argument y is annotated with the string ‘annotating y’, and the third argument z is annotated with type int. The return value is annotated with the type float. Here the ‘->’ syntax for annotating the return value.
>>> func(2,3,-4)
1
>>> func('Function','-','Annotation')
Function-Annotation
Above we call func() twice, once with int arguments and once with string arguments. In both cases, func() does the right thing and annotations are simply ignored. So, we see the annotations have no effect on the execution of the function func().
All the annotations are stored in a dictionary called __annotations__, which itself is an attribute of the function −
>>> def func(x:'annotating x', y: 'annotating y', z: int) -> float: print(x + y + z)
>>> func.__annotations__
{'x': 'annotating x', 'y': 'annotating y', 'z': <class 'int'>, 'return': <class 'float'>}
As we can see in the preceding code example, annotations are not typed declarations, though they could certainly be used for that purpose and they resemble the typing syntax used in some other languages, as shown below −
>>> def func(a: 'python', b: {'category: ' 'language'}) -> 'yep':
pass
>>> func.__annotations__
{'a': 'python', 'b': {'category: language'}, 'return': 'yep'}
>>>
They are arbitrary expressions, which means that arbitrary values can be stored in the __annotations__ dictionary. Although, they don’t add much significance to the python itself, except that it should store the values. That said, defining the parameter and return types is a common use of function annotations.
If you find yourselves using a tool that assumes annotations are type declarations but you want to use them for some other purpose, use the standard @no_type_check decorator to exempt your function from such processing, as shown here −
>>> from typing import no_type_check
>>> @no_type_check
def func(a: 'python', b: {'category: ' 'language'}) -> 'yep':
pass
>>>
Normally, this isn’t required as most tools that use annotations have a way of recognizing the ones meant for them. The decorator is for protecting corner cases where things are ambiguous.
Annotations combine well with decorators because annotation values make a good way to provide input to a decorator, and decorator-generated wrappers are a good place to put code that gives meaning to annotations.
from functools import wraps
def adapted(func):
@wraps(func)
def wrapper(**kwargs):
final_args = {}
for name, value in kwargs. items():
adapt = func.__annotations__.get(name)
if adapt is not None:
final_args[name] = adapt(value)
else:
final_args[name] = value
result = func(**final_args)
adapt = func.__annotations__.get('result')
if adapt is not None:
return adapt(result)
return result
return wrapper
@adapted
def func(a: int, b: repr) -> str:
return a
So, the adapted decorator encloses the function in a wrapper. This wrapper only accepts keyword arguments, which means that even, if the original function could accept positional arguments, they have to be specified by name.
Once the function is wrapped, wrapper also looks for adapters in the function's parameter annotations and applies them before passing the arguments to the real function.
Once the function returns, the wrapper checks for a return value adapter; if it finds one, it applies it to the return value before finally returning it.
When we consider the implications of what's happening here, they're pretty impressive. We've actually modified what it means to pass a parameter to a function or return a value.
Sometimes, one or more of a method's parameters don't require any processing, except assigning them to an attribute of self. Can we use decorators and annotations to make this happen automatically? Of course, we can.
from functools import wraps
def store_args(func):
@wraps(func)
def wrapper(self, **kwargs):
for name, value in kwargs.items():
attrib = func.__annotations__.get(name)
if attrib is True:
attrib = name
if isinstance(attrib, str):
setattr(self, attrib, value)
return func(self, **kwargs)
return wrapper
class A:
@store_args
def __init__(self, first: True, second: 'example'):
pass
a = A(first = 5, second = 6)
assert a.first == 5
assert a.example == 6 | [
{
"code": null,
"e": 1397,
"s": 1062,
"text": "Function annotations introduced in Python 3.0 adds a feature that allows you to add arbitrary metadata to function parameters and return value. Since python 3, function annotations have been officially added to python (PEP-3107). The primary purpose was to have a standard way to link metadata to function parameters and return value."
},
{
"code": null,
"e": 1452,
"s": 1397,
"text": "Let’s understand some basics of function annotations −"
},
{
"code": null,
"e": 1535,
"s": 1452,
"text": "Function annotations are completely optional both for parameters and return value."
},
{
"code": null,
"e": 1618,
"s": 1535,
"text": "Function annotations are completely optional both for parameters and return value."
},
{
"code": null,
"e": 1747,
"s": 1618,
"text": "Function annotations provide a way of associating various parts of a function with arbitrary python expressions at compile time."
},
{
"code": null,
"e": 1876,
"s": 1747,
"text": "Function annotations provide a way of associating various parts of a function with arbitrary python expressions at compile time."
},
{
"code": null,
"e": 2029,
"s": 1876,
"text": "The PEP-3107 makes no attempt to introduce any kind of standard semantics, even for the built-in types. All this work left to the third-party libraries."
},
{
"code": null,
"e": 2182,
"s": 2029,
"text": "The PEP-3107 makes no attempt to introduce any kind of standard semantics, even for the built-in types. All this work left to the third-party libraries."
},
{
"code": null,
"e": 2215,
"s": 2182,
"text": "Annotations of simple parameters"
},
{
"code": null,
"e": 2272,
"s": 2215,
"text": "The annotations for parameters take the following form −"
},
{
"code": null,
"e": 2324,
"s": 2272,
"text": "def foo(x: expression, y: expression = 20):\n ...."
},
{
"code": null,
"e": 2379,
"s": 2324,
"text": "Whereas the annotations for excess parameters are as −"
},
{
"code": null,
"e": 2439,
"s": 2379,
"text": "def foo(**args: expression, **kwargs: expression):\n ....."
},
{
"code": null,
"e": 2634,
"s": 2439,
"text": "In the case of nested parameters, annotations always follow the name of the parameters and not till the last parenthesis. It is not required to annotate all the parameters of a nested parameter."
},
{
"code": null,
"e": 2721,
"s": 2634,
"text": "def foo(x1, y1: expression), (x2: expression, y2: expression)=(None, None)):\n ......"
},
{
"code": null,
"e": 2949,
"s": 2721,
"text": "It’s important to understand that python doesn’t provide any semantics with annotations. It only provides nice syntactic support for associating metadata as well as an easy way to access it. Also, annotations are not mandatory."
},
{
"code": null,
"e": 3034,
"s": 2949,
"text": ">>> def func(x:'annotating x', y: 'annotating y', z: int) -> float: print(x + y + z)"
},
{
"code": null,
"e": 3422,
"s": 3034,
"text": "In the above example, function func() takes three parameters called x,y and z, finally prints their sum. The first argument x is annotated with string ‘annotating x’, second argument y is annotated with the string ‘annotating y’, and the third argument z is annotated with type int. The return value is annotated with the type float. Here the ‘->’ syntax for annotating the return value."
},
{
"code": null,
"e": 3499,
"s": 3422,
"text": ">>> func(2,3,-4)\n1\n>>> func('Function','-','Annotation')\nFunction-Annotation"
},
{
"code": null,
"e": 3745,
"s": 3499,
"text": "Above we call func() twice, once with int arguments and once with string arguments. In both cases, func() does the right thing and annotations are simply ignored. So, we see the annotations have no effect on the execution of the function func()."
},
{
"code": null,
"e": 3863,
"s": 3745,
"text": "All the annotations are stored in a dictionary called __annotations__, which itself is an attribute of the function −"
},
{
"code": null,
"e": 4063,
"s": 3863,
"text": ">>> def func(x:'annotating x', y: 'annotating y', z: int) -> float: print(x + y + z)\n>>> func.__annotations__\n{'x': 'annotating x', 'y': 'annotating y', 'z': <class 'int'>, 'return': <class 'float'>}"
},
{
"code": null,
"e": 4284,
"s": 4063,
"text": "As we can see in the preceding code example, annotations are not typed declarations, though they could certainly be used for that purpose and they resemble the typing syntax used in some other languages, as shown below −"
},
{
"code": null,
"e": 4449,
"s": 4284,
"text": ">>> def func(a: 'python', b: {'category: ' 'language'}) -> 'yep':\n pass\n>>> func.__annotations__\n{'a': 'python', 'b': {'category: language'}, 'return': 'yep'}\n>>>"
},
{
"code": null,
"e": 4761,
"s": 4449,
"text": "They are arbitrary expressions, which means that arbitrary values can be stored in the __annotations__ dictionary. Although, they don’t add much significance to the python itself, except that it should store the values. That said, defining the parameter and return types is a common use of function annotations."
},
{
"code": null,
"e": 4997,
"s": 4761,
"text": "If you find yourselves using a tool that assumes annotations are type declarations but you want to use them for some other purpose, use the standard @no_type_check decorator to exempt your function from such processing, as shown here −"
},
{
"code": null,
"e": 5127,
"s": 4997,
"text": ">>> from typing import no_type_check\n>>> @no_type_check\ndef func(a: 'python', b: {'category: ' 'language'}) -> 'yep':\n pass\n>>>"
},
{
"code": null,
"e": 5316,
"s": 5127,
"text": "Normally, this isn’t required as most tools that use annotations have a way of recognizing the ones meant for them. The decorator is for protecting corner cases where things are ambiguous."
},
{
"code": null,
"e": 5529,
"s": 5316,
"text": "Annotations combine well with decorators because annotation values make a good way to provide input to a decorator, and decorator-generated wrappers are a good place to put code that gives meaning to annotations."
},
{
"code": null,
"e": 6046,
"s": 5529,
"text": "from functools import wraps\ndef adapted(func):\n @wraps(func)\n def wrapper(**kwargs):\n final_args = {}\n for name, value in kwargs. items():\n adapt = func.__annotations__.get(name)\n if adapt is not None:\n final_args[name] = adapt(value)\n else:\n final_args[name] = value\n result = func(**final_args)\n adapt = func.__annotations__.get('result')\n if adapt is not None:\n return adapt(result)\n return result\nreturn wrapper\n@adapted\ndef func(a: int, b: repr) -> str:\nreturn a"
},
{
"code": null,
"e": 6271,
"s": 6046,
"text": "So, the adapted decorator encloses the function in a wrapper. This wrapper only accepts keyword arguments, which means that even, if the original function could accept positional arguments, they have to be specified by name."
},
{
"code": null,
"e": 6441,
"s": 6271,
"text": "Once the function is wrapped, wrapper also looks for adapters in the function's parameter annotations and applies them before passing the arguments to the real function."
},
{
"code": null,
"e": 6595,
"s": 6441,
"text": "Once the function returns, the wrapper checks for a return value adapter; if it finds one, it applies it to the return value before finally returning it."
},
{
"code": null,
"e": 6773,
"s": 6595,
"text": "When we consider the implications of what's happening here, they're pretty impressive. We've actually modified what it means to pass a parameter to a function or return a value."
},
{
"code": null,
"e": 6990,
"s": 6773,
"text": "Sometimes, one or more of a method's parameters don't require any processing, except assigning them to an attribute of self. Can we use decorators and annotations to make this happen automatically? Of course, we can."
},
{
"code": null,
"e": 7493,
"s": 6990,
"text": "from functools import wraps\ndef store_args(func):\n @wraps(func)\n def wrapper(self, **kwargs):\n for name, value in kwargs.items():\n attrib = func.__annotations__.get(name)\n if attrib is True:\n attrib = name\n if isinstance(attrib, str):\n setattr(self, attrib, value)\n return func(self, **kwargs)\n return wrapper\nclass A:\n@store_args\ndef __init__(self, first: True, second: 'example'):\npass\na = A(first = 5, second = 6)\nassert a.first == 5\nassert a.example == 6"
}
] |
Increase the thickness of a line with Matplotlib - GeeksforGeeks | 26 Dec, 2020
Prerequisites: Matplotlib
Matplotlib is the most widely used library for plotting graphs with the available dataset. Matplotlib supports line chart which are used to represent data over a continuous time span. In line chart, the data value is plotted as points and later connected by a line to show trend of a measure over time. The functionality of increasing the thickness of a line is given by linewidth attribute.
Linewidth: By default the linewidth is 1. For graphs with multiple lines it becomes difficult to trace the lines with lighter colors. This situation can be handled by increasing the linewidth. The linewidth can be used to focus on certain data compared to the others. It can help get a detailed visualization of the particular record in the dataset. This attribute belongs to plot function().
Import modules
Create or load data
Plot graph with required line thickness
Display plot
xlabel()- This function is used to set labels for x-axis
Syntax: plt.xlabel(xlabel, fontdict=None, labelpad=None, **kwargs)
Parameter:
xlabel: accepts string type value and is used to label the X axis.
fontdict: used to override default font properties of the label. Its default value is None and is optional.
labelpad: default value is None. It is used to specify the spacing of the label from the axes. This is optional.
**kwargs: used to specify other properties that can be used to modify the appearance of the label.
ylabel()- this function is used to set labels for y-axis
Syntax: plt.ylabel(ylabel, fontdict=None, labelpad=None, **kwargs)
Parameter:
ylabel: accepts string type value and is used to label the Y axis.
fontdict: used to override default font properties of the label. Its default value is None and is optional.
labelpad: default value is None. It is used to specify the spacing of the label from the axes. This is optional.
**kwargs: used to specify other properties that can be used to modify the appearance of the label.
plot()- It is used to make a 2D hexagonal binning plot of points x, y.
Syntax: plt.plot(x,y, data=None, **kwargs)
Parameter
x,y : used to specify the data to be plotted along the x and y axis.
data: default value is None. It is an object with labelled data and can be passed instead of the x,y values. If data object is passed then the xand y label should be specified.
**kwargs: used to specify line properties like linewidth, color, antialiasing, marker, markercolor etc.
legend()- A legend is an area describing the elements of the graph. In the matplotlib library, there’s a function called legend() which is used to Place a legend on the axes.
Syntax: plt.legend(**options)
Parameter
**options: used to specify the properties of the legend, its size, its location, edgecolor, facecolor etc
Example 1:
Python3
import matplotlib.pyplot as plt places = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]literacy_rate = [100, 98, 90, 85, 75, 50, 30, 45, 65, 70]female_literacy = [95, 100, 50, 60, 85, 80, 75, 99, 70, 30] plt.xlabel("Places")plt.ylabel("Percentage") plt.plot(places, literacy_rate, color='blue', linewidth=6, label="Literacy rate") plt.plot(places, female_literacy, color='fuchsia', linewidth=4, label="Female Literacy rate") plt.legend(loc='lower left', ncol=1)
Output
Example 2:
Python3
import matplotlib.pyplot as plt age = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]cardiac_cases = [5, 15, 20, 40, 55, 55, 70, 80, 90, 95]survival_chances = [99, 99, 90, 90, 80, 75, 60, 50, 30, 25] plt.xlabel("Age")plt.ylabel("Percentage") plt.plot(age, cardiac_cases, color='black', linewidth=2, label="Cardiac Cases", marker='o', markerfacecolor='red', markersize=12) plt.plot(age, survival_chances, color='yellow', linewidth=3, label="Survival Chances", marker='o', markerfacecolor='green', markersize=12) plt.legend(loc='lower right', ncol=1)
Output
Picked
Python-matplotlib
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
How to Install PIP on Windows ?
Read a file line by line in Python
Enumerate() in Python
Iterate over a list in Python | [
{
"code": null,
"e": 30222,
"s": 30194,
"text": "\n26 Dec, 2020"
},
{
"code": null,
"e": 30248,
"s": 30222,
"text": "Prerequisites: Matplotlib"
},
{
"code": null,
"e": 30640,
"s": 30248,
"text": "Matplotlib is the most widely used library for plotting graphs with the available dataset. Matplotlib supports line chart which are used to represent data over a continuous time span. In line chart, the data value is plotted as points and later connected by a line to show trend of a measure over time. The functionality of increasing the thickness of a line is given by linewidth attribute."
},
{
"code": null,
"e": 31033,
"s": 30640,
"text": "Linewidth: By default the linewidth is 1. For graphs with multiple lines it becomes difficult to trace the lines with lighter colors. This situation can be handled by increasing the linewidth. The linewidth can be used to focus on certain data compared to the others. It can help get a detailed visualization of the particular record in the dataset. This attribute belongs to plot function()."
},
{
"code": null,
"e": 31048,
"s": 31033,
"text": "Import modules"
},
{
"code": null,
"e": 31068,
"s": 31048,
"text": "Create or load data"
},
{
"code": null,
"e": 31108,
"s": 31068,
"text": "Plot graph with required line thickness"
},
{
"code": null,
"e": 31121,
"s": 31108,
"text": "Display plot"
},
{
"code": null,
"e": 31178,
"s": 31121,
"text": "xlabel()- This function is used to set labels for x-axis"
},
{
"code": null,
"e": 31245,
"s": 31178,
"text": "Syntax: plt.xlabel(xlabel, fontdict=None, labelpad=None, **kwargs)"
},
{
"code": null,
"e": 31256,
"s": 31245,
"text": "Parameter:"
},
{
"code": null,
"e": 31323,
"s": 31256,
"text": "xlabel: accepts string type value and is used to label the X axis."
},
{
"code": null,
"e": 31431,
"s": 31323,
"text": "fontdict: used to override default font properties of the label. Its default value is None and is optional."
},
{
"code": null,
"e": 31544,
"s": 31431,
"text": "labelpad: default value is None. It is used to specify the spacing of the label from the axes. This is optional."
},
{
"code": null,
"e": 31643,
"s": 31544,
"text": "**kwargs: used to specify other properties that can be used to modify the appearance of the label."
},
{
"code": null,
"e": 31700,
"s": 31643,
"text": "ylabel()- this function is used to set labels for y-axis"
},
{
"code": null,
"e": 31767,
"s": 31700,
"text": "Syntax: plt.ylabel(ylabel, fontdict=None, labelpad=None, **kwargs)"
},
{
"code": null,
"e": 31778,
"s": 31767,
"text": "Parameter:"
},
{
"code": null,
"e": 31845,
"s": 31778,
"text": "ylabel: accepts string type value and is used to label the Y axis."
},
{
"code": null,
"e": 31953,
"s": 31845,
"text": "fontdict: used to override default font properties of the label. Its default value is None and is optional."
},
{
"code": null,
"e": 32066,
"s": 31953,
"text": "labelpad: default value is None. It is used to specify the spacing of the label from the axes. This is optional."
},
{
"code": null,
"e": 32165,
"s": 32066,
"text": "**kwargs: used to specify other properties that can be used to modify the appearance of the label."
},
{
"code": null,
"e": 32236,
"s": 32165,
"text": "plot()- It is used to make a 2D hexagonal binning plot of points x, y."
},
{
"code": null,
"e": 32279,
"s": 32236,
"text": "Syntax: plt.plot(x,y, data=None, **kwargs)"
},
{
"code": null,
"e": 32289,
"s": 32279,
"text": "Parameter"
},
{
"code": null,
"e": 32358,
"s": 32289,
"text": "x,y : used to specify the data to be plotted along the x and y axis."
},
{
"code": null,
"e": 32535,
"s": 32358,
"text": "data: default value is None. It is an object with labelled data and can be passed instead of the x,y values. If data object is passed then the xand y label should be specified."
},
{
"code": null,
"e": 32639,
"s": 32535,
"text": "**kwargs: used to specify line properties like linewidth, color, antialiasing, marker, markercolor etc."
},
{
"code": null,
"e": 32814,
"s": 32639,
"text": "legend()- A legend is an area describing the elements of the graph. In the matplotlib library, there’s a function called legend() which is used to Place a legend on the axes."
},
{
"code": null,
"e": 32844,
"s": 32814,
"text": "Syntax: plt.legend(**options)"
},
{
"code": null,
"e": 32854,
"s": 32844,
"text": "Parameter"
},
{
"code": null,
"e": 32960,
"s": 32854,
"text": "**options: used to specify the properties of the legend, its size, its location, edgecolor, facecolor etc"
},
{
"code": null,
"e": 32971,
"s": 32960,
"text": "Example 1:"
},
{
"code": null,
"e": 32979,
"s": 32971,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as plt places = [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\"]literacy_rate = [100, 98, 90, 85, 75, 50, 30, 45, 65, 70]female_literacy = [95, 100, 50, 60, 85, 80, 75, 99, 70, 30] plt.xlabel(\"Places\")plt.ylabel(\"Percentage\") plt.plot(places, literacy_rate, color='blue', linewidth=6, label=\"Literacy rate\") plt.plot(places, female_literacy, color='fuchsia', linewidth=4, label=\"Female Literacy rate\") plt.legend(loc='lower left', ncol=1)",
"e": 33466,
"s": 32979,
"text": null
},
{
"code": null,
"e": 33473,
"s": 33466,
"text": "Output"
},
{
"code": null,
"e": 33484,
"s": 33473,
"text": "Example 2:"
},
{
"code": null,
"e": 33492,
"s": 33484,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as plt age = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]cardiac_cases = [5, 15, 20, 40, 55, 55, 70, 80, 90, 95]survival_chances = [99, 99, 90, 90, 80, 75, 60, 50, 30, 25] plt.xlabel(\"Age\")plt.ylabel(\"Percentage\") plt.plot(age, cardiac_cases, color='black', linewidth=2, label=\"Cardiac Cases\", marker='o', markerfacecolor='red', markersize=12) plt.plot(age, survival_chances, color='yellow', linewidth=3, label=\"Survival Chances\", marker='o', markerfacecolor='green', markersize=12) plt.legend(loc='lower right', ncol=1)",
"e": 34056,
"s": 33492,
"text": null
},
{
"code": null,
"e": 34063,
"s": 34056,
"text": "Output"
},
{
"code": null,
"e": 34070,
"s": 34063,
"text": "Picked"
},
{
"code": null,
"e": 34088,
"s": 34070,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 34112,
"s": 34088,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 34119,
"s": 34112,
"text": "Python"
},
{
"code": null,
"e": 34138,
"s": 34119,
"text": "Technical Scripter"
},
{
"code": null,
"e": 34236,
"s": 34138,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34245,
"s": 34236,
"text": "Comments"
},
{
"code": null,
"e": 34258,
"s": 34245,
"text": "Old Comments"
},
{
"code": null,
"e": 34286,
"s": 34258,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 34336,
"s": 34286,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 34358,
"s": 34336,
"text": "Python map() function"
},
{
"code": null,
"e": 34402,
"s": 34358,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 34420,
"s": 34402,
"text": "Python Dictionary"
},
{
"code": null,
"e": 34443,
"s": 34420,
"text": "Taking input in Python"
},
{
"code": null,
"e": 34475,
"s": 34443,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 34510,
"s": 34475,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 34532,
"s": 34510,
"text": "Enumerate() in Python"
}
] |
Java program to count total bits in a number | The total bits in a number can be counted by using its binary representation. An example of this is given as follows −
Number = 9
Binary representation = 1001
Total bits = 4
A program that demonstrates this is given as follows.
Live Demo
public class Example {
public static void main(String[] arg) {
int num = 10;
int n = num;
int count = 0;
while (num != 0) {
count++;
num >>= 1;
}
System.out.print("The total bits in " + n + " are " + count);
}
}
The total bits in 10 are 4
Now let us understand the above program.
First, the number is defined. Then the total bits in the number are stored in count. This is done by using the right shift operator in a while loop. Finally, the total bits are displayed. The code snippet that demonstrates this is given as follows −
int num = 10;
int n = num;
int count = 0;
while (num != 0) {
count++;
num >>= 1;
}
System.out.print("The total bits in " + n + " are " + count); | [
{
"code": null,
"e": 1181,
"s": 1062,
"text": "The total bits in a number can be counted by using its binary representation. An example of this is given as follows −"
},
{
"code": null,
"e": 1237,
"s": 1181,
"text": "Number = 9\nBinary representation = 1001\nTotal bits = 4\n"
},
{
"code": null,
"e": 1291,
"s": 1237,
"text": "A program that demonstrates this is given as follows."
},
{
"code": null,
"e": 1302,
"s": 1291,
"text": " Live Demo"
},
{
"code": null,
"e": 1575,
"s": 1302,
"text": "public class Example {\n public static void main(String[] arg) {\n int num = 10;\n int n = num;\n int count = 0;\n while (num != 0) {\n count++;\n num >>= 1;\n } \n System.out.print(\"The total bits in \" + n + \" are \" + count);\n }\n}"
},
{
"code": null,
"e": 1603,
"s": 1575,
"text": "The total bits in 10 are 4\n"
},
{
"code": null,
"e": 1644,
"s": 1603,
"text": "Now let us understand the above program."
},
{
"code": null,
"e": 1894,
"s": 1644,
"text": "First, the number is defined. Then the total bits in the number are stored in count. This is done by using the right shift operator in a while loop. Finally, the total bits are displayed. The code snippet that demonstrates this is given as follows −"
},
{
"code": null,
"e": 2046,
"s": 1894,
"text": "int num = 10;\nint n = num;\nint count = 0;\nwhile (num != 0) {\n count++;\n num >>= 1;\n}\nSystem.out.print(\"The total bits in \" + n + \" are \" + count);\n"
}
] |
Clojure - Maps | A Map is a collection that maps keys to values. Two different map types are provided - hashed and sorted. HashMaps require keys that correctly support hashCode and equals. SortedMaps require keys that implement Comparable, or an instance of Comparator.
A map can be created in two ways, the first is via the hash-map method.
HashMaps have a typical key value relationship and is created by using hash-map function.
(ns clojure.examples.example
(:gen-class))
(defn example []
(def demokeys (hash-map "z" "1" "b" "2" "a" "3"))
(println demokeys))
(example)
The above code produces the following output.
{z 1, b 2, a 3}
SortedMaps have the unique characteristic of sorting their elements based on the key element. Following is an example that shows how the sorted map can be created using the sorted-map function.
(ns clojure.examples.example
(:gen-class))
(defn example []
(def demokeys (sorted-map "z" "1" "b" "2" "a" "3"))
(println demokeys))
(example)
The above code produces the following output.
{a 3, b 2, z 1}
From the above program you can clearly see that elements in the maps are sorted as per the key value. Following are the methods available for maps.
Returns the value mapped to key, not-found or nil if key is not present.
See whether the map contains a required key.
Returns the map entry for the key.
Returns the list of keys in the map.
Returns the list of values in the map.
Dissociates a key value entry from the map.
Merges two maps entries into one single map entry.
Returns a map that consists of the rest of the maps conj-ed onto the first.
Returns a map containing only those entries in map whose key is in keys.
Renames keys in the current HashMap to the newly defined ones.
Inverts the maps so that the values become the keys and vice versa.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2627,
"s": 2374,
"text": "A Map is a collection that maps keys to values. Two different map types are provided - hashed and sorted. HashMaps require keys that correctly support hashCode and equals. SortedMaps require keys that implement Comparable, or an instance of Comparator."
},
{
"code": null,
"e": 2699,
"s": 2627,
"text": "A map can be created in two ways, the first is via the hash-map method."
},
{
"code": null,
"e": 2789,
"s": 2699,
"text": "HashMaps have a typical key value relationship and is created by using hash-map function."
},
{
"code": null,
"e": 2938,
"s": 2789,
"text": "(ns clojure.examples.example\n (:gen-class))\n(defn example []\n (def demokeys (hash-map \"z\" \"1\" \"b\" \"2\" \"a\" \"3\"))\n (println demokeys))\n(example)"
},
{
"code": null,
"e": 2984,
"s": 2938,
"text": "The above code produces the following output."
},
{
"code": null,
"e": 3001,
"s": 2984,
"text": "{z 1, b 2, a 3}\n"
},
{
"code": null,
"e": 3195,
"s": 3001,
"text": "SortedMaps have the unique characteristic of sorting their elements based on the key element. Following is an example that shows how the sorted map can be created using the sorted-map function."
},
{
"code": null,
"e": 3346,
"s": 3195,
"text": "(ns clojure.examples.example\n (:gen-class))\n(defn example []\n (def demokeys (sorted-map \"z\" \"1\" \"b\" \"2\" \"a\" \"3\"))\n (println demokeys))\n(example)"
},
{
"code": null,
"e": 3392,
"s": 3346,
"text": "The above code produces the following output."
},
{
"code": null,
"e": 3409,
"s": 3392,
"text": "{a 3, b 2, z 1}\n"
},
{
"code": null,
"e": 3557,
"s": 3409,
"text": "From the above program you can clearly see that elements in the maps are sorted as per the key value. Following are the methods available for maps."
},
{
"code": null,
"e": 3630,
"s": 3557,
"text": "Returns the value mapped to key, not-found or nil if key is not present."
},
{
"code": null,
"e": 3675,
"s": 3630,
"text": "See whether the map contains a required key."
},
{
"code": null,
"e": 3710,
"s": 3675,
"text": "Returns the map entry for the key."
},
{
"code": null,
"e": 3747,
"s": 3710,
"text": "Returns the list of keys in the map."
},
{
"code": null,
"e": 3786,
"s": 3747,
"text": "Returns the list of values in the map."
},
{
"code": null,
"e": 3830,
"s": 3786,
"text": "Dissociates a key value entry from the map."
},
{
"code": null,
"e": 3881,
"s": 3830,
"text": "Merges two maps entries into one single map entry."
},
{
"code": null,
"e": 3957,
"s": 3881,
"text": "Returns a map that consists of the rest of the maps conj-ed onto the first."
},
{
"code": null,
"e": 4030,
"s": 3957,
"text": "Returns a map containing only those entries in map whose key is in keys."
},
{
"code": null,
"e": 4093,
"s": 4030,
"text": "Renames keys in the current HashMap to the newly defined ones."
},
{
"code": null,
"e": 4161,
"s": 4093,
"text": "Inverts the maps so that the values become the keys and vice versa."
},
{
"code": null,
"e": 4168,
"s": 4161,
"text": " Print"
},
{
"code": null,
"e": 4179,
"s": 4168,
"text": " Add Notes"
}
] |
TensorFlow - Keras | Keras is compact, easy to learn, high-level Python library run on top of TensorFlow framework. It is made with focus of understanding deep learning techniques, such as creating layers for neural networks maintaining the concepts of shapes and mathematical details. The creation of freamework can be of the following two types −
Sequential API
Functional API
Consider the following eight steps to create deep learning model in Keras −
Loading the data
Preprocess the loaded data
Definition of model
Compiling the model
Fit the specified model
Evaluate it
Make the required predictions
Save the model
We will use the Jupyter Notebook for execution and display of output as shown below −
Step 1 − Loading the data and preprocessing the loaded data is implemented first to execute the deep learning model.
import warnings
warnings.filterwarnings('ignore')
import numpy as np
np.random.seed(123) # for reproducibility
from keras.models import Sequential
from keras.layers import Flatten, MaxPool2D, Conv2D, Dense, Reshape, Dropout
from keras.utils import np_utils
Using TensorFlow backend.
from keras.datasets import mnist
# Load pre-shuffled MNIST data into train and test sets
(X_train, y_train), (X_test, y_test) = mnist.load_data()
X_train = X_train.reshape(X_train.shape[0], 28, 28, 1)
X_test = X_test.reshape(X_test.shape[0], 28, 28, 1)
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train /= 255
X_test /= 255
Y_train = np_utils.to_categorical(y_train, 10)
Y_test = np_utils.to_categorical(y_test, 10)
This step can be defined as “Import libraries and Modules” which means all the libraries and modules are imported as an initial step.
Step 2 − In this step, we will define the model architecture −
model = Sequential()
model.add(Conv2D(32, 3, 3, activation = 'relu', input_shape = (28,28,1)))
model.add(Conv2D(32, 3, 3, activation = 'relu'))
model.add(MaxPool2D(pool_size = (2,2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation = 'relu'))
model.add(Dropout(0.5))
model.add(Dense(10, activation = 'softmax'))
Step 3 − Let us now compile the specified model −
model.compile(loss = 'categorical_crossentropy', optimizer = 'adam', metrics = ['accuracy'])
Step 4 − We will now fit the model using training data −
model.fit(X_train, Y_train, batch_size = 32, epochs = 10, verbose = 1)
The output of iterations created is as follows −
Epoch 1/10 60000/60000 [==============================] - 65s -
loss: 0.2124 -
acc: 0.9345
Epoch 2/10 60000/60000 [==============================] - 62s -
loss: 0.0893 -
acc: 0.9740
Epoch 3/10 60000/60000 [==============================] - 58s -
loss: 0.0665 -
acc: 0.9802
Epoch 4/10 60000/60000 [==============================] - 62s -
loss: 0.0571 -
acc: 0.9830
Epoch 5/10 60000/60000 [==============================] - 62s -
loss: 0.0474 -
acc: 0.9855
Epoch 6/10 60000/60000 [==============================] - 59s -
loss: 0.0416 -
acc: 0.9871
Epoch 7/10 60000/60000 [==============================] - 61s -
loss: 0.0380 -
acc: 0.9877
Epoch 8/10 60000/60000 [==============================] - 63s -
loss: 0.0333 -
acc: 0.9895
Epoch 9/10 60000/60000 [==============================] - 64s -
loss: 0.0325 -
acc: 0.9898
Epoch 10/10 60000/60000 [==============================] - 60s -
loss: 0.0284 - | [
{
"code": null,
"e": 2777,
"s": 2449,
"text": "Keras is compact, easy to learn, high-level Python library run on top of TensorFlow framework. It is made with focus of understanding deep learning techniques, such as creating layers for neural networks maintaining the concepts of shapes and mathematical details. The creation of freamework can be of the following two types −"
},
{
"code": null,
"e": 2792,
"s": 2777,
"text": "Sequential API"
},
{
"code": null,
"e": 2807,
"s": 2792,
"text": "Functional API"
},
{
"code": null,
"e": 2883,
"s": 2807,
"text": "Consider the following eight steps to create deep learning model in Keras −"
},
{
"code": null,
"e": 2900,
"s": 2883,
"text": "Loading the data"
},
{
"code": null,
"e": 2927,
"s": 2900,
"text": "Preprocess the loaded data"
},
{
"code": null,
"e": 2947,
"s": 2927,
"text": "Definition of model"
},
{
"code": null,
"e": 2967,
"s": 2947,
"text": "Compiling the model"
},
{
"code": null,
"e": 2991,
"s": 2967,
"text": "Fit the specified model"
},
{
"code": null,
"e": 3003,
"s": 2991,
"text": "Evaluate it"
},
{
"code": null,
"e": 3033,
"s": 3003,
"text": "Make the required predictions"
},
{
"code": null,
"e": 3048,
"s": 3033,
"text": "Save the model"
},
{
"code": null,
"e": 3134,
"s": 3048,
"text": "We will use the Jupyter Notebook for execution and display of output as shown below −"
},
{
"code": null,
"e": 3251,
"s": 3134,
"text": "Step 1 − Loading the data and preprocessing the loaded data is implemented first to execute the deep learning model."
},
{
"code": null,
"e": 3981,
"s": 3251,
"text": "import warnings\nwarnings.filterwarnings('ignore')\n\nimport numpy as np\nnp.random.seed(123) # for reproducibility\n\nfrom keras.models import Sequential\nfrom keras.layers import Flatten, MaxPool2D, Conv2D, Dense, Reshape, Dropout\nfrom keras.utils import np_utils\nUsing TensorFlow backend.\nfrom keras.datasets import mnist\n\n# Load pre-shuffled MNIST data into train and test sets\n(X_train, y_train), (X_test, y_test) = mnist.load_data()\nX_train = X_train.reshape(X_train.shape[0], 28, 28, 1)\nX_test = X_test.reshape(X_test.shape[0], 28, 28, 1)\nX_train = X_train.astype('float32')\nX_test = X_test.astype('float32')\nX_train /= 255\nX_test /= 255\nY_train = np_utils.to_categorical(y_train, 10)\nY_test = np_utils.to_categorical(y_test, 10)"
},
{
"code": null,
"e": 4115,
"s": 3981,
"text": "This step can be defined as “Import libraries and Modules” which means all the libraries and modules are imported as an initial step."
},
{
"code": null,
"e": 4178,
"s": 4115,
"text": "Step 2 − In this step, we will define the model architecture −"
},
{
"code": null,
"e": 4520,
"s": 4178,
"text": "model = Sequential()\nmodel.add(Conv2D(32, 3, 3, activation = 'relu', input_shape = (28,28,1)))\nmodel.add(Conv2D(32, 3, 3, activation = 'relu'))\nmodel.add(MaxPool2D(pool_size = (2,2)))\nmodel.add(Dropout(0.25))\nmodel.add(Flatten())\nmodel.add(Dense(128, activation = 'relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(10, activation = 'softmax'))"
},
{
"code": null,
"e": 4570,
"s": 4520,
"text": "Step 3 − Let us now compile the specified model −"
},
{
"code": null,
"e": 4664,
"s": 4570,
"text": "model.compile(loss = 'categorical_crossentropy', optimizer = 'adam', metrics = ['accuracy'])\n"
},
{
"code": null,
"e": 4721,
"s": 4664,
"text": "Step 4 − We will now fit the model using training data −"
},
{
"code": null,
"e": 4793,
"s": 4721,
"text": "model.fit(X_train, Y_train, batch_size = 32, epochs = 10, verbose = 1)\n"
},
{
"code": null,
"e": 4842,
"s": 4793,
"text": "The output of iterations created is as follows −"
}
] |
How to export class with static methods in Node.js ? | 26 May, 2021
We know JS static keyword defines static properties and methods for a class. Static method or properties can not be called from instances of the class. Instead, they’re calling from the class itself.
class Car {
static run() { console.log('Car running...') }
}
// Error: (intermediate value).run
// is not a function
( new Car() ).run()
// Car running...
Car.run()
Relation between require() and module.exports: By default, module.exports point to an object. The value of module.exports can be literal, function, object, etc. When we export a module, it means we export the value of module.exports.
The task of require() function is to import the value of module.exports in the module from where it was called. The value returned by the require() function in moduleB is equal to the module.exports object in the moduleA. So, the Relation is shown below.
require() == module.exports
Export class with static method: If you want to export a class with a static method from NodeJS module then the idea is as simple as exporting a class itself. Let’s see some examples.
Step 1: Create a NodeJS project using the following command.
mkdir Project && cd Project
npm init -y
Step 2: Create two JS files in the root directory of your project and name them App.js and myModule.js
Project Structure: It will look like this.
Step 3: Edit myModule.js with the following code.
myModule.js
// myModule moduleclass Car{ static run() { console.log('Car running...') }} // Export this modulemodule.exports = Car
We have created a class called Car with static method run() in the myModule.js and export it by assigning the class itself to module.exports
Step 4: Next, edit your App.js with the following code.
App.js
// Import myModuleconst mercedes = require('./myModule') // Printing dataconsole.log(mercedes) // Invoke static functionmercedes.run()
In the App.js file, we import the myModule using require() function and assign the return value to the variable name mercedes. So, the class Car directly assigns to mercedes, and now we can invoke the static method run() from mercedes from App.js module.
Step 5: Run the server using the following command.
node App.js
Output:
[Function: Car]
Car running...
If, you want to export a module in a form of an object then, add class Car as a property of module.exports as shown below:
myModule.js
// myModule moduleclass Car{ static run() { console.log('Car running...') }} // Export this module// add class Car as a property // of module.exportsmodule.exports = { Car }
App.js
// Importing our moduleconst mercedes = require('./myModule').Car // Executing run functionmercedes.run()
Run the server using the following command.
node App.js
Output:
Car running...
NodeJS-Questions
Picked
Node.js
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": "\n26 May, 2021"
},
{
"code": null,
"e": 228,
"s": 28,
"text": "We know JS static keyword defines static properties and methods for a class. Static method or properties can not be called from instances of the class. Instead, they’re calling from the class itself."
},
{
"code": null,
"e": 399,
"s": 228,
"text": "class Car {\n static run() { console.log('Car running...') }\n}\n\n// Error: (intermediate value).run\n// is not a function\n( new Car() ).run()\n\n// Car running...\nCar.run()"
},
{
"code": null,
"e": 634,
"s": 399,
"text": "Relation between require() and module.exports: By default, module.exports point to an object. The value of module.exports can be literal, function, object, etc. When we export a module, it means we export the value of module.exports. "
},
{
"code": null,
"e": 889,
"s": 634,
"text": "The task of require() function is to import the value of module.exports in the module from where it was called. The value returned by the require() function in moduleB is equal to the module.exports object in the moduleA. So, the Relation is shown below."
},
{
"code": null,
"e": 917,
"s": 889,
"text": "require() == module.exports"
},
{
"code": null,
"e": 1102,
"s": 917,
"text": "Export class with static method: If you want to export a class with a static method from NodeJS module then the idea is as simple as exporting a class itself. Let’s see some examples. "
},
{
"code": null,
"e": 1165,
"s": 1104,
"text": "Step 1: Create a NodeJS project using the following command."
},
{
"code": null,
"e": 1205,
"s": 1165,
"text": "mkdir Project && cd Project\nnpm init -y"
},
{
"code": null,
"e": 1308,
"s": 1205,
"text": "Step 2: Create two JS files in the root directory of your project and name them App.js and myModule.js"
},
{
"code": null,
"e": 1351,
"s": 1308,
"text": "Project Structure: It will look like this."
},
{
"code": null,
"e": 1402,
"s": 1351,
"text": "Step 3: Edit myModule.js with the following code. "
},
{
"code": null,
"e": 1414,
"s": 1402,
"text": "myModule.js"
},
{
"code": "// myModule moduleclass Car{ static run() { console.log('Car running...') }} // Export this modulemodule.exports = Car",
"e": 1537,
"s": 1414,
"text": null
},
{
"code": null,
"e": 1678,
"s": 1537,
"text": "We have created a class called Car with static method run() in the myModule.js and export it by assigning the class itself to module.exports"
},
{
"code": null,
"e": 1734,
"s": 1678,
"text": "Step 4: Next, edit your App.js with the following code."
},
{
"code": null,
"e": 1741,
"s": 1734,
"text": "App.js"
},
{
"code": "// Import myModuleconst mercedes = require('./myModule') // Printing dataconsole.log(mercedes) // Invoke static functionmercedes.run()",
"e": 1878,
"s": 1741,
"text": null
},
{
"code": null,
"e": 2134,
"s": 1878,
"text": "In the App.js file, we import the myModule using require() function and assign the return value to the variable name mercedes. So, the class Car directly assigns to mercedes, and now we can invoke the static method run() from mercedes from App.js module. "
},
{
"code": null,
"e": 2186,
"s": 2134,
"text": "Step 5: Run the server using the following command."
},
{
"code": null,
"e": 2198,
"s": 2186,
"text": "node App.js"
},
{
"code": null,
"e": 2206,
"s": 2198,
"text": "Output:"
},
{
"code": null,
"e": 2237,
"s": 2206,
"text": "[Function: Car]\nCar running..."
},
{
"code": null,
"e": 2360,
"s": 2237,
"text": "If, you want to export a module in a form of an object then, add class Car as a property of module.exports as shown below:"
},
{
"code": null,
"e": 2372,
"s": 2360,
"text": "myModule.js"
},
{
"code": "// myModule moduleclass Car{ static run() { console.log('Car running...') }} // Export this module// add class Car as a property // of module.exportsmodule.exports = { Car }",
"e": 2550,
"s": 2372,
"text": null
},
{
"code": null,
"e": 2557,
"s": 2550,
"text": "App.js"
},
{
"code": "// Importing our moduleconst mercedes = require('./myModule').Car // Executing run functionmercedes.run()",
"e": 2664,
"s": 2557,
"text": null
},
{
"code": null,
"e": 2708,
"s": 2664,
"text": "Run the server using the following command."
},
{
"code": null,
"e": 2720,
"s": 2708,
"text": "node App.js"
},
{
"code": null,
"e": 2728,
"s": 2720,
"text": "Output:"
},
{
"code": null,
"e": 2743,
"s": 2728,
"text": "Car running..."
},
{
"code": null,
"e": 2760,
"s": 2743,
"text": "NodeJS-Questions"
},
{
"code": null,
"e": 2767,
"s": 2760,
"text": "Picked"
},
{
"code": null,
"e": 2775,
"s": 2767,
"text": "Node.js"
},
{
"code": null,
"e": 2792,
"s": 2775,
"text": "Web Technologies"
}
] |
Python | Merging nested lists | 18 Dec, 2021
Given two nested lists, ‘lst1’ and ‘lst2’, write a Python program to create a new nested list ‘lst3’ out of the two given nested lists, so that the new nested list consist common intersections of both lists as well as the non-intersecting elements.
Examples:
Input : lst1 = [[5, 9], [8, 2, 6], [3, 4]]
lst2 = [[9, 5, 8], [2, 6], [3, 4, 1]]
Output : [[9, 5], [8], [2, 6], [3, 4], [1]]
Input : lst1 = [['a', 'b', 'c'], ['x']]
lst2 = [['b', 'c', 'y'], ['x', 'y']]
Output : [['b', 'c'], ['x'], ['y'], ['a']]
Approach #1 : By set intersection using functools.reduce()This method uses the set intersection to compute each intersection, then add any item which is leftover (that is, items appearing on only one of the two lists). We will first use functools.reduce() to yield unique elements of ‘lst1’ and ‘lst2’ and save them to ‘temp1’ and ‘temp2’ respectively. After this, find the set intersection of both the list in ‘lst3’. At last, find the symmetric difference of ‘lst1’ and ‘lst2’, which yields the items which appear in only one of the 2 sets and append it to ‘lst3’.
Python3
# Python3 program to find Greatest common# intersection of two nested listsimport itertoolsimport functools def GCI(lst1, lst2): temp1 = functools.reduce(lambda a, b: set(a).union(set(b)), lst1) temp2 = functools.reduce(lambda a, b: set(a).union(set(b)), lst2) lst3 = [list(set(a).intersection(set(b))) for a, b in itertools.product(lst1, lst2) if len(set(a).intersection(set(b))) != 0] lst3.extend([x] for x in temp1.symmetric_difference(temp2)) return lst3 # Driver codelst1 = [[5, 9], [8, 2, 6], [3, 4]]lst2 = [[9, 5, 8], [2, 6], [3, 4, 1]]print(GCI(lst1, lst2))
[[9, 5], [8], [2, 6], [3, 4], [1]]
Approach #2 : By set intersection using filterThis is an efficient approach over approach #1 as it simplifies the intersection. First, flatten the nested lists. Take Intersection using filter() and save it to ‘lst3’. Now find elements either not in lst1 or in lst2, and save them to ‘temp’. Finally, append ‘temp’ to ‘lst3’.
Python3
# Python3 program to find Greatest common# intersection of two nested listsimport itertoolsfrom functools import reduce def GCI(lst1, lst2): temp1 = reduce(list.__add__, lst1) temp2 = reduce(list.__add__, lst2) lst3 = list(filter(None, [list(set(o1) & set(o2)) for o1 in lst1 for o2 in lst2])) temp = filter(lambda x : x not in temp1 or x not in temp2, set(temp1) | set(temp2)) lst3.append(list(temp)) return lst3 # Driver codelst1 = [[5, 9], [8, 2, 6], [3, 4]]lst2 = [[9, 5, 8], [2, 6], [3, 4, 1]]print(GCI(lst1, lst2))
[[9, 5], [8], [2, 6], [3, 4], [1]]
varshagumber28
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Dec, 2021"
},
{
"code": null,
"e": 277,
"s": 28,
"text": "Given two nested lists, ‘lst1’ and ‘lst2’, write a Python program to create a new nested list ‘lst3’ out of the two given nested lists, so that the new nested list consist common intersections of both lists as well as the non-intersecting elements."
},
{
"code": null,
"e": 288,
"s": 277,
"text": "Examples: "
},
{
"code": null,
"e": 550,
"s": 288,
"text": "Input : lst1 = [[5, 9], [8, 2, 6], [3, 4]]\n lst2 = [[9, 5, 8], [2, 6], [3, 4, 1]]\nOutput : [[9, 5], [8], [2, 6], [3, 4], [1]]\n\nInput : lst1 = [['a', 'b', 'c'], ['x']]\n lst2 = [['b', 'c', 'y'], ['x', 'y']]\nOutput : [['b', 'c'], ['x'], ['y'], ['a']]"
},
{
"code": null,
"e": 1117,
"s": 550,
"text": "Approach #1 : By set intersection using functools.reduce()This method uses the set intersection to compute each intersection, then add any item which is leftover (that is, items appearing on only one of the two lists). We will first use functools.reduce() to yield unique elements of ‘lst1’ and ‘lst2’ and save them to ‘temp1’ and ‘temp2’ respectively. After this, find the set intersection of both the list in ‘lst3’. At last, find the symmetric difference of ‘lst1’ and ‘lst2’, which yields the items which appear in only one of the 2 sets and append it to ‘lst3’."
},
{
"code": null,
"e": 1125,
"s": 1117,
"text": "Python3"
},
{
"code": "# Python3 program to find Greatest common# intersection of two nested listsimport itertoolsimport functools def GCI(lst1, lst2): temp1 = functools.reduce(lambda a, b: set(a).union(set(b)), lst1) temp2 = functools.reduce(lambda a, b: set(a).union(set(b)), lst2) lst3 = [list(set(a).intersection(set(b))) for a, b in itertools.product(lst1, lst2) if len(set(a).intersection(set(b))) != 0] lst3.extend([x] for x in temp1.symmetric_difference(temp2)) return lst3 # Driver codelst1 = [[5, 9], [8, 2, 6], [3, 4]]lst2 = [[9, 5, 8], [2, 6], [3, 4, 1]]print(GCI(lst1, lst2))",
"e": 1754,
"s": 1125,
"text": null
},
{
"code": null,
"e": 1789,
"s": 1754,
"text": "[[9, 5], [8], [2, 6], [3, 4], [1]]"
},
{
"code": null,
"e": 2118,
"s": 1791,
"text": " Approach #2 : By set intersection using filterThis is an efficient approach over approach #1 as it simplifies the intersection. First, flatten the nested lists. Take Intersection using filter() and save it to ‘lst3’. Now find elements either not in lst1 or in lst2, and save them to ‘temp’. Finally, append ‘temp’ to ‘lst3’. "
},
{
"code": null,
"e": 2126,
"s": 2118,
"text": "Python3"
},
{
"code": "# Python3 program to find Greatest common# intersection of two nested listsimport itertoolsfrom functools import reduce def GCI(lst1, lst2): temp1 = reduce(list.__add__, lst1) temp2 = reduce(list.__add__, lst2) lst3 = list(filter(None, [list(set(o1) & set(o2)) for o1 in lst1 for o2 in lst2])) temp = filter(lambda x : x not in temp1 or x not in temp2, set(temp1) | set(temp2)) lst3.append(list(temp)) return lst3 # Driver codelst1 = [[5, 9], [8, 2, 6], [3, 4]]lst2 = [[9, 5, 8], [2, 6], [3, 4, 1]]print(GCI(lst1, lst2))",
"e": 2742,
"s": 2126,
"text": null
},
{
"code": null,
"e": 2777,
"s": 2742,
"text": "[[9, 5], [8], [2, 6], [3, 4], [1]]"
},
{
"code": null,
"e": 2794,
"s": 2779,
"text": "varshagumber28"
},
{
"code": null,
"e": 2815,
"s": 2794,
"text": "Python list-programs"
},
{
"code": null,
"e": 2822,
"s": 2815,
"text": "Python"
},
{
"code": null,
"e": 2838,
"s": 2822,
"text": "Python Programs"
}
] |
Improving Linear Search Technique | 13 Jan, 2022
A linear search or sequential search is a method for finding an element within a list. It sequentially checks each element of the list until a match is found or the whole list has been searched. It is observed that when searching for a key element, then there is a possibility for searching the same key element again and again.
The goal is that if the same element is searched again then the operation must take lesser time. Therefore, in such a case, Linear Search can be improved by using the following two methods:
TranspositionMove to Front
Transposition
Move to Front
In transposition, if the key element is found, it is swapped to the element an index before to increase in a number of search count for a particular key, the search operation also optimizes and keep moving the element to the starting of the array where the searching time complexity would be of constant time.
For Example: If the array arr[] is {2, 5, 7, 1, 6, 4, 5, 8, 3, 7} and let the key to be searched is 4, then below are the steps:
After searching for key 4, the element is found at index 5 of the given array after 6 comparisons. Now after transposition, the array becomes {2, 5, 7, 1, 4, 6, 5, 8, 3, 7} i.e., the key with value 4 comes at index 4.
Again after searching for key 4, the element is found at index 4 of the given array after 6 comparisons. Now after transposition, the array becomes {2, 5, 7, 4, 1, 6, 5, 8, 3, 7} i.e., the key with value 4 comes at index 3.
The above process will continue until any key reaches the front of the array if the element to be found is not at the first index.
Below is the implementation of the above algorithm discussed:
C++
C
Java
C#
Python3
// C++ program for transposition to// improve the Linear Search Algorithm#include <iostream>using namespace std; // Structure of the arraystruct Array { int A[10]; int size; int length;}; // Function to print the array elementvoid Display(struct Array arr){ int i; // Traverse the array arr[] for (i = 0; i < arr.length; i++) { cout <<" "<< arr.A[i]; } cout <<"\n";} // Function that swaps two elements// at different addressesvoid swap(int* x, int* y){ // Store the value store at // x in a variable temp int temp = *x; // Swapping of value *x = *y; *y = temp;} // Function that performs the Linear// Search Transpositionint LinearSearchTransposition( struct Array* arr, int key){ int i; // Traverse the array for (i = 0; i < arr->length; i++) { // If key is found, then swap // the element with it's // previous index if (key == arr->A[i]) { // If key is first element if (i == 0) return i; swap(&arr->A[i], &arr->A[i - 1]); return i; } } return -1;} // Driver Codeint main(){ // Given array arr[] struct Array arr = { { 2, 23, 14, 5, 6, 9, 8, 12 }, 10, 8 }; cout <<"Elements before Linear" " Search Transposition: "; // Function Call for displaying // the array arr[] Display(arr); // Function Call for transposition LinearSearchTransposition(&arr, 14); cout <<"Elements after Linear" " Search Transposition: "; // Function Call for displaying // the array arr[] Display(arr); return 0;} // this code is contributed by shivanisinghss2110
// C program for transposition to// improve the Linear Search Algorithm#include <stdio.h> // Structure of the arraystruct Array { int A[10]; int size; int length;}; // Function to print the array elementvoid Display(struct Array arr){ int i; // Traverse the array arr[] for (i = 0; i < arr.length; i++) { printf("%d ", arr.A[i]); } printf("\n");} // Function that swaps two elements// at different addressesvoid swap(int* x, int* y){ // Store the value store at // x in a variable temp int temp = *x; // Swapping of value *x = *y; *y = temp;} // Function that performs the Linear// Search Transpositionint LinearSearchTransposition( struct Array* arr, int key){ int i; // Traverse the array for (i = 0; i < arr->length; i++) { // If key is found, then swap // the element with it's // previous index if (key == arr->A[i]) { // If key is first element if (i == 0) return i; swap(&arr->A[i], &arr->A[i - 1]); return i; } } return -1;} // Driver Codeint main(){ // Given array arr[] struct Array arr = { { 2, 23, 14, 5, 6, 9, 8, 12 }, 10, 8 }; printf("Elements before Linear" " Search Transposition: "); // Function Call for displaying // the array arr[] Display(arr); // Function Call for transposition LinearSearchTransposition(&arr, 14); printf("Elements after Linear" " Search Transposition: "); // Function Call for displaying // the array arr[] Display(arr); return 0;}
// Java program for transposition// to improve the Linear Search// Algorithmclass GFG{ // Structure of the// arraystatic class Array{ int []A = new int[10]; int size; int length; Array(int []A, int size, int length) { this.A = A; this.size = size; this.length = length; }}; // Function to print the// array elementstatic void Display(Array arr){ int i; // Traverse the array arr[] for (i = 0; i < arr.length; i++) { System.out.printf("%d ", arr.A[i]); } System.out.printf("\n");} // Function that performs the Linear// Search Transpositionstatic int LinearSearchTransposition(Array arr, int key){ int i; // Traverse the array for (i = 0; i < arr.length; i++) { // If key is found, then swap // the element with it's // previous index if (key == arr.A[i]) { // If key is first element if (i == 0) return i; int temp = arr.A[i]; arr.A[i] = arr.A[i - 1]; arr.A[i - 1] = temp; return i; } } return -1;} // Driver Codepublic static void main(String[] args){ // Given array arr[] int tempArr[] = {2, 23, 14, 5, 6, 9, 8, 12}; Array arr = new Array(tempArr, 10, 8); System.out.printf("Elements before Linear" + " Search Transposition: "); // Function Call for displaying // the array arr[] Display(arr); // Function Call for transposition LinearSearchTransposition(arr, 14); System.out.printf("Elements after Linear" + " Search Transposition: "); // Function Call for displaying // the array arr[] Display(arr);}} // This code is contributed by Princi Singh
// C# program for transposition// to improve the Linear Search// Algorithmusing System; class GFG{ // Structure of the// arraypublic class Array{ public int []A = new int[10]; public int size; public int length; public Array(int []A, int size, int length) { this.A = A; this.size = size; this.length = length; }}; // Function to print the// array elementstatic void Display(Array arr){ int i; // Traverse the array []arr for(i = 0; i < arr.length; i++) { Console.Write(arr.A[i] + " "); } Console.Write("\n");} // Function that performs the Linear// Search Transpositionstatic int LinearSearchTransposition(Array arr, int key){ int i; // Traverse the array for(i = 0; i < arr.length; i++) { // If key is found, then swap // the element with it's // previous index if (key == arr.A[i]) { // If key is first element if (i == 0) return i; int temp = arr.A[i]; arr.A[i] = arr.A[i - 1]; arr.A[i - 1] = temp; return i; } } return -1;} // Driver Codepublic static void Main(String[] args){ // Given array []arr int []tempArr = { 2, 23, 14, 5, 6, 9, 8, 12 }; Array arr = new Array(tempArr, 10, 8); Console.Write("Elements before Linear " + "Search Transposition: "); // Function Call for displaying // the array []arr Display(arr); // Function Call for transposition LinearSearchTransposition(arr, 14); Console.Write("Elements after Linear " + "Search Transposition: "); // Function Call for displaying // the array []arr Display(arr);}} // This code is contributed by Amit Katiyar
# Python3 program for transposition to# improve the Linear Search Algorithm # Structure of the arrayclass Array : def __init__(self,a=[0]*10,size=10,l=0) -> None: self.A=a self.size=size self.length=l # Function to print array elementdef Display(arr): # Traverse the array arr[] for i in range(arr.length) : print(arr.A[i],end=" ") print() # Function that performs the Linear# Search Transpositiondef LinearSearchTransposition(arr, key): # Traverse the array for i in range(arr.length) : # If key is found, then swap # the element with it's # previous index if (key == arr.A[i]) : # If key is first element if (i == 0): return i arr.A[i],arr.A[i - 1]=arr.A[i - 1],arr.A[i] return i return -1 # Driver Codeif __name__ == '__main__': # Given array arr[] arr=Array([2, 23, 14, 5, 6, 9, 8, 12], 10, 8) print("Elements before Linear Search Transposition: ") # Function Call for displaying # the array arr[] Display(arr) # Function Call for transposition LinearSearchTransposition(arr, 14) print("Elements after Linear Search Transposition: ") # Function Call for displaying # the array arr[] Display(arr)
In this method, if the key element is found then it is directly swapped with the index 0, so that the next consecutive time, search operation for the same key element is of O(1), i.e., constant time.
For Example: If the array arr[] is {2, 5, 7, 1, 6, 4, 5, 8, 3, 7} and let the key to be searched is 4, then below are the steps:
After searching for key 4, the element is found at index 5 of the given array after 6 comparisons. Now after moving to front operation, the array becomes {4, 2, 5, 7, 1, 6, 5, 8, 3, 7} i.e., the key with value 4 comes at index 0.
Again after searching for key 4, the element is found at index 0 of the given array which reduces the entire’s search space.
C++
C
Java
C#
Python3
// C program to implement the move to// front to optimized Linear Search#include <iostream>using namespace std; // Structure of the arraystruct Array { int A[10]; int size; int length;}; // Function to print the array elementvoid Display(struct Array arr){ int i; // Traverse the array arr[] for (i = 0; i < arr.length; i++) { cout <<" "<< arr.A[i]; } cout <<"\n";} // Function that swaps two elements// at different addressesvoid swap(int* x, int* y){ // Store the value store at // x in a variable temp int temp = *x; // Swapping of value *x = *y; *y = temp;} // Function that performs the move to// front operation for Linear Searchint LinearSearchMoveToFront( struct Array* arr, int key){ int i; // Traverse the array for (i = 0; i < arr->length; i++) { // If key is found, then swap // the element with 0-th index if (key == arr->A[i]) { swap(&arr->A[i], &arr->A[0]); return i; } } return -1;} // Driver codeint main(){ // Given array arr[] struct Array arr = { { 2, 23, 14, 5, 6, 9, 8, 12 }, 10, 8 }; cout <<"Elements before Linear" " Search Move To Front: "; // Function Call for displaying // the array arr[] Display(arr); // Function Call for Move to // front operation LinearSearchMoveToFront(&arr, 14); cout <<"Elements after Linear" " Search Move To Front: "; // Function Call for displaying // the array arr[] Display(arr); return 0;} // This code is contributed by shivanisinghss2110
// C program to implement the move to// front to optimized Linear Search#include <stdio.h> // Structure of the arraystruct Array { int A[10]; int size; int length;}; // Function to print the array elementvoid Display(struct Array arr){ int i; // Traverse the array arr[] for (i = 0; i < arr.length; i++) { printf("%d ", arr.A[i]); } printf("\n");} // Function that swaps two elements// at different addressesvoid swap(int* x, int* y){ // Store the value store at // x in a variable temp int temp = *x; // Swapping of value *x = *y; *y = temp;} // Function that performs the move to// front operation for Linear Searchint LinearSearchMoveToFront( struct Array* arr, int key){ int i; // Traverse the array for (i = 0; i < arr->length; i++) { // If key is found, then swap // the element with 0-th index if (key == arr->A[i]) { swap(&arr->A[i], &arr->A[0]); return i; } } return -1;} // Driver codeint main(){ // Given array arr[] struct Array arr = { { 2, 23, 14, 5, 6, 9, 8, 12 }, 10, 8 }; printf("Elements before Linear" " Search Move To Front: "); // Function Call for displaying // the array arr[] Display(arr); // Function Call for Move to // front operation LinearSearchMoveToFront(&arr, 14); printf("Elements after Linear" " Search Move To Front: "); // Function Call for displaying // the array arr[] Display(arr); return 0;}
// Java program to implement// the move to front to optimized// Linear Searchclass GFG{ // Structure of the arraystatic class Array{ int []A = new int[10]; int size; int length; Array(int []A, int size, int length) { this.A = A; this.size = size; this.length = length; }}; // Function to print the// array elementstatic void Display(Array arr){ int i; // Traverse the array arr[] for (i = 0; i < arr.length; i++) { System.out.printf("%d ", arr.A[i]); } System.out.printf("\n");} // Function that performs the// move to front operation for// Linear Searchstatic int LinearSearchMoveToFront(Array arr, int key){ int i; // Traverse the array for (i = 0; i < arr.length; i++) { // If key is found, then swap // the element with 0-th index if (key == arr.A[i]) { int temp = arr.A[i]; arr.A[i] = arr.A[0]; arr.A[0] = temp; return i; } } return -1;} // Driver codepublic static void main(String[] args){ // Given array arr[] int a[] = {2, 23, 14, 5, 6, 9, 8, 12 }; Array arr = new Array(a, 10, 8); System.out.printf("Elements before Linear" + " Search Move To Front: "); // Function Call for // displaying the array // arr[] Display(arr); // Function Call for Move // to front operation LinearSearchMoveToFront(arr, 14); System.out.printf("Elements after Linear" + " Search Move To Front: "); // Function Call for displaying // the array arr[] Display(arr);}} // This code is contributed by gauravrajput1
// C# program to implement// the move to front to optimized// Linear Searchusing System;class GFG{ // Structure of the arraypublic class Array{ public int []A = new int[10]; public int size; public int length; public Array(int []A, int size, int length) { this.A = A; this.size = size; this.length = length; }}; // Function to print the// array elementstatic void Display(Array arr){ int i; // Traverse the array []arr for (i = 0; i < arr.length; i++) { Console.Write(" " + arr.A[i]); } Console.Write("\n");} // Function that performs the// move to front operation for// Linear Searchstatic int LinearSearchMoveToFront(Array arr, int key){ int i; // Traverse the array for (i = 0; i < arr.length; i++) { // If key is found, then swap // the element with 0-th index if (key == arr.A[i]) { int temp = arr.A[i]; arr.A[i] = arr.A[0]; arr.A[0] = temp; return i; } } return -1;} // Driver codepublic static void Main(String[] args){ // Given array []arr int []a = {2, 23, 14, 5, 6, 9, 8, 12 }; Array arr = new Array(a, 10, 8); Console.Write("Elements before Linear" + " Search Move To Front: "); // Function Call for // displaying the array // []arr Display(arr); // Function Call for Move // to front operation LinearSearchMoveToFront(arr, 14); Console.Write("Elements after Linear" + " Search Move To Front: "); // Function Call for displaying // the array []arr Display(arr);}} // This code is contributed by gauravrajput1
# Python3 program for transposition to# improve the Linear Search Algorithm # Structure of the arrayclass Array : def __init__(self,a=[0]*10,size=10,l=0) -> None: self.A=a self.size=size self.length=l # Function to print array elementdef Display(arr): # Traverse the array arr[] for i in range(arr.length) : print(arr.A[i],end=" ") print() # Function that performs the move to# front operation for Linear Searchdef LinearSearchMoveToFront(arr, key:int): # Traverse the array for i in range(arr.length) : # If key is found, then swap # the element with 0-th index if (key == arr.A[i]) : arr.A[i], arr.A[0]=arr.A[0],arr.A[i] return i return -1 # Driver Codeif __name__ == '__main__': # Given array arr[] arr=Array([2, 23, 14, 5, 6, 9, 8, 12], 10, 8) print("Elements before Linear Search Transposition: ",end='') # Function Call for displaying # the array arr[] Display(arr) # Function Call for transposition LinearSearchMoveToFront(arr, 14) print("Elements after Linear Search Transposition: ",end='') # Function Call for displaying # the array arr[] Display(arr)
Time Complexity: O(N) Auxiliary Space: O(1)
princi singh
amit143katiyar
GauravRajput1
shivanisinghss2110
pankajsharmagfg
amartyaghoshgfg
khushboogoyal499
Algorithms-Searching
Algorithms
Arrays
Articles
Data Structures
Searching
Data Structures
Arrays
Searching
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
SDE SHEET - A Complete Guide for SDE Preparation
What is Hashing | A Complete Tutorial
Understanding Time Complexity with Simple Examples
Find if there is a path between two vertices in an undirected graph
Arrays in Java
Multidimensional Arrays in Java
Arrays in C/C++
Find the smallest positive integer value that cannot be represented as sum of any subset of a given array
Maximum and minimum of an array using minimum number of comparisons | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n13 Jan, 2022"
},
{
"code": null,
"e": 382,
"s": 53,
"text": "A linear search or sequential search is a method for finding an element within a list. It sequentially checks each element of the list until a match is found or the whole list has been searched. It is observed that when searching for a key element, then there is a possibility for searching the same key element again and again."
},
{
"code": null,
"e": 573,
"s": 382,
"text": "The goal is that if the same element is searched again then the operation must take lesser time. Therefore, in such a case, Linear Search can be improved by using the following two methods: "
},
{
"code": null,
"e": 600,
"s": 573,
"text": "TranspositionMove to Front"
},
{
"code": null,
"e": 614,
"s": 600,
"text": "Transposition"
},
{
"code": null,
"e": 628,
"s": 614,
"text": "Move to Front"
},
{
"code": null,
"e": 939,
"s": 628,
"text": "In transposition, if the key element is found, it is swapped to the element an index before to increase in a number of search count for a particular key, the search operation also optimizes and keep moving the element to the starting of the array where the searching time complexity would be of constant time. "
},
{
"code": null,
"e": 1069,
"s": 939,
"text": "For Example: If the array arr[] is {2, 5, 7, 1, 6, 4, 5, 8, 3, 7} and let the key to be searched is 4, then below are the steps: "
},
{
"code": null,
"e": 1287,
"s": 1069,
"text": "After searching for key 4, the element is found at index 5 of the given array after 6 comparisons. Now after transposition, the array becomes {2, 5, 7, 1, 4, 6, 5, 8, 3, 7} i.e., the key with value 4 comes at index 4."
},
{
"code": null,
"e": 1511,
"s": 1287,
"text": "Again after searching for key 4, the element is found at index 4 of the given array after 6 comparisons. Now after transposition, the array becomes {2, 5, 7, 4, 1, 6, 5, 8, 3, 7} i.e., the key with value 4 comes at index 3."
},
{
"code": null,
"e": 1642,
"s": 1511,
"text": "The above process will continue until any key reaches the front of the array if the element to be found is not at the first index."
},
{
"code": null,
"e": 1704,
"s": 1642,
"text": "Below is the implementation of the above algorithm discussed:"
},
{
"code": null,
"e": 1708,
"s": 1704,
"text": "C++"
},
{
"code": null,
"e": 1710,
"s": 1708,
"text": "C"
},
{
"code": null,
"e": 1715,
"s": 1710,
"text": "Java"
},
{
"code": null,
"e": 1718,
"s": 1715,
"text": "C#"
},
{
"code": null,
"e": 1726,
"s": 1718,
"text": "Python3"
},
{
"code": "// C++ program for transposition to// improve the Linear Search Algorithm#include <iostream>using namespace std; // Structure of the arraystruct Array { int A[10]; int size; int length;}; // Function to print the array elementvoid Display(struct Array arr){ int i; // Traverse the array arr[] for (i = 0; i < arr.length; i++) { cout <<\" \"<< arr.A[i]; } cout <<\"\\n\";} // Function that swaps two elements// at different addressesvoid swap(int* x, int* y){ // Store the value store at // x in a variable temp int temp = *x; // Swapping of value *x = *y; *y = temp;} // Function that performs the Linear// Search Transpositionint LinearSearchTransposition( struct Array* arr, int key){ int i; // Traverse the array for (i = 0; i < arr->length; i++) { // If key is found, then swap // the element with it's // previous index if (key == arr->A[i]) { // If key is first element if (i == 0) return i; swap(&arr->A[i], &arr->A[i - 1]); return i; } } return -1;} // Driver Codeint main(){ // Given array arr[] struct Array arr = { { 2, 23, 14, 5, 6, 9, 8, 12 }, 10, 8 }; cout <<\"Elements before Linear\" \" Search Transposition: \"; // Function Call for displaying // the array arr[] Display(arr); // Function Call for transposition LinearSearchTransposition(&arr, 14); cout <<\"Elements after Linear\" \" Search Transposition: \"; // Function Call for displaying // the array arr[] Display(arr); return 0;} // this code is contributed by shivanisinghss2110",
"e": 3445,
"s": 1726,
"text": null
},
{
"code": "// C program for transposition to// improve the Linear Search Algorithm#include <stdio.h> // Structure of the arraystruct Array { int A[10]; int size; int length;}; // Function to print the array elementvoid Display(struct Array arr){ int i; // Traverse the array arr[] for (i = 0; i < arr.length; i++) { printf(\"%d \", arr.A[i]); } printf(\"\\n\");} // Function that swaps two elements// at different addressesvoid swap(int* x, int* y){ // Store the value store at // x in a variable temp int temp = *x; // Swapping of value *x = *y; *y = temp;} // Function that performs the Linear// Search Transpositionint LinearSearchTransposition( struct Array* arr, int key){ int i; // Traverse the array for (i = 0; i < arr->length; i++) { // If key is found, then swap // the element with it's // previous index if (key == arr->A[i]) { // If key is first element if (i == 0) return i; swap(&arr->A[i], &arr->A[i - 1]); return i; } } return -1;} // Driver Codeint main(){ // Given array arr[] struct Array arr = { { 2, 23, 14, 5, 6, 9, 8, 12 }, 10, 8 }; printf(\"Elements before Linear\" \" Search Transposition: \"); // Function Call for displaying // the array arr[] Display(arr); // Function Call for transposition LinearSearchTransposition(&arr, 14); printf(\"Elements after Linear\" \" Search Transposition: \"); // Function Call for displaying // the array arr[] Display(arr); return 0;}",
"e": 5096,
"s": 3445,
"text": null
},
{
"code": "// Java program for transposition// to improve the Linear Search// Algorithmclass GFG{ // Structure of the// arraystatic class Array{ int []A = new int[10]; int size; int length; Array(int []A, int size, int length) { this.A = A; this.size = size; this.length = length; }}; // Function to print the// array elementstatic void Display(Array arr){ int i; // Traverse the array arr[] for (i = 0; i < arr.length; i++) { System.out.printf(\"%d \", arr.A[i]); } System.out.printf(\"\\n\");} // Function that performs the Linear// Search Transpositionstatic int LinearSearchTransposition(Array arr, int key){ int i; // Traverse the array for (i = 0; i < arr.length; i++) { // If key is found, then swap // the element with it's // previous index if (key == arr.A[i]) { // If key is first element if (i == 0) return i; int temp = arr.A[i]; arr.A[i] = arr.A[i - 1]; arr.A[i - 1] = temp; return i; } } return -1;} // Driver Codepublic static void main(String[] args){ // Given array arr[] int tempArr[] = {2, 23, 14, 5, 6, 9, 8, 12}; Array arr = new Array(tempArr, 10, 8); System.out.printf(\"Elements before Linear\" + \" Search Transposition: \"); // Function Call for displaying // the array arr[] Display(arr); // Function Call for transposition LinearSearchTransposition(arr, 14); System.out.printf(\"Elements after Linear\" + \" Search Transposition: \"); // Function Call for displaying // the array arr[] Display(arr);}} // This code is contributed by Princi Singh",
"e": 6794,
"s": 5096,
"text": null
},
{
"code": "// C# program for transposition// to improve the Linear Search// Algorithmusing System; class GFG{ // Structure of the// arraypublic class Array{ public int []A = new int[10]; public int size; public int length; public Array(int []A, int size, int length) { this.A = A; this.size = size; this.length = length; }}; // Function to print the// array elementstatic void Display(Array arr){ int i; // Traverse the array []arr for(i = 0; i < arr.length; i++) { Console.Write(arr.A[i] + \" \"); } Console.Write(\"\\n\");} // Function that performs the Linear// Search Transpositionstatic int LinearSearchTransposition(Array arr, int key){ int i; // Traverse the array for(i = 0; i < arr.length; i++) { // If key is found, then swap // the element with it's // previous index if (key == arr.A[i]) { // If key is first element if (i == 0) return i; int temp = arr.A[i]; arr.A[i] = arr.A[i - 1]; arr.A[i - 1] = temp; return i; } } return -1;} // Driver Codepublic static void Main(String[] args){ // Given array []arr int []tempArr = { 2, 23, 14, 5, 6, 9, 8, 12 }; Array arr = new Array(tempArr, 10, 8); Console.Write(\"Elements before Linear \" + \"Search Transposition: \"); // Function Call for displaying // the array []arr Display(arr); // Function Call for transposition LinearSearchTransposition(arr, 14); Console.Write(\"Elements after Linear \" + \"Search Transposition: \"); // Function Call for displaying // the array []arr Display(arr);}} // This code is contributed by Amit Katiyar",
"e": 8702,
"s": 6794,
"text": null
},
{
"code": "# Python3 program for transposition to# improve the Linear Search Algorithm # Structure of the arrayclass Array : def __init__(self,a=[0]*10,size=10,l=0) -> None: self.A=a self.size=size self.length=l # Function to print array elementdef Display(arr): # Traverse the array arr[] for i in range(arr.length) : print(arr.A[i],end=\" \") print() # Function that performs the Linear# Search Transpositiondef LinearSearchTransposition(arr, key): # Traverse the array for i in range(arr.length) : # If key is found, then swap # the element with it's # previous index if (key == arr.A[i]) : # If key is first element if (i == 0): return i arr.A[i],arr.A[i - 1]=arr.A[i - 1],arr.A[i] return i return -1 # Driver Codeif __name__ == '__main__': # Given array arr[] arr=Array([2, 23, 14, 5, 6, 9, 8, 12], 10, 8) print(\"Elements before Linear Search Transposition: \") # Function Call for displaying # the array arr[] Display(arr) # Function Call for transposition LinearSearchTransposition(arr, 14) print(\"Elements after Linear Search Transposition: \") # Function Call for displaying # the array arr[] Display(arr)",
"e": 10007,
"s": 8702,
"text": null
},
{
"code": null,
"e": 10208,
"s": 10007,
"text": "In this method, if the key element is found then it is directly swapped with the index 0, so that the next consecutive time, search operation for the same key element is of O(1), i.e., constant time. "
},
{
"code": null,
"e": 10338,
"s": 10208,
"text": "For Example: If the array arr[] is {2, 5, 7, 1, 6, 4, 5, 8, 3, 7} and let the key to be searched is 4, then below are the steps: "
},
{
"code": null,
"e": 10568,
"s": 10338,
"text": "After searching for key 4, the element is found at index 5 of the given array after 6 comparisons. Now after moving to front operation, the array becomes {4, 2, 5, 7, 1, 6, 5, 8, 3, 7} i.e., the key with value 4 comes at index 0."
},
{
"code": null,
"e": 10693,
"s": 10568,
"text": "Again after searching for key 4, the element is found at index 0 of the given array which reduces the entire’s search space."
},
{
"code": null,
"e": 10697,
"s": 10693,
"text": "C++"
},
{
"code": null,
"e": 10699,
"s": 10697,
"text": "C"
},
{
"code": null,
"e": 10704,
"s": 10699,
"text": "Java"
},
{
"code": null,
"e": 10707,
"s": 10704,
"text": "C#"
},
{
"code": null,
"e": 10715,
"s": 10707,
"text": "Python3"
},
{
"code": "// C program to implement the move to// front to optimized Linear Search#include <iostream>using namespace std; // Structure of the arraystruct Array { int A[10]; int size; int length;}; // Function to print the array elementvoid Display(struct Array arr){ int i; // Traverse the array arr[] for (i = 0; i < arr.length; i++) { cout <<\" \"<< arr.A[i]; } cout <<\"\\n\";} // Function that swaps two elements// at different addressesvoid swap(int* x, int* y){ // Store the value store at // x in a variable temp int temp = *x; // Swapping of value *x = *y; *y = temp;} // Function that performs the move to// front operation for Linear Searchint LinearSearchMoveToFront( struct Array* arr, int key){ int i; // Traverse the array for (i = 0; i < arr->length; i++) { // If key is found, then swap // the element with 0-th index if (key == arr->A[i]) { swap(&arr->A[i], &arr->A[0]); return i; } } return -1;} // Driver codeint main(){ // Given array arr[] struct Array arr = { { 2, 23, 14, 5, 6, 9, 8, 12 }, 10, 8 }; cout <<\"Elements before Linear\" \" Search Move To Front: \"; // Function Call for displaying // the array arr[] Display(arr); // Function Call for Move to // front operation LinearSearchMoveToFront(&arr, 14); cout <<\"Elements after Linear\" \" Search Move To Front: \"; // Function Call for displaying // the array arr[] Display(arr); return 0;} // This code is contributed by shivanisinghss2110",
"e": 12331,
"s": 10715,
"text": null
},
{
"code": "// C program to implement the move to// front to optimized Linear Search#include <stdio.h> // Structure of the arraystruct Array { int A[10]; int size; int length;}; // Function to print the array elementvoid Display(struct Array arr){ int i; // Traverse the array arr[] for (i = 0; i < arr.length; i++) { printf(\"%d \", arr.A[i]); } printf(\"\\n\");} // Function that swaps two elements// at different addressesvoid swap(int* x, int* y){ // Store the value store at // x in a variable temp int temp = *x; // Swapping of value *x = *y; *y = temp;} // Function that performs the move to// front operation for Linear Searchint LinearSearchMoveToFront( struct Array* arr, int key){ int i; // Traverse the array for (i = 0; i < arr->length; i++) { // If key is found, then swap // the element with 0-th index if (key == arr->A[i]) { swap(&arr->A[i], &arr->A[0]); return i; } } return -1;} // Driver codeint main(){ // Given array arr[] struct Array arr = { { 2, 23, 14, 5, 6, 9, 8, 12 }, 10, 8 }; printf(\"Elements before Linear\" \" Search Move To Front: \"); // Function Call for displaying // the array arr[] Display(arr); // Function Call for Move to // front operation LinearSearchMoveToFront(&arr, 14); printf(\"Elements after Linear\" \" Search Move To Front: \"); // Function Call for displaying // the array arr[] Display(arr); return 0;}",
"e": 13881,
"s": 12331,
"text": null
},
{
"code": "// Java program to implement// the move to front to optimized// Linear Searchclass GFG{ // Structure of the arraystatic class Array{ int []A = new int[10]; int size; int length; Array(int []A, int size, int length) { this.A = A; this.size = size; this.length = length; }}; // Function to print the// array elementstatic void Display(Array arr){ int i; // Traverse the array arr[] for (i = 0; i < arr.length; i++) { System.out.printf(\"%d \", arr.A[i]); } System.out.printf(\"\\n\");} // Function that performs the// move to front operation for// Linear Searchstatic int LinearSearchMoveToFront(Array arr, int key){ int i; // Traverse the array for (i = 0; i < arr.length; i++) { // If key is found, then swap // the element with 0-th index if (key == arr.A[i]) { int temp = arr.A[i]; arr.A[i] = arr.A[0]; arr.A[0] = temp; return i; } } return -1;} // Driver codepublic static void main(String[] args){ // Given array arr[] int a[] = {2, 23, 14, 5, 6, 9, 8, 12 }; Array arr = new Array(a, 10, 8); System.out.printf(\"Elements before Linear\" + \" Search Move To Front: \"); // Function Call for // displaying the array // arr[] Display(arr); // Function Call for Move // to front operation LinearSearchMoveToFront(arr, 14); System.out.printf(\"Elements after Linear\" + \" Search Move To Front: \"); // Function Call for displaying // the array arr[] Display(arr);}} // This code is contributed by gauravrajput1",
"e": 15463,
"s": 13881,
"text": null
},
{
"code": "// C# program to implement// the move to front to optimized// Linear Searchusing System;class GFG{ // Structure of the arraypublic class Array{ public int []A = new int[10]; public int size; public int length; public Array(int []A, int size, int length) { this.A = A; this.size = size; this.length = length; }}; // Function to print the// array elementstatic void Display(Array arr){ int i; // Traverse the array []arr for (i = 0; i < arr.length; i++) { Console.Write(\" \" + arr.A[i]); } Console.Write(\"\\n\");} // Function that performs the// move to front operation for// Linear Searchstatic int LinearSearchMoveToFront(Array arr, int key){ int i; // Traverse the array for (i = 0; i < arr.length; i++) { // If key is found, then swap // the element with 0-th index if (key == arr.A[i]) { int temp = arr.A[i]; arr.A[i] = arr.A[0]; arr.A[0] = temp; return i; } } return -1;} // Driver codepublic static void Main(String[] args){ // Given array []arr int []a = {2, 23, 14, 5, 6, 9, 8, 12 }; Array arr = new Array(a, 10, 8); Console.Write(\"Elements before Linear\" + \" Search Move To Front: \"); // Function Call for // displaying the array // []arr Display(arr); // Function Call for Move // to front operation LinearSearchMoveToFront(arr, 14); Console.Write(\"Elements after Linear\" + \" Search Move To Front: \"); // Function Call for displaying // the array []arr Display(arr);}} // This code is contributed by gauravrajput1",
"e": 17082,
"s": 15463,
"text": null
},
{
"code": "# Python3 program for transposition to# improve the Linear Search Algorithm # Structure of the arrayclass Array : def __init__(self,a=[0]*10,size=10,l=0) -> None: self.A=a self.size=size self.length=l # Function to print array elementdef Display(arr): # Traverse the array arr[] for i in range(arr.length) : print(arr.A[i],end=\" \") print() # Function that performs the move to# front operation for Linear Searchdef LinearSearchMoveToFront(arr, key:int): # Traverse the array for i in range(arr.length) : # If key is found, then swap # the element with 0-th index if (key == arr.A[i]) : arr.A[i], arr.A[0]=arr.A[0],arr.A[i] return i return -1 # Driver Codeif __name__ == '__main__': # Given array arr[] arr=Array([2, 23, 14, 5, 6, 9, 8, 12], 10, 8) print(\"Elements before Linear Search Transposition: \",end='') # Function Call for displaying # the array arr[] Display(arr) # Function Call for transposition LinearSearchMoveToFront(arr, 14) print(\"Elements after Linear Search Transposition: \",end='') # Function Call for displaying # the array arr[] Display(arr)",
"e": 18302,
"s": 17082,
"text": null
},
{
"code": null,
"e": 18347,
"s": 18302,
"text": "Time Complexity: O(N) Auxiliary Space: O(1)"
},
{
"code": null,
"e": 18360,
"s": 18347,
"text": "princi singh"
},
{
"code": null,
"e": 18375,
"s": 18360,
"text": "amit143katiyar"
},
{
"code": null,
"e": 18389,
"s": 18375,
"text": "GauravRajput1"
},
{
"code": null,
"e": 18408,
"s": 18389,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 18424,
"s": 18408,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 18440,
"s": 18424,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 18457,
"s": 18440,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 18478,
"s": 18457,
"text": "Algorithms-Searching"
},
{
"code": null,
"e": 18489,
"s": 18478,
"text": "Algorithms"
},
{
"code": null,
"e": 18496,
"s": 18489,
"text": "Arrays"
},
{
"code": null,
"e": 18505,
"s": 18496,
"text": "Articles"
},
{
"code": null,
"e": 18521,
"s": 18505,
"text": "Data Structures"
},
{
"code": null,
"e": 18531,
"s": 18521,
"text": "Searching"
},
{
"code": null,
"e": 18547,
"s": 18531,
"text": "Data Structures"
},
{
"code": null,
"e": 18554,
"s": 18547,
"text": "Arrays"
},
{
"code": null,
"e": 18564,
"s": 18554,
"text": "Searching"
},
{
"code": null,
"e": 18575,
"s": 18564,
"text": "Algorithms"
},
{
"code": null,
"e": 18673,
"s": 18575,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 18698,
"s": 18673,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 18747,
"s": 18698,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 18785,
"s": 18747,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 18836,
"s": 18785,
"text": "Understanding Time Complexity with Simple Examples"
},
{
"code": null,
"e": 18904,
"s": 18836,
"text": "Find if there is a path between two vertices in an undirected graph"
},
{
"code": null,
"e": 18919,
"s": 18904,
"text": "Arrays in Java"
},
{
"code": null,
"e": 18951,
"s": 18919,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 18967,
"s": 18951,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 19073,
"s": 18967,
"text": "Find the smallest positive integer value that cannot be represented as sum of any subset of a given array"
}
] |
Socket Programming in C/C++: Handling multiple clients on server without multi threading | 28 Jun, 2022
This tutorial assumes you have a basic knowledge of socket programming, i.e you are familiar with basic server and client model. In the basic model, server handles only one client at a time, which is a big assumption if you want to develop any scalable server model.The simple way to handle multiple clients would be to spawn new thread for every new client connected to the server. This method is strongly not recommended because of various disadvantages, namely:
Threads are difficult to code, debug and sometimes they have unpredictable results.
Overhead switching of context
Not scalable for large number of clients
Deadlocks can occur
Select()
A better way to handle multiple clients is by using select() linux command.
Select command allows to monitor multiple file descriptors, waiting until one of the file descriptors become active.
For example, if there is some data to be read on one of the sockets select will provide that information.
Select works like an interrupt handler, which gets activated as soon as any file descriptor sends any data.
Data structure used for select: fd_setIt contains the list of file descriptors to monitor for some activity.There are four functions associated with fd_set:
fd_set readfds;
// Clear an fd_set
FD_ZERO(&readfds);
// Add a descriptor to an fd_set
FD_SET(master_sock, &readfds);
// Remove a descriptor from an fd_set
FD_CLR(master_sock, &readfds);
//If something happened on the master socket , then its an incoming connection
FD_ISSET(master_sock, &readfds);
Activating select: Please read the man page for select to check all the arguments for select command.
activity = select( max_fd + 1 , &readfds , NULL , NULL , NULL);
Implementation:
//Example code: A simple server side code, which echos back the received message.//Handle multiple socket connections with select and fd_set on Linux #include <stdio.h> #include <string.h> //strlen #include <stdlib.h> #include <errno.h> #include <unistd.h> //close #include <arpa/inet.h> //close #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <sys/time.h> //FD_SET, FD_ISSET, FD_ZERO macros #define TRUE 1 #define FALSE 0 #define PORT 8888 int main(int argc , char *argv[]) { int opt = TRUE; int master_socket , addrlen , new_socket , client_socket[30] , max_clients = 30 , activity, i , valread , sd; int max_sd; struct sockaddr_in address; char buffer[1025]; //data buffer of 1K //set of socket descriptors fd_set readfds; //a message char *message = "ECHO Daemon v1.0 \r\n"; //initialise all client_socket[] to 0 so not checked for (i = 0; i < max_clients; i++) { client_socket[i] = 0; } //create a master socket if( (master_socket = socket(AF_INET , SOCK_STREAM , 0)) == 0) { perror("socket failed"); exit(EXIT_FAILURE); } //set master socket to allow multiple connections , //this is just a good habit, it will work without this if( setsockopt(master_socket, SOL_SOCKET, SO_REUSEADDR, (char *)&opt, sizeof(opt)) < 0 ) { perror("setsockopt"); exit(EXIT_FAILURE); } //type of socket created address.sin_family = AF_INET; address.sin_addr.s_addr = INADDR_ANY; address.sin_port = htons( PORT ); //bind the socket to localhost port 8888 if (bind(master_socket, (struct sockaddr *)&address, sizeof(address))<0) { perror("bind failed"); exit(EXIT_FAILURE); } printf("Listener on port %d \n", PORT); //try to specify maximum of 3 pending connections for the master socket if (listen(master_socket, 3) < 0) { perror("listen"); exit(EXIT_FAILURE); } //accept the incoming connection addrlen = sizeof(address); puts("Waiting for connections ..."); while(TRUE) { //clear the socket set FD_ZERO(&readfds); //add master socket to set FD_SET(master_socket, &readfds); max_sd = master_socket; //add child sockets to set for ( i = 0 ; i < max_clients ; i++) { //socket descriptor sd = client_socket[i]; //if valid socket descriptor then add to read list if(sd > 0) FD_SET( sd , &readfds); //highest file descriptor number, need it for the select function if(sd > max_sd) max_sd = sd; } //wait for an activity on one of the sockets , timeout is NULL , //so wait indefinitely activity = select( max_sd + 1 , &readfds , NULL , NULL , NULL); if ((activity < 0) && (errno!=EINTR)) { printf("select error"); } //If something happened on the master socket , //then its an incoming connection if (FD_ISSET(master_socket, &readfds)) { if ((new_socket = accept(master_socket, (struct sockaddr *)&address, (socklen_t*)&addrlen))<0) { perror("accept"); exit(EXIT_FAILURE); } //inform user of socket number - used in send and receive commands printf("New connection , socket fd is %d , ip is : %s , port : %d \n" , new_socket , inet_ntoa(address.sin_addr) , ntohs (address.sin_port)); //send new connection greeting message if( send(new_socket, message, strlen(message), 0) != strlen(message) ) { perror("send"); } puts("Welcome message sent successfully"); //add new socket to array of sockets for (i = 0; i < max_clients; i++) { //if position is empty if( client_socket[i] == 0 ) { client_socket[i] = new_socket; printf("Adding to list of sockets as %d\n" , i); break; } } } //else its some IO operation on some other socket for (i = 0; i < max_clients; i++) { sd = client_socket[i]; if (FD_ISSET( sd , &readfds)) { //Check if it was for closing , and also read the //incoming message if ((valread = read( sd , buffer, 1024)) == 0) { //Somebody disconnected , get his details and print getpeername(sd , (struct sockaddr*)&address , \ (socklen_t*)&addrlen); printf("Host disconnected , ip %s , port %d \n" , inet_ntoa(address.sin_addr) , ntohs(address.sin_port)); //Close the socket and mark as 0 in list for reuse close( sd ); client_socket[i] = 0; } //Echo back the message that came in else { //set the string terminating NULL byte on the end //of the data read buffer[valread] = '\0'; send(sd , buffer , strlen(buffer) , 0 ); } } } } return 0; }
Compile the file and run the server.Use telnet to connect the server as a client.
Try running on different machines using following command:
telnet localhost 8888
Code Explanation:
We have created a fd_set variable readfds, which will monitor all the active file descriptors of the clients plus that of the main server listening socket.
Whenever a new client will connect, master_socket will be activated and a new fd will be open for that client. We will store its fd in our client_list and in the next iteration we will add it to the readfds to monitor for activity from this client.
Similarly, if an old client sends some data, readfds will be activated and we will check from the list of existing client to see which client has send the data.
Alternatives:There are other functions that can perform tasks similar to select. pselect , poll , ppoll
This article is contributed by Akshat 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.
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
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String 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": "\n28 Jun, 2022"
},
{
"code": null,
"e": 517,
"s": 52,
"text": "This tutorial assumes you have a basic knowledge of socket programming, i.e you are familiar with basic server and client model. In the basic model, server handles only one client at a time, which is a big assumption if you want to develop any scalable server model.The simple way to handle multiple clients would be to spawn new thread for every new client connected to the server. This method is strongly not recommended because of various disadvantages, namely:"
},
{
"code": null,
"e": 601,
"s": 517,
"text": "Threads are difficult to code, debug and sometimes they have unpredictable results."
},
{
"code": null,
"e": 631,
"s": 601,
"text": "Overhead switching of context"
},
{
"code": null,
"e": 672,
"s": 631,
"text": "Not scalable for large number of clients"
},
{
"code": null,
"e": 692,
"s": 672,
"text": "Deadlocks can occur"
},
{
"code": null,
"e": 701,
"s": 692,
"text": "Select()"
},
{
"code": null,
"e": 777,
"s": 701,
"text": "A better way to handle multiple clients is by using select() linux command."
},
{
"code": null,
"e": 894,
"s": 777,
"text": "Select command allows to monitor multiple file descriptors, waiting until one of the file descriptors become active."
},
{
"code": null,
"e": 1000,
"s": 894,
"text": "For example, if there is some data to be read on one of the sockets select will provide that information."
},
{
"code": null,
"e": 1108,
"s": 1000,
"text": "Select works like an interrupt handler, which gets activated as soon as any file descriptor sends any data."
},
{
"code": null,
"e": 1265,
"s": 1108,
"text": "Data structure used for select: fd_setIt contains the list of file descriptors to monitor for some activity.There are four functions associated with fd_set:"
},
{
"code": null,
"e": 1578,
"s": 1265,
"text": "fd_set readfds;\n\n// Clear an fd_set\nFD_ZERO(&readfds); \n\n// Add a descriptor to an fd_set\nFD_SET(master_sock, &readfds); \n\n// Remove a descriptor from an fd_set\nFD_CLR(master_sock, &readfds); \n\n//If something happened on the master socket , then its an incoming connection \nFD_ISSET(master_sock, &readfds); \n"
},
{
"code": null,
"e": 1680,
"s": 1578,
"text": "Activating select: Please read the man page for select to check all the arguments for select command."
},
{
"code": null,
"e": 1744,
"s": 1680,
"text": "activity = select( max_fd + 1 , &readfds , NULL , NULL , NULL);"
},
{
"code": null,
"e": 1760,
"s": 1744,
"text": "Implementation:"
},
{
"code": "//Example code: A simple server side code, which echos back the received message.//Handle multiple socket connections with select and fd_set on Linux #include <stdio.h> #include <string.h> //strlen #include <stdlib.h> #include <errno.h> #include <unistd.h> //close #include <arpa/inet.h> //close #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <sys/time.h> //FD_SET, FD_ISSET, FD_ZERO macros #define TRUE 1 #define FALSE 0 #define PORT 8888 int main(int argc , char *argv[]) { int opt = TRUE; int master_socket , addrlen , new_socket , client_socket[30] , max_clients = 30 , activity, i , valread , sd; int max_sd; struct sockaddr_in address; char buffer[1025]; //data buffer of 1K //set of socket descriptors fd_set readfds; //a message char *message = \"ECHO Daemon v1.0 \\r\\n\"; //initialise all client_socket[] to 0 so not checked for (i = 0; i < max_clients; i++) { client_socket[i] = 0; } //create a master socket if( (master_socket = socket(AF_INET , SOCK_STREAM , 0)) == 0) { perror(\"socket failed\"); exit(EXIT_FAILURE); } //set master socket to allow multiple connections , //this is just a good habit, it will work without this if( setsockopt(master_socket, SOL_SOCKET, SO_REUSEADDR, (char *)&opt, sizeof(opt)) < 0 ) { perror(\"setsockopt\"); exit(EXIT_FAILURE); } //type of socket created address.sin_family = AF_INET; address.sin_addr.s_addr = INADDR_ANY; address.sin_port = htons( PORT ); //bind the socket to localhost port 8888 if (bind(master_socket, (struct sockaddr *)&address, sizeof(address))<0) { perror(\"bind failed\"); exit(EXIT_FAILURE); } printf(\"Listener on port %d \\n\", PORT); //try to specify maximum of 3 pending connections for the master socket if (listen(master_socket, 3) < 0) { perror(\"listen\"); exit(EXIT_FAILURE); } //accept the incoming connection addrlen = sizeof(address); puts(\"Waiting for connections ...\"); while(TRUE) { //clear the socket set FD_ZERO(&readfds); //add master socket to set FD_SET(master_socket, &readfds); max_sd = master_socket; //add child sockets to set for ( i = 0 ; i < max_clients ; i++) { //socket descriptor sd = client_socket[i]; //if valid socket descriptor then add to read list if(sd > 0) FD_SET( sd , &readfds); //highest file descriptor number, need it for the select function if(sd > max_sd) max_sd = sd; } //wait for an activity on one of the sockets , timeout is NULL , //so wait indefinitely activity = select( max_sd + 1 , &readfds , NULL , NULL , NULL); if ((activity < 0) && (errno!=EINTR)) { printf(\"select error\"); } //If something happened on the master socket , //then its an incoming connection if (FD_ISSET(master_socket, &readfds)) { if ((new_socket = accept(master_socket, (struct sockaddr *)&address, (socklen_t*)&addrlen))<0) { perror(\"accept\"); exit(EXIT_FAILURE); } //inform user of socket number - used in send and receive commands printf(\"New connection , socket fd is %d , ip is : %s , port : %d \\n\" , new_socket , inet_ntoa(address.sin_addr) , ntohs (address.sin_port)); //send new connection greeting message if( send(new_socket, message, strlen(message), 0) != strlen(message) ) { perror(\"send\"); } puts(\"Welcome message sent successfully\"); //add new socket to array of sockets for (i = 0; i < max_clients; i++) { //if position is empty if( client_socket[i] == 0 ) { client_socket[i] = new_socket; printf(\"Adding to list of sockets as %d\\n\" , i); break; } } } //else its some IO operation on some other socket for (i = 0; i < max_clients; i++) { sd = client_socket[i]; if (FD_ISSET( sd , &readfds)) { //Check if it was for closing , and also read the //incoming message if ((valread = read( sd , buffer, 1024)) == 0) { //Somebody disconnected , get his details and print getpeername(sd , (struct sockaddr*)&address , \\ (socklen_t*)&addrlen); printf(\"Host disconnected , ip %s , port %d \\n\" , inet_ntoa(address.sin_addr) , ntohs(address.sin_port)); //Close the socket and mark as 0 in list for reuse close( sd ); client_socket[i] = 0; } //Echo back the message that came in else { //set the string terminating NULL byte on the end //of the data read buffer[valread] = '\\0'; send(sd , buffer , strlen(buffer) , 0 ); } } } } return 0; } ",
"e": 7776,
"s": 1760,
"text": null
},
{
"code": null,
"e": 7858,
"s": 7776,
"text": "Compile the file and run the server.Use telnet to connect the server as a client."
},
{
"code": null,
"e": 7917,
"s": 7858,
"text": "Try running on different machines using following command:"
},
{
"code": null,
"e": 7940,
"s": 7917,
"text": " telnet localhost 8888"
},
{
"code": null,
"e": 7958,
"s": 7940,
"text": "Code Explanation:"
},
{
"code": null,
"e": 8114,
"s": 7958,
"text": "We have created a fd_set variable readfds, which will monitor all the active file descriptors of the clients plus that of the main server listening socket."
},
{
"code": null,
"e": 8363,
"s": 8114,
"text": "Whenever a new client will connect, master_socket will be activated and a new fd will be open for that client. We will store its fd in our client_list and in the next iteration we will add it to the readfds to monitor for activity from this client."
},
{
"code": null,
"e": 8524,
"s": 8363,
"text": "Similarly, if an old client sends some data, readfds will be activated and we will check from the list of existing client to see which client has send the data."
},
{
"code": null,
"e": 8628,
"s": 8524,
"text": "Alternatives:There are other functions that can perform tasks similar to select. pselect , poll , ppoll"
},
{
"code": null,
"e": 8924,
"s": 8628,
"text": "This article is contributed by Akshat 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."
},
{
"code": null,
"e": 9049,
"s": 8924,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 9060,
"s": 9049,
"text": "C Language"
},
{
"code": null,
"e": 9064,
"s": 9060,
"text": "C++"
},
{
"code": null,
"e": 9068,
"s": 9064,
"text": "CPP"
},
{
"code": null,
"e": 9166,
"s": 9068,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9183,
"s": 9166,
"text": "Substring in C++"
},
{
"code": null,
"e": 9205,
"s": 9183,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 9240,
"s": 9205,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 9286,
"s": 9240,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 9331,
"s": 9286,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 9349,
"s": 9331,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 9392,
"s": 9349,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 9438,
"s": 9392,
"text": "Initialize a vector in C++ (7 different ways)"
},
{
"code": null,
"e": 9481,
"s": 9438,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
How to set Default Password Character in TextBox in C#? | 29 Nov, 2019
In Windows forms, TextBox plays an important role. With the help of TextBox, the user can enter data in the application, it can be of a single line or of multiple lines. In TextBox, you are allowed to set a value which represents whether the text in the TextBox control should appear as the default password character by using the UseSystemPasswordChar property of the TextBox. If you set the value of this property to true, then the text present in the TextBox control should appear as the default password character, otherwise set false. In Windows form, you can set this property in two different ways:
1. Design-Time: It is the simplest way to set the UseSystemPasswordChar property of the TextBox as shown in below steps:
Step 1: Create a windows form.Visual Studio -> File -> New -> Project -> WindowsFormApp
Step 2: Drag the TextBox control from the ToolBox and Drop it on the windows form. You can place TextBox anywhere on the windows form according to your need. As shown in the below image:
Step 3: After drag and drop you will go to the properties of the TextBox control to set the UseSystemPasswordChar property of the TextBox. As shown in the below image:Output:
Output:
2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the UseSystemPasswordChar property of the TextBox programmatically with the help of the given syntax:
public bool UseSystemPasswordChar { get; set; }
Here, the value of this property is of System.Boolean type. Following steps are used to set the UseSystemPasswordChar property of the TextBox:
Step 1 : Create a textbox using the TextBox() constructor provided by the TextBox class.// Creating textbox
TextBox Mytextbox = new TextBox();
// Creating textbox
TextBox Mytextbox = new TextBox();
Step 2 : After creating TextBox, set the UseSystemPasswordChar property of the TextBox provided by the TextBox class.// Set UseSystemPasswordChar property
Mytextbox.UseSystemPasswordChar = true;
// Set UseSystemPasswordChar property
Mytextbox.UseSystemPasswordChar = true;
Step 3 : And last add this textbox control to from using Add() method.// Add this textbox to form
this.Controls.Add(Mytextbox);
Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace my { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of Lable1 Label Mylablel = new Label(); Mylablel.Location = new Point(96, 54); Mylablel.Text = "Enter Password"; Mylablel.AutoSize = true; Mylablel.BackColor = Color.LightGray; // Add this label to form this.Controls.Add(Mylablel); // Creating and setting the properties of TextBox1 TextBox Mytextbox = new TextBox(); Mytextbox.Location = new Point(187, 51); Mytextbox.BackColor = Color.LightGray; Mytextbox.ForeColor = Color.DarkOliveGreen; Mytextbox.AutoSize = true; Mytextbox.Name = "text_box1"; Mytextbox.UseSystemPasswordChar = true; // Add this textbox to form this.Controls.Add(Mytextbox); }}}Output:
// Add this textbox to form
this.Controls.Add(Mytextbox);
Example:
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace my { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of Lable1 Label Mylablel = new Label(); Mylablel.Location = new Point(96, 54); Mylablel.Text = "Enter Password"; Mylablel.AutoSize = true; Mylablel.BackColor = Color.LightGray; // Add this label to form this.Controls.Add(Mylablel); // Creating and setting the properties of TextBox1 TextBox Mytextbox = new TextBox(); Mytextbox.Location = new Point(187, 51); Mytextbox.BackColor = Color.LightGray; Mytextbox.ForeColor = Color.DarkOliveGreen; Mytextbox.AutoSize = true; Mytextbox.Name = "text_box1"; Mytextbox.UseSystemPasswordChar = true; // Add this textbox to form this.Controls.Add(Mytextbox); }}}
Output:
CSharp-Windows-Forms-Namespace
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Nov, 2019"
},
{
"code": null,
"e": 634,
"s": 28,
"text": "In Windows forms, TextBox plays an important role. With the help of TextBox, the user can enter data in the application, it can be of a single line or of multiple lines. In TextBox, you are allowed to set a value which represents whether the text in the TextBox control should appear as the default password character by using the UseSystemPasswordChar property of the TextBox. If you set the value of this property to true, then the text present in the TextBox control should appear as the default password character, otherwise set false. In Windows form, you can set this property in two different ways:"
},
{
"code": null,
"e": 755,
"s": 634,
"text": "1. Design-Time: It is the simplest way to set the UseSystemPasswordChar property of the TextBox as shown in below steps:"
},
{
"code": null,
"e": 843,
"s": 755,
"text": "Step 1: Create a windows form.Visual Studio -> File -> New -> Project -> WindowsFormApp"
},
{
"code": null,
"e": 1030,
"s": 843,
"text": "Step 2: Drag the TextBox control from the ToolBox and Drop it on the windows form. You can place TextBox anywhere on the windows form according to your need. As shown in the below image:"
},
{
"code": null,
"e": 1205,
"s": 1030,
"text": "Step 3: After drag and drop you will go to the properties of the TextBox control to set the UseSystemPasswordChar property of the TextBox. As shown in the below image:Output:"
},
{
"code": null,
"e": 1213,
"s": 1205,
"text": "Output:"
},
{
"code": null,
"e": 1407,
"s": 1213,
"text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the UseSystemPasswordChar property of the TextBox programmatically with the help of the given syntax:"
},
{
"code": null,
"e": 1455,
"s": 1407,
"text": "public bool UseSystemPasswordChar { get; set; }"
},
{
"code": null,
"e": 1598,
"s": 1455,
"text": "Here, the value of this property is of System.Boolean type. Following steps are used to set the UseSystemPasswordChar property of the TextBox:"
},
{
"code": null,
"e": 1742,
"s": 1598,
"text": "Step 1 : Create a textbox using the TextBox() constructor provided by the TextBox class.// Creating textbox\nTextBox Mytextbox = new TextBox();\n"
},
{
"code": null,
"e": 1798,
"s": 1742,
"text": "// Creating textbox\nTextBox Mytextbox = new TextBox();\n"
},
{
"code": null,
"e": 1994,
"s": 1798,
"text": "Step 2 : After creating TextBox, set the UseSystemPasswordChar property of the TextBox provided by the TextBox class.// Set UseSystemPasswordChar property\nMytextbox.UseSystemPasswordChar = true;\n"
},
{
"code": null,
"e": 2073,
"s": 1994,
"text": "// Set UseSystemPasswordChar property\nMytextbox.UseSystemPasswordChar = true;\n"
},
{
"code": null,
"e": 3374,
"s": 2073,
"text": "Step 3 : And last add this textbox control to from using Add() method.// Add this textbox to form\nthis.Controls.Add(Mytextbox);\nExample:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace my { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of Lable1 Label Mylablel = new Label(); Mylablel.Location = new Point(96, 54); Mylablel.Text = \"Enter Password\"; Mylablel.AutoSize = true; Mylablel.BackColor = Color.LightGray; // Add this label to form this.Controls.Add(Mylablel); // Creating and setting the properties of TextBox1 TextBox Mytextbox = new TextBox(); Mytextbox.Location = new Point(187, 51); Mytextbox.BackColor = Color.LightGray; Mytextbox.ForeColor = Color.DarkOliveGreen; Mytextbox.AutoSize = true; Mytextbox.Name = \"text_box1\"; Mytextbox.UseSystemPasswordChar = true; // Add this textbox to form this.Controls.Add(Mytextbox); }}}Output:"
},
{
"code": null,
"e": 3433,
"s": 3374,
"text": "// Add this textbox to form\nthis.Controls.Add(Mytextbox);\n"
},
{
"code": null,
"e": 3442,
"s": 3433,
"text": "Example:"
},
{
"code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace my { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of Lable1 Label Mylablel = new Label(); Mylablel.Location = new Point(96, 54); Mylablel.Text = \"Enter Password\"; Mylablel.AutoSize = true; Mylablel.BackColor = Color.LightGray; // Add this label to form this.Controls.Add(Mylablel); // Creating and setting the properties of TextBox1 TextBox Mytextbox = new TextBox(); Mytextbox.Location = new Point(187, 51); Mytextbox.BackColor = Color.LightGray; Mytextbox.ForeColor = Color.DarkOliveGreen; Mytextbox.AutoSize = true; Mytextbox.Name = \"text_box1\"; Mytextbox.UseSystemPasswordChar = true; // Add this textbox to form this.Controls.Add(Mytextbox); }}}",
"e": 4600,
"s": 3442,
"text": null
},
{
"code": null,
"e": 4608,
"s": 4600,
"text": "Output:"
},
{
"code": null,
"e": 4639,
"s": 4608,
"text": "CSharp-Windows-Forms-Namespace"
},
{
"code": null,
"e": 4642,
"s": 4639,
"text": "C#"
}
] |
LESS - Fade | It is used to set the transparency of a color for selected elements. It has following parameters −
color − It represents color object.
color − It represents color object.
amount − It contains percentage between 0 - 100%.
amount − It contains percentage between 0 - 100%.
The following example demonstrates the use of fade color operation in the LESS file −
<html>
<head>
<title>Fade</title>
<link rel = "stylesheet" type = "text/css" href = "style.css"/>
</head>
<body>
<h2>Example of Fade Color Operation</h2>
<div class = "myclass1">
<p>color :<br>#426105</p>
</div><br>
<div class = "myclass2">
<p>result :<br>rgba(66, 97, 5, 0.1)</p>
</div>
</body>
</html>
Next, create the style.less file.
.myclass1 {
height:100px;
width:100px;
padding: 30px 0px 0px 25px;
background-color: hsl(80, 90%, 20%);
color:white;
}
.myclass2 {
height:100px;
width:100px;
padding: 30px 0px 0px 25px;
background-color: fade(hsl(80, 90%, 20%), 10%);
color:black;
}
You can compile the style.less to style.css by using the following command −
lessc style.less style.css
Execute the above command; it will create the style.css file automatically with the following code −
.myclass1 {
height: 100px;
width: 100px;
padding: 30px 0px 0px 25px;
background-color: #426105;
color: white;
}
.myclass2 {
height: 100px;
width: 100px;
padding: 30px 0px 0px 25px;
background-color: rgba(66, 97, 5, 0.1);
color: black;
}
Follow these steps to see how the above code works −
Save above code in fade.html file.
Save above code in fade.html file.
Open this HTML file in a browser, the following output will get displayed.
Open this HTML file in a browser, the following output will get displayed.
20 Lectures
1 hours
Anadi Sharma
44 Lectures
7.5 hours
Eduonix Learning Solutions
17 Lectures
2 hours
Zach Miller
23 Lectures
1.5 hours
Zach Miller
34 Lectures
4 hours
Syed Raza
31 Lectures
3 hours
Harshit Srivastava
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2649,
"s": 2550,
"text": "It is used to set the transparency of a color for selected elements. It has following parameters −"
},
{
"code": null,
"e": 2685,
"s": 2649,
"text": "color − It represents color object."
},
{
"code": null,
"e": 2721,
"s": 2685,
"text": "color − It represents color object."
},
{
"code": null,
"e": 2771,
"s": 2721,
"text": "amount − It contains percentage between 0 - 100%."
},
{
"code": null,
"e": 2821,
"s": 2771,
"text": "amount − It contains percentage between 0 - 100%."
},
{
"code": null,
"e": 2907,
"s": 2821,
"text": "The following example demonstrates the use of fade color operation in the LESS file −"
},
{
"code": null,
"e": 3285,
"s": 2907,
"text": "<html>\n <head>\n <title>Fade</title>\n <link rel = \"stylesheet\" type = \"text/css\" href = \"style.css\"/>\n </head>\n\n <body>\n <h2>Example of Fade Color Operation</h2>\n <div class = \"myclass1\">\n <p>color :<br>#426105</p>\n </div><br>\n\n <div class = \"myclass2\">\n <p>result :<br>rgba(66, 97, 5, 0.1)</p>\n </div>\n </body>\n</html>"
},
{
"code": null,
"e": 3319,
"s": 3285,
"text": "Next, create the style.less file."
},
{
"code": null,
"e": 3599,
"s": 3319,
"text": ".myclass1 {\n height:100px;\n width:100px;\n padding: 30px 0px 0px 25px;\n background-color: hsl(80, 90%, 20%);\n color:white;\n}\n\n.myclass2 {\n height:100px;\n width:100px;\n padding: 30px 0px 0px 25px;\n background-color: fade(hsl(80, 90%, 20%), 10%);\n color:black;\n}"
},
{
"code": null,
"e": 3676,
"s": 3599,
"text": "You can compile the style.less to style.css by using the following command −"
},
{
"code": null,
"e": 3704,
"s": 3676,
"text": "lessc style.less style.css\n"
},
{
"code": null,
"e": 3805,
"s": 3704,
"text": "Execute the above command; it will create the style.css file automatically with the following code −"
},
{
"code": null,
"e": 4073,
"s": 3805,
"text": ".myclass1 {\n height: 100px;\n width: 100px;\n padding: 30px 0px 0px 25px;\n background-color: #426105;\n color: white;\n}\n\n.myclass2 {\n height: 100px;\n width: 100px;\n padding: 30px 0px 0px 25px;\n background-color: rgba(66, 97, 5, 0.1);\n color: black;\n}"
},
{
"code": null,
"e": 4126,
"s": 4073,
"text": "Follow these steps to see how the above code works −"
},
{
"code": null,
"e": 4161,
"s": 4126,
"text": "Save above code in fade.html file."
},
{
"code": null,
"e": 4196,
"s": 4161,
"text": "Save above code in fade.html file."
},
{
"code": null,
"e": 4271,
"s": 4196,
"text": "Open this HTML file in a browser, the following output will get displayed."
},
{
"code": null,
"e": 4346,
"s": 4271,
"text": "Open this HTML file in a browser, the following output will get displayed."
},
{
"code": null,
"e": 4379,
"s": 4346,
"text": "\n 20 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4393,
"s": 4379,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4428,
"s": 4393,
"text": "\n 44 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 4456,
"s": 4428,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4489,
"s": 4456,
"text": "\n 17 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4502,
"s": 4489,
"text": " Zach Miller"
},
{
"code": null,
"e": 4537,
"s": 4502,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4550,
"s": 4537,
"text": " Zach Miller"
},
{
"code": null,
"e": 4583,
"s": 4550,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4594,
"s": 4583,
"text": " Syed Raza"
},
{
"code": null,
"e": 4627,
"s": 4594,
"text": "\n 31 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 4647,
"s": 4627,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 4654,
"s": 4647,
"text": " Print"
},
{
"code": null,
"e": 4665,
"s": 4654,
"text": " Add Notes"
}
] |
Custom ArrayList in Java | A custom ArrayList can have multiple types of data and its attributes in general are based on the user requirements.
A program that demonstrates a custom ArrayList is given as follows −
Live Demo
import java.util.ArrayList;
public class CustomArrayList {
int n = 5;
class Employee {
int eno;
String name;
Employee(int eno, String name) {
this.eno = eno;
this.name = name;
}
}
public static void main(String args[]) {
int eno[] = {101, 102, 103, 104, 105};
String name[] = {"Jane", "Mary", "Adam", "Harry", "John"};
CustomArrayList caList = new CustomArrayList();
caList.add(eno, name);
}
public void add(int eno[], String name[]) {
ArrayList<Employee> aList = new ArrayList<>();
for (int i = 0; i < n; i++) {
aList.add(new Employee(eno[i], name[i]));
}
print(aList);
}
public void print(ArrayList<Employee> aList) {
for (int i = 0; i < n; i++) {
Employee e = aList.get(i);
System.out.println("\nEmployee Number: " + e.eno);
System.out.println("Employee Name: " + e.name);
}
}
}
The output of the above program is as follows −
Employee Number: 101
Employee Name: Jane
Employee Number: 102
Employee Name: Mary
Employee Number: 103
Employee Name: Adam
Employee Number: 104
Employee Name: Harry
Employee Number: 105
Employee Name: John | [
{
"code": null,
"e": 1179,
"s": 1062,
"text": "A custom ArrayList can have multiple types of data and its attributes in general are based on the user requirements."
},
{
"code": null,
"e": 1248,
"s": 1179,
"text": "A program that demonstrates a custom ArrayList is given as follows −"
},
{
"code": null,
"e": 1259,
"s": 1248,
"text": " Live Demo"
},
{
"code": null,
"e": 2206,
"s": 1259,
"text": "import java.util.ArrayList;\npublic class CustomArrayList {\n int n = 5;\n class Employee {\n int eno;\n String name;\n Employee(int eno, String name) {\n this.eno = eno;\n this.name = name;\n }\n }\n public static void main(String args[]) {\n int eno[] = {101, 102, 103, 104, 105};\n String name[] = {\"Jane\", \"Mary\", \"Adam\", \"Harry\", \"John\"};\n CustomArrayList caList = new CustomArrayList();\n caList.add(eno, name);\n }\n public void add(int eno[], String name[]) {\n ArrayList<Employee> aList = new ArrayList<>();\n for (int i = 0; i < n; i++) {\n aList.add(new Employee(eno[i], name[i]));\n }\n print(aList);\n }\n public void print(ArrayList<Employee> aList) {\n for (int i = 0; i < n; i++) {\n Employee e = aList.get(i);\n System.out.println(\"\\nEmployee Number: \" + e.eno);\n System.out.println(\"Employee Name: \" + e.name);\n }\n }\n}"
},
{
"code": null,
"e": 2254,
"s": 2206,
"text": "The output of the above program is as follows −"
},
{
"code": null,
"e": 2464,
"s": 2254,
"text": "Employee Number: 101\nEmployee Name: Jane\n\nEmployee Number: 102\nEmployee Name: Mary\n\nEmployee Number: 103\nEmployee Name: Adam\n\nEmployee Number: 104\nEmployee Name: Harry\n\nEmployee Number: 105\nEmployee Name: John"
}
] |
Generate all the binary strings of N bits - GeeksforGeeks | 12 Jul, 2021
Given a positive integer number N. The task is to generate all the binary strings of N bits. These binary strings should be in ascending order.Examples:
Input: 2
Output:
0 0
0 1
1 0
1 1
Input: 3
Output:
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
Approach: The idea is to try every permutation. For every position, there are 2 options, either ‘0’ or ‘1’. Backtracking is used in this approach to try every possibility/permutation. Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of the above approach: #include <bits/stdc++.h>using namespace std; // Function to print the outputvoid printTheArray(int arr[], int n){ for (int i = 0; i < n; i++) { cout << arr[i] << " "; } cout << endl;} // Function to generate all binary stringsvoid generateAllBinaryStrings(int n, int arr[], int i){ if (i == n) { printTheArray(arr, n); return; } // First assign "0" at ith position // and try for all other permutations // for remaining positions arr[i] = 0; generateAllBinaryStrings(n, arr, i + 1); // And then assign "1" at ith position // and try for all other permutations // for remaining positions arr[i] = 1; generateAllBinaryStrings(n, arr, i + 1);} // Driver Codeint main(){ int n = 4; int arr[n]; // Print all binary strings generateAllBinaryStrings(n, arr, 0); return 0;}
// Java implementation of the above approach:import java.util.*; class GFG{ // Function to print the outputstatic void printTheArray(int arr[], int n){ for (int i = 0; i < n; i++) { System.out.print(arr[i]+" "); } System.out.println();} // Function to generate all binary stringsstatic void generateAllBinaryStrings(int n, int arr[], int i){ if (i == n) { printTheArray(arr, n); return; } // First assign "0" at ith position // and try for all other permutations // for remaining positions arr[i] = 0; generateAllBinaryStrings(n, arr, i + 1); // And then assign "1" at ith position // and try for all other permutations // for remaining positions arr[i] = 1; generateAllBinaryStrings(n, arr, i + 1);} // Driver Codepublic static void main(String args[]){ int n = 4; int[] arr = new int[n]; // Print all binary strings generateAllBinaryStrings(n, arr, 0);}} // This code is contributed by// Surendra_Gangwar
# Python3 implementation of the# above approach # Function to print the outputdef printTheArray(arr, n): for i in range(0, n): print(arr[i], end = " ") print() # Function to generate all binary stringsdef generateAllBinaryStrings(n, arr, i): if i == n: printTheArray(arr, n) return # First assign "0" at ith position # and try for all other permutations # for remaining positions arr[i] = 0 generateAllBinaryStrings(n, arr, i + 1) # And then assign "1" at ith position # and try for all other permutations # for remaining positions arr[i] = 1 generateAllBinaryStrings(n, arr, i + 1) # Driver Codeif __name__ == "__main__": n = 4 arr = [None] * n # Print all binary strings generateAllBinaryStrings(n, arr, 0) # This code is contributed# by Rituraj Jain
// C# implementation of the above approach:using System; class GFG{ // Function to print the outputstatic void printTheArray(int []arr, int n){ for (int i = 0; i < n; i++) { Console.Write(arr[i]+" "); } Console.WriteLine();} // Function to generate all binary stringsstatic void generateAllBinaryStrings(int n, int []arr, int i){ if (i == n) { printTheArray(arr, n); return; } // First assign "0" at ith position // and try for all other permutations // for remaining positions arr[i] = 0; generateAllBinaryStrings(n, arr, i + 1); // And then assign "1" at ith position // and try for all other permutations // for remaining positions arr[i] = 1; generateAllBinaryStrings(n, arr, i + 1);} // Driver Codepublic static void Main(String []args){ int n = 4; int[] arr = new int[n]; // Print all binary strings generateAllBinaryStrings(n, arr, 0);}} // This code has been contributed by 29AjayKumar
<?php// PHP implementation of the above approach // Function to print the outputfunction printTheArray($arr, $n){ for ($i = 0; $i < $n; $i++) { echo $arr[$i], " "; } echo "\n";} // Function to generate all binary stringsfunction generateAllBinaryStrings($n, $arr, $i){ if ($i == $n) { printTheArray($arr, $n); return; } // First assign "0" at ith position // and try for all other permutations // for remaining positions $arr[$i] = 0; generateAllBinaryStrings($n, $arr, $i + 1); // And then assign "1" at ith position // and try for all other permutations // for remaining positions $arr[$i] = 1; generateAllBinaryStrings($n, $arr, $i + 1);} // Driver Code$n = 4; $arr = array_fill(0, $n, 0); // Print all binary stringsgenerateAllBinaryStrings($n, $arr, 0); // This code is contributed by Ryuga?>
<script> // Javascript implementation of the above approach: // Function to print the output function printTheArray(arr, n) { for (let i = 0; i < n; i++) { document.write(arr[i]+" "); } document.write("</br>"); } // Function to generate all binary strings function generateAllBinaryStrings(n, arr, i) { if (i == n) { printTheArray(arr, n); return; } // First assign "0" at ith position // and try for all other permutations // for remaining positions arr[i] = 0; generateAllBinaryStrings(n, arr, i + 1); // And then assign "1" at ith position // and try for all other permutations // for remaining positions arr[i] = 1; generateAllBinaryStrings(n, arr, i + 1); } let n = 4; let arr = new Array(n); arr.fill(0); // Print all binary strings generateAllBinaryStrings(n, arr, 0); // This code is contributed by divyeshrabadiya07.</script>
0 0 0 0
0 0 0 1
0 0 1 0
0 0 1 1
0 1 0 0
0 1 0 1
0 1 1 0
0 1 1 1
1 0 0 0
1 0 0 1
1 0 1 0
1 0 1 1
1 1 0 0
1 1 0 1
1 1 1 0
1 1 1 1
Time complexity – O(2n)
Space complexity – O(n)
Related Article: Generate all the binary number from 0 to n
rituraj_jain
ankthon
SURENDRA_GANGWAR
29AjayKumar
divyeshrabadiya07
abhinavjain194
binary-string
Backtracking
C++
Recursion
Recursion
Backtracking
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Subset Sum | Backtracking-4
m Coloring Problem | Backtracking-5
Hamiltonian Cycle | Backtracking-6
Print all permutations of a string in Java
Backtracking to find all subsets
Vector in C++ STL
Arrays in C/C++
Inheritance in C++
Initialize a vector in C++ (6 different ways)
Socket Programming in C/C++ | [
{
"code": null,
"e": 25278,
"s": 25250,
"text": "\n12 Jul, 2021"
},
{
"code": null,
"e": 25433,
"s": 25278,
"text": "Given a positive integer number N. The task is to generate all the binary strings of N bits. These binary strings should be in ascending order.Examples: "
},
{
"code": null,
"e": 25532,
"s": 25433,
"text": "Input: 2\nOutput:\n0 0\n0 1\n1 0\n1 1\n\nInput: 3\nOutput:\n0 0 0\n0 0 1\n0 1 0\n0 1 1\n1 0 0\n1 0 1\n1 1 0\n1 1 1"
},
{
"code": null,
"e": 25770,
"s": 25534,
"text": "Approach: The idea is to try every permutation. For every position, there are 2 options, either ‘0’ or ‘1’. Backtracking is used in this approach to try every possibility/permutation. Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25774,
"s": 25770,
"text": "C++"
},
{
"code": null,
"e": 25779,
"s": 25774,
"text": "Java"
},
{
"code": null,
"e": 25787,
"s": 25779,
"text": "Python3"
},
{
"code": null,
"e": 25790,
"s": 25787,
"text": "C#"
},
{
"code": null,
"e": 25794,
"s": 25790,
"text": "PHP"
},
{
"code": null,
"e": 25805,
"s": 25794,
"text": "Javascript"
},
{
"code": "// C++ implementation of the above approach: #include <bits/stdc++.h>using namespace std; // Function to print the outputvoid printTheArray(int arr[], int n){ for (int i = 0; i < n; i++) { cout << arr[i] << \" \"; } cout << endl;} // Function to generate all binary stringsvoid generateAllBinaryStrings(int n, int arr[], int i){ if (i == n) { printTheArray(arr, n); return; } // First assign \"0\" at ith position // and try for all other permutations // for remaining positions arr[i] = 0; generateAllBinaryStrings(n, arr, i + 1); // And then assign \"1\" at ith position // and try for all other permutations // for remaining positions arr[i] = 1; generateAllBinaryStrings(n, arr, i + 1);} // Driver Codeint main(){ int n = 4; int arr[n]; // Print all binary strings generateAllBinaryStrings(n, arr, 0); return 0;}",
"e": 26702,
"s": 25805,
"text": null
},
{
"code": "// Java implementation of the above approach:import java.util.*; class GFG{ // Function to print the outputstatic void printTheArray(int arr[], int n){ for (int i = 0; i < n; i++) { System.out.print(arr[i]+\" \"); } System.out.println();} // Function to generate all binary stringsstatic void generateAllBinaryStrings(int n, int arr[], int i){ if (i == n) { printTheArray(arr, n); return; } // First assign \"0\" at ith position // and try for all other permutations // for remaining positions arr[i] = 0; generateAllBinaryStrings(n, arr, i + 1); // And then assign \"1\" at ith position // and try for all other permutations // for remaining positions arr[i] = 1; generateAllBinaryStrings(n, arr, i + 1);} // Driver Codepublic static void main(String args[]){ int n = 4; int[] arr = new int[n]; // Print all binary strings generateAllBinaryStrings(n, arr, 0);}} // This code is contributed by// Surendra_Gangwar",
"e": 27724,
"s": 26702,
"text": null
},
{
"code": "# Python3 implementation of the# above approach # Function to print the outputdef printTheArray(arr, n): for i in range(0, n): print(arr[i], end = \" \") print() # Function to generate all binary stringsdef generateAllBinaryStrings(n, arr, i): if i == n: printTheArray(arr, n) return # First assign \"0\" at ith position # and try for all other permutations # for remaining positions arr[i] = 0 generateAllBinaryStrings(n, arr, i + 1) # And then assign \"1\" at ith position # and try for all other permutations # for remaining positions arr[i] = 1 generateAllBinaryStrings(n, arr, i + 1) # Driver Codeif __name__ == \"__main__\": n = 4 arr = [None] * n # Print all binary strings generateAllBinaryStrings(n, arr, 0) # This code is contributed# by Rituraj Jain",
"e": 28564,
"s": 27724,
"text": null
},
{
"code": "// C# implementation of the above approach:using System; class GFG{ // Function to print the outputstatic void printTheArray(int []arr, int n){ for (int i = 0; i < n; i++) { Console.Write(arr[i]+\" \"); } Console.WriteLine();} // Function to generate all binary stringsstatic void generateAllBinaryStrings(int n, int []arr, int i){ if (i == n) { printTheArray(arr, n); return; } // First assign \"0\" at ith position // and try for all other permutations // for remaining positions arr[i] = 0; generateAllBinaryStrings(n, arr, i + 1); // And then assign \"1\" at ith position // and try for all other permutations // for remaining positions arr[i] = 1; generateAllBinaryStrings(n, arr, i + 1);} // Driver Codepublic static void Main(String []args){ int n = 4; int[] arr = new int[n]; // Print all binary strings generateAllBinaryStrings(n, arr, 0);}} // This code has been contributed by 29AjayKumar",
"e": 29573,
"s": 28564,
"text": null
},
{
"code": "<?php// PHP implementation of the above approach // Function to print the outputfunction printTheArray($arr, $n){ for ($i = 0; $i < $n; $i++) { echo $arr[$i], \" \"; } echo \"\\n\";} // Function to generate all binary stringsfunction generateAllBinaryStrings($n, $arr, $i){ if ($i == $n) { printTheArray($arr, $n); return; } // First assign \"0\" at ith position // and try for all other permutations // for remaining positions $arr[$i] = 0; generateAllBinaryStrings($n, $arr, $i + 1); // And then assign \"1\" at ith position // and try for all other permutations // for remaining positions $arr[$i] = 1; generateAllBinaryStrings($n, $arr, $i + 1);} // Driver Code$n = 4; $arr = array_fill(0, $n, 0); // Print all binary stringsgenerateAllBinaryStrings($n, $arr, 0); // This code is contributed by Ryuga?>",
"e": 30445,
"s": 29573,
"text": null
},
{
"code": "<script> // Javascript implementation of the above approach: // Function to print the output function printTheArray(arr, n) { for (let i = 0; i < n; i++) { document.write(arr[i]+\" \"); } document.write(\"</br>\"); } // Function to generate all binary strings function generateAllBinaryStrings(n, arr, i) { if (i == n) { printTheArray(arr, n); return; } // First assign \"0\" at ith position // and try for all other permutations // for remaining positions arr[i] = 0; generateAllBinaryStrings(n, arr, i + 1); // And then assign \"1\" at ith position // and try for all other permutations // for remaining positions arr[i] = 1; generateAllBinaryStrings(n, arr, i + 1); } let n = 4; let arr = new Array(n); arr.fill(0); // Print all binary strings generateAllBinaryStrings(n, arr, 0); // This code is contributed by divyeshrabadiya07.</script>",
"e": 31493,
"s": 30445,
"text": null
},
{
"code": null,
"e": 31636,
"s": 31493,
"text": "0 0 0 0 \n0 0 0 1 \n0 0 1 0 \n0 0 1 1 \n0 1 0 0 \n0 1 0 1 \n0 1 1 0 \n0 1 1 1 \n1 0 0 0 \n1 0 0 1 \n1 0 1 0 \n1 0 1 1 \n1 1 0 0 \n1 1 0 1 \n1 1 1 0 \n1 1 1 1"
},
{
"code": null,
"e": 31662,
"s": 31638,
"text": "Time complexity – O(2n)"
},
{
"code": null,
"e": 31686,
"s": 31662,
"text": "Space complexity – O(n)"
},
{
"code": null,
"e": 31747,
"s": 31686,
"text": "Related Article: Generate all the binary number from 0 to n "
},
{
"code": null,
"e": 31760,
"s": 31747,
"text": "rituraj_jain"
},
{
"code": null,
"e": 31768,
"s": 31760,
"text": "ankthon"
},
{
"code": null,
"e": 31785,
"s": 31768,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 31797,
"s": 31785,
"text": "29AjayKumar"
},
{
"code": null,
"e": 31815,
"s": 31797,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 31830,
"s": 31815,
"text": "abhinavjain194"
},
{
"code": null,
"e": 31844,
"s": 31830,
"text": "binary-string"
},
{
"code": null,
"e": 31857,
"s": 31844,
"text": "Backtracking"
},
{
"code": null,
"e": 31861,
"s": 31857,
"text": "C++"
},
{
"code": null,
"e": 31871,
"s": 31861,
"text": "Recursion"
},
{
"code": null,
"e": 31881,
"s": 31871,
"text": "Recursion"
},
{
"code": null,
"e": 31894,
"s": 31881,
"text": "Backtracking"
},
{
"code": null,
"e": 31898,
"s": 31894,
"text": "CPP"
},
{
"code": null,
"e": 31996,
"s": 31898,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32005,
"s": 31996,
"text": "Comments"
},
{
"code": null,
"e": 32018,
"s": 32005,
"text": "Old Comments"
},
{
"code": null,
"e": 32046,
"s": 32018,
"text": "Subset Sum | Backtracking-4"
},
{
"code": null,
"e": 32082,
"s": 32046,
"text": "m Coloring Problem | Backtracking-5"
},
{
"code": null,
"e": 32117,
"s": 32082,
"text": "Hamiltonian Cycle | Backtracking-6"
},
{
"code": null,
"e": 32160,
"s": 32117,
"text": "Print all permutations of a string in Java"
},
{
"code": null,
"e": 32193,
"s": 32160,
"text": "Backtracking to find all subsets"
},
{
"code": null,
"e": 32211,
"s": 32193,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 32227,
"s": 32211,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 32246,
"s": 32227,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 32292,
"s": 32246,
"text": "Initialize a vector in C++ (6 different ways)"
}
] |
MongoDB $arrayElemAt Operator | 09 Dec, 2021
MongoDB provides different types of array expression operators that are used in the aggregation pipeline stages and $arrayElemAt operator is one of them. This operator is used to return the element present on the specified index of the given array.
Syntax:
{ $arrayElemAt: [ <array>, <index> ] }
Here, the array must be a valid expression until it resolves to an array and index must be a valid expression until it resolves to an integer.
If the value of index is positive, then this operator will return the element at the index position, from the start of the array.
If the value of index is negative, then this operator will return the element at the index position, from the end of the array.
If the index exceeds the array bounds, then this operator does not return any result.
Examples:
In the following examples, we are working with:
Database: GeeksforGeeks
Collection: arrayExample
Document: three documents that contain the details in the form of field-value pairs.
Using $arrayElemAt Operator:
In this example, we are going to find the elements of the array(i.e., the value of fruits field) on the specified index using $arrayElemAt operator.
db.arrayExample.aggregate([
... {$match: {name: "Bongo"}},
... {$project: {
... firstItem: {$arrayElemAt: ["$fruits", 0]},
... lastItem: {$arrayElemAt: ["$fruits", -1]}}}])
Using $arrayElemAt Operator in the Embedded Document:
In this example, we are going to find the elements of the array(i.e., the value of favGame.outdoorGames field) on the specified index using $arrayElemAt operator.
db.arrayExample.aggregate([
... {$match: {name: "Piku"}},
... {$project: {
... firstItem: {$arrayElemAt: ["$favGame.outdoorGames", 0]},
... item: {$arrayElemAt: ["$favGame.outdoorGames", 2]}}}])
as5853535
MongoDB-operators
MongoDB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to connect MongoDB with ReactJS ?
MongoDB - limit() Method
MongoDB - sort() Method
MongoDB - FindOne() Method
MongoDB updateOne() Method - db.Collection.updateOne()
MongoDB - Regex
MongoDB - Compound Indexes
MongoDB updateMany() Method - db.Collection.updateMany()
MongoDB Cursor
Mongoose | update() Function | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 Dec, 2021"
},
{
"code": null,
"e": 278,
"s": 28,
"text": "MongoDB provides different types of array expression operators that are used in the aggregation pipeline stages and $arrayElemAt operator is one of them. This operator is used to return the element present on the specified index of the given array. "
},
{
"code": null,
"e": 287,
"s": 278,
"text": "Syntax: "
},
{
"code": null,
"e": 326,
"s": 287,
"text": "{ $arrayElemAt: [ <array>, <index> ] }"
},
{
"code": null,
"e": 469,
"s": 326,
"text": "Here, the array must be a valid expression until it resolves to an array and index must be a valid expression until it resolves to an integer."
},
{
"code": null,
"e": 599,
"s": 469,
"text": "If the value of index is positive, then this operator will return the element at the index position, from the start of the array."
},
{
"code": null,
"e": 727,
"s": 599,
"text": "If the value of index is negative, then this operator will return the element at the index position, from the end of the array."
},
{
"code": null,
"e": 813,
"s": 727,
"text": "If the index exceeds the array bounds, then this operator does not return any result."
},
{
"code": null,
"e": 824,
"s": 813,
"text": " Examples:"
},
{
"code": null,
"e": 872,
"s": 824,
"text": "In the following examples, we are working with:"
},
{
"code": null,
"e": 896,
"s": 872,
"text": "Database: GeeksforGeeks"
},
{
"code": null,
"e": 921,
"s": 896,
"text": "Collection: arrayExample"
},
{
"code": null,
"e": 1006,
"s": 921,
"text": "Document: three documents that contain the details in the form of field-value pairs."
},
{
"code": null,
"e": 1035,
"s": 1006,
"text": "Using $arrayElemAt Operator:"
},
{
"code": null,
"e": 1185,
"s": 1035,
"text": "In this example, we are going to find the elements of the array(i.e., the value of fruits field) on the specified index using $arrayElemAt operator. "
},
{
"code": null,
"e": 1358,
"s": 1185,
"text": "db.arrayExample.aggregate([\n... {$match: {name: \"Bongo\"}},\n... {$project: {\n... firstItem: {$arrayElemAt: [\"$fruits\", 0]},\n... lastItem: {$arrayElemAt: [\"$fruits\", -1]}}}])"
},
{
"code": null,
"e": 1412,
"s": 1358,
"text": "Using $arrayElemAt Operator in the Embedded Document:"
},
{
"code": null,
"e": 1576,
"s": 1412,
"text": "In this example, we are going to find the elements of the array(i.e., the value of favGame.outdoorGames field) on the specified index using $arrayElemAt operator. "
},
{
"code": null,
"e": 1771,
"s": 1576,
"text": "db.arrayExample.aggregate([\n... {$match: {name: \"Piku\"}},\n... {$project: {\n... firstItem: {$arrayElemAt: [\"$favGame.outdoorGames\", 0]},\n... item: {$arrayElemAt: [\"$favGame.outdoorGames\", 2]}}}])"
},
{
"code": null,
"e": 1781,
"s": 1771,
"text": "as5853535"
},
{
"code": null,
"e": 1799,
"s": 1781,
"text": "MongoDB-operators"
},
{
"code": null,
"e": 1807,
"s": 1799,
"text": "MongoDB"
},
{
"code": null,
"e": 1905,
"s": 1807,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1943,
"s": 1905,
"text": "How to connect MongoDB with ReactJS ?"
},
{
"code": null,
"e": 1968,
"s": 1943,
"text": "MongoDB - limit() Method"
},
{
"code": null,
"e": 1992,
"s": 1968,
"text": "MongoDB - sort() Method"
},
{
"code": null,
"e": 2019,
"s": 1992,
"text": "MongoDB - FindOne() Method"
},
{
"code": null,
"e": 2074,
"s": 2019,
"text": "MongoDB updateOne() Method - db.Collection.updateOne()"
},
{
"code": null,
"e": 2090,
"s": 2074,
"text": "MongoDB - Regex"
},
{
"code": null,
"e": 2117,
"s": 2090,
"text": "MongoDB - Compound Indexes"
},
{
"code": null,
"e": 2174,
"s": 2117,
"text": "MongoDB updateMany() Method - db.Collection.updateMany()"
},
{
"code": null,
"e": 2189,
"s": 2174,
"text": "MongoDB Cursor"
}
] |
Matplotlib.pyplot.eventplot() in Python | 19 Apr, 2020
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack.
This function is often used to plot identical lines at a given position. These plots, in general, are used for representing neural events in neuroscience, where more often it is called spike raster or dot raster or raster plot. More often it is also used for showing the timing or positioning of multiple sets of different or discrete events. For instance the arrival times of employees each day to a business every month or date of hurricanes every year for the last decade or century.
Syntax:: matplotlib.pyplot.eventplot(positions, orientation=’vertical’, lineoffsets=2, linelengths=2, linewidth= None, colors= None, linestyles=’solid’, *, data= None, **kwargs)
Parameters :
Positions: This parameter is generally a 1D or D array-like object where each value in the array represents an event. For a 2D array like position, each row corresponds to either a row or a column of the line which depends upon the orientation parameter. It is a required parameter for this method.
orientation: It is an optional argument which takes two values either ‘horizontal’ or ‘vertical’. It is responsible for controlling the direction of the event collections. If the passed value of orientation is ‘horizontal’ the lines are arranged horizontally in rows and are vertical whereas if the passed value is ‘vertical’ the lines are arranged vertically in columns and are horizontal
lineoffsets: This is an optional argument whose default value is 1. This parameter is used for plotting offset of the center of lines starting from the origin, which are orthogonal to the orientation of the plot. It accepts a scalar or sequence of scalars as its values.
linelengths: Similar to lineoffsets it is also an optional parameter whose default value is 1 and accepts scalar or a scalar sequence as its value. It is used to set the total height of the lines. It sets the stretches of the lines from lineoffset – linelength/2 to lineoffset + linelength/2.
linewidths: It is an optional parameter whose default value is None. It accepts scalar or scalar sequence or None as values. It is used to set the line width(s) of event lines in points. If it is set to None it defaults to its rcParams setting.
colors: As the name suggests it is used to set the colors of the event lines. It is an optional parameter whose default value is None. If the value is None it defaults to its rcParams setting. It takes color, the sequence of colors or None as a value.
linestyles: It is an optional parameter that takes a string, tuple or a sequence of strings or tuples as its value. The default value for this parameter is ‘solid’. The valid strings for this parameter are [‘solid’, ‘dashed’, ‘dashdot’, ‘dotted’, ‘-‘, ‘–‘, ‘-.’, ‘:’]. The dash tuples need to be in the form of (offset, onoffseq) where onoffseq is a tuple of on and off ink in points of even lengths.
**kwargs: It is an optional parameter. It generally accepts keywords from LineCollection properties.
Return:This method returns a list of EventCollection objects which contains the EventCollection that were added.
Note: It is important to note that for linelengths, linewidths, colors, and linestyles, if only a single value is provided than those values are applied to all lines whereas for an array-like value it is important that it has the same length as positions and each value is applied to the corresponding row of the array.
Example 1:
import numpy as npimport matplotlib.pyplot as plt positions = np.array([2, 4, 6])[:,np.newaxis]offsets = [2,4,6] plt.eventplot(positions, lineoffsets=offsets)plt.show()
Output:
Example 2:
import numpy as npimport matplotlib.pyplot as plt spike = 100*np.random.random(100)plt.eventplot(spike, orientation = 'vertical', linelengths = 0.8, color = [(0.5,0.5,0.8)])
Output:
Python-matplotlib
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
Convert integer to string in Python
Convert string to integer in Python
How to set input type date in dd-mm-yyyy format using HTML ?
Python infinity
Factory method design pattern in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Apr, 2020"
},
{
"code": null,
"e": 240,
"s": 28,
"text": "Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack."
},
{
"code": null,
"e": 727,
"s": 240,
"text": "This function is often used to plot identical lines at a given position. These plots, in general, are used for representing neural events in neuroscience, where more often it is called spike raster or dot raster or raster plot. More often it is also used for showing the timing or positioning of multiple sets of different or discrete events. For instance the arrival times of employees each day to a business every month or date of hurricanes every year for the last decade or century."
},
{
"code": null,
"e": 905,
"s": 727,
"text": "Syntax:: matplotlib.pyplot.eventplot(positions, orientation=’vertical’, lineoffsets=2, linelengths=2, linewidth= None, colors= None, linestyles=’solid’, *, data= None, **kwargs)"
},
{
"code": null,
"e": 918,
"s": 905,
"text": "Parameters :"
},
{
"code": null,
"e": 1217,
"s": 918,
"text": "Positions: This parameter is generally a 1D or D array-like object where each value in the array represents an event. For a 2D array like position, each row corresponds to either a row or a column of the line which depends upon the orientation parameter. It is a required parameter for this method."
},
{
"code": null,
"e": 1607,
"s": 1217,
"text": "orientation: It is an optional argument which takes two values either ‘horizontal’ or ‘vertical’. It is responsible for controlling the direction of the event collections. If the passed value of orientation is ‘horizontal’ the lines are arranged horizontally in rows and are vertical whereas if the passed value is ‘vertical’ the lines are arranged vertically in columns and are horizontal"
},
{
"code": null,
"e": 1878,
"s": 1607,
"text": "lineoffsets: This is an optional argument whose default value is 1. This parameter is used for plotting offset of the center of lines starting from the origin, which are orthogonal to the orientation of the plot. It accepts a scalar or sequence of scalars as its values."
},
{
"code": null,
"e": 2171,
"s": 1878,
"text": "linelengths: Similar to lineoffsets it is also an optional parameter whose default value is 1 and accepts scalar or a scalar sequence as its value. It is used to set the total height of the lines. It sets the stretches of the lines from lineoffset – linelength/2 to lineoffset + linelength/2."
},
{
"code": null,
"e": 2416,
"s": 2171,
"text": "linewidths: It is an optional parameter whose default value is None. It accepts scalar or scalar sequence or None as values. It is used to set the line width(s) of event lines in points. If it is set to None it defaults to its rcParams setting."
},
{
"code": null,
"e": 2668,
"s": 2416,
"text": "colors: As the name suggests it is used to set the colors of the event lines. It is an optional parameter whose default value is None. If the value is None it defaults to its rcParams setting. It takes color, the sequence of colors or None as a value."
},
{
"code": null,
"e": 3069,
"s": 2668,
"text": "linestyles: It is an optional parameter that takes a string, tuple or a sequence of strings or tuples as its value. The default value for this parameter is ‘solid’. The valid strings for this parameter are [‘solid’, ‘dashed’, ‘dashdot’, ‘dotted’, ‘-‘, ‘–‘, ‘-.’, ‘:’]. The dash tuples need to be in the form of (offset, onoffseq) where onoffseq is a tuple of on and off ink in points of even lengths."
},
{
"code": null,
"e": 3170,
"s": 3069,
"text": "**kwargs: It is an optional parameter. It generally accepts keywords from LineCollection properties."
},
{
"code": null,
"e": 3283,
"s": 3170,
"text": "Return:This method returns a list of EventCollection objects which contains the EventCollection that were added."
},
{
"code": null,
"e": 3603,
"s": 3283,
"text": "Note: It is important to note that for linelengths, linewidths, colors, and linestyles, if only a single value is provided than those values are applied to all lines whereas for an array-like value it is important that it has the same length as positions and each value is applied to the corresponding row of the array."
},
{
"code": null,
"e": 3614,
"s": 3603,
"text": "Example 1:"
},
{
"code": "import numpy as npimport matplotlib.pyplot as plt positions = np.array([2, 4, 6])[:,np.newaxis]offsets = [2,4,6] plt.eventplot(positions, lineoffsets=offsets)plt.show()",
"e": 3785,
"s": 3614,
"text": null
},
{
"code": null,
"e": 3793,
"s": 3785,
"text": "Output:"
},
{
"code": null,
"e": 3804,
"s": 3793,
"text": "Example 2:"
},
{
"code": "import numpy as npimport matplotlib.pyplot as plt spike = 100*np.random.random(100)plt.eventplot(spike, orientation = 'vertical', linelengths = 0.8, color = [(0.5,0.5,0.8)])",
"e": 4020,
"s": 3804,
"text": null
},
{
"code": null,
"e": 4028,
"s": 4020,
"text": "Output:"
},
{
"code": null,
"e": 4046,
"s": 4028,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 4053,
"s": 4046,
"text": "Python"
},
{
"code": null,
"e": 4069,
"s": 4053,
"text": "Write From Home"
},
{
"code": null,
"e": 4167,
"s": 4069,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4209,
"s": 4167,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 4231,
"s": 4209,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 4266,
"s": 4231,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 4292,
"s": 4266,
"text": "Python String | replace()"
},
{
"code": null,
"e": 4324,
"s": 4292,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4360,
"s": 4324,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 4396,
"s": 4360,
"text": "Convert string to integer in Python"
},
{
"code": null,
"e": 4457,
"s": 4396,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 4473,
"s": 4457,
"text": "Python infinity"
}
] |
Levene’s test | 21 May, 2021
Levene’s test is used to assess the equality of variance between two different samples. For every case, it calculates the absolute difference between the value of that case and its cell mean and performs a one-way analysis of variance (ANOVA) on those differences
The samples from the populations under consideration are independent.
The populations under consideration are approximately normally distributed.
The null hypothesis for Levene’s test is that the variance among groups is equal.
The alternative hypothesis is that the variance among different groups is not equal (for at least one pair the variance is not equal to others).
The test statistics for Levene’s test is:
where,k: number of different groups to which the sampled cases belong.Ni: Number of elements in different groups.N: total number of cases in all groups
k: number of different groups to which the sampled cases belong.
Ni: Number of elements in different groups.
N: total number of cases in all groups
where,Yij: the value of jth case and ith group.
Yij: the value of jth case and ith group.
[Tex]Z_{..} = \frac{1}{N_i}\sum_{i=1}^{K}\sum_{j=1}^{N_i}Z_{ij} \, where \, Z_{ij} \,is \, the\, mean \, of \, all. [/Tex]
There are three types of Levene’s statistics availableIf a distribution has longer tailed distribution like the Cauchy distribution then we use trimmed mean.For skewed distribution, if the distribution is not clear we will use the median for test statistics.For the symmetric distribution and moderately tailed distribution, we use mean value for distribution.
If a distribution has longer tailed distribution like the Cauchy distribution then we use trimmed mean.
For skewed distribution, if the distribution is not clear we will use the median for test statistics.
For the symmetric distribution and moderately tailed distribution, we use mean value for distribution.
Decide the level of significance (alpha). Generally, we take it as 0.05.
Find the critical value in the F-distribution table for the given level of significance, (N-k) and (k-1) parameters.If W > F∝, k-1, N-k, then we reject the null hypothesis.else, we do not reject the null hypothesis.
If W > F∝, k-1, N-k, then we reject the null hypothesis.
else, we do not reject the null hypothesis.
Suppose there are 2 groups of students containing their scores in a maths test are below:
Here, our null hypothesis is defined as:
and the alternate hypothesis is
And our level of significance is:
Now, calculate the test statistics using above formula
where, meanVar is ,
and k-1 = Num of groups -1 =1
N-k = 20-2 =18.
By solving the test statistics using following parameters
[Tex]W = 0.54481[/Tex]
Since, W < F0.05,1,19 , hence we do not reject the null hypothesis.
Python3
from scipy.stats import levene# define groupsgroup_1 = [14, 34, 16, 43, 45, 36, 42, 43, 16, 27]group_2 = [34, 36, 44, 18, 42, 39, 16, 35, 15, 33] # define alphaalpha =0.05# now we pass the groups and center value from the following# ('trimmed mean', 'mean', 'median')w_stats, p_value =levene(group_1,group_2, center ='mean') if p_value > alpha : print("We do not reject the null hypothesis")else: print("Reject the Null Hypothesis")
We do not reject the null hypothesis
surinderdawra388
Engineering Mathematics
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Propositional Logic and Predicate Logic
Activation Functions
Logic Notations in LaTeX
Mathematics | Introduction of Set theory
Modular Arithmetic
Naive Bayes Classifiers
ML | Linear Regression
Linear Regression (Python Implementation) | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 May, 2021"
},
{
"code": null,
"e": 292,
"s": 28,
"text": "Levene’s test is used to assess the equality of variance between two different samples. For every case, it calculates the absolute difference between the value of that case and its cell mean and performs a one-way analysis of variance (ANOVA) on those differences"
},
{
"code": null,
"e": 362,
"s": 292,
"text": "The samples from the populations under consideration are independent."
},
{
"code": null,
"e": 438,
"s": 362,
"text": "The populations under consideration are approximately normally distributed."
},
{
"code": null,
"e": 520,
"s": 438,
"text": "The null hypothesis for Levene’s test is that the variance among groups is equal."
},
{
"code": null,
"e": 665,
"s": 520,
"text": "The alternative hypothesis is that the variance among different groups is not equal (for at least one pair the variance is not equal to others)."
},
{
"code": null,
"e": 707,
"s": 665,
"text": "The test statistics for Levene’s test is:"
},
{
"code": null,
"e": 859,
"s": 707,
"text": "where,k: number of different groups to which the sampled cases belong.Ni: Number of elements in different groups.N: total number of cases in all groups"
},
{
"code": null,
"e": 924,
"s": 859,
"text": "k: number of different groups to which the sampled cases belong."
},
{
"code": null,
"e": 968,
"s": 924,
"text": "Ni: Number of elements in different groups."
},
{
"code": null,
"e": 1007,
"s": 968,
"text": "N: total number of cases in all groups"
},
{
"code": null,
"e": 1055,
"s": 1007,
"text": "where,Yij: the value of jth case and ith group."
},
{
"code": null,
"e": 1097,
"s": 1055,
"text": "Yij: the value of jth case and ith group."
},
{
"code": null,
"e": 1220,
"s": 1097,
"text": "[Tex]Z_{..} = \\frac{1}{N_i}\\sum_{i=1}^{K}\\sum_{j=1}^{N_i}Z_{ij} \\, where \\, Z_{ij} \\,is \\, the\\, mean \\, of \\, all. [/Tex]"
},
{
"code": null,
"e": 1581,
"s": 1220,
"text": "There are three types of Levene’s statistics availableIf a distribution has longer tailed distribution like the Cauchy distribution then we use trimmed mean.For skewed distribution, if the distribution is not clear we will use the median for test statistics.For the symmetric distribution and moderately tailed distribution, we use mean value for distribution."
},
{
"code": null,
"e": 1685,
"s": 1581,
"text": "If a distribution has longer tailed distribution like the Cauchy distribution then we use trimmed mean."
},
{
"code": null,
"e": 1787,
"s": 1685,
"text": "For skewed distribution, if the distribution is not clear we will use the median for test statistics."
},
{
"code": null,
"e": 1890,
"s": 1787,
"text": "For the symmetric distribution and moderately tailed distribution, we use mean value for distribution."
},
{
"code": null,
"e": 1963,
"s": 1890,
"text": "Decide the level of significance (alpha). Generally, we take it as 0.05."
},
{
"code": null,
"e": 2179,
"s": 1963,
"text": "Find the critical value in the F-distribution table for the given level of significance, (N-k) and (k-1) parameters.If W > F∝, k-1, N-k, then we reject the null hypothesis.else, we do not reject the null hypothesis."
},
{
"code": null,
"e": 2236,
"s": 2179,
"text": "If W > F∝, k-1, N-k, then we reject the null hypothesis."
},
{
"code": null,
"e": 2280,
"s": 2236,
"text": "else, we do not reject the null hypothesis."
},
{
"code": null,
"e": 2370,
"s": 2280,
"text": "Suppose there are 2 groups of students containing their scores in a maths test are below:"
},
{
"code": null,
"e": 2411,
"s": 2370,
"text": "Here, our null hypothesis is defined as:"
},
{
"code": null,
"e": 2443,
"s": 2411,
"text": "and the alternate hypothesis is"
},
{
"code": null,
"e": 2477,
"s": 2443,
"text": "And our level of significance is:"
},
{
"code": null,
"e": 2532,
"s": 2477,
"text": "Now, calculate the test statistics using above formula"
},
{
"code": null,
"e": 2552,
"s": 2532,
"text": "where, meanVar is ,"
},
{
"code": null,
"e": 2582,
"s": 2552,
"text": "and k-1 = Num of groups -1 =1"
},
{
"code": null,
"e": 2598,
"s": 2582,
"text": "N-k = 20-2 =18."
},
{
"code": null,
"e": 2656,
"s": 2598,
"text": "By solving the test statistics using following parameters"
},
{
"code": null,
"e": 2679,
"s": 2656,
"text": "[Tex]W = 0.54481[/Tex]"
},
{
"code": null,
"e": 2747,
"s": 2679,
"text": "Since, W < F0.05,1,19 , hence we do not reject the null hypothesis."
},
{
"code": null,
"e": 2755,
"s": 2747,
"text": "Python3"
},
{
"code": "from scipy.stats import levene# define groupsgroup_1 = [14, 34, 16, 43, 45, 36, 42, 43, 16, 27]group_2 = [34, 36, 44, 18, 42, 39, 16, 35, 15, 33] # define alphaalpha =0.05# now we pass the groups and center value from the following# ('trimmed mean', 'mean', 'median')w_stats, p_value =levene(group_1,group_2, center ='mean') if p_value > alpha : print(\"We do not reject the null hypothesis\")else: print(\"Reject the Null Hypothesis\")",
"e": 3190,
"s": 2755,
"text": null
},
{
"code": null,
"e": 3227,
"s": 3190,
"text": "We do not reject the null hypothesis"
},
{
"code": null,
"e": 3244,
"s": 3227,
"text": "surinderdawra388"
},
{
"code": null,
"e": 3268,
"s": 3244,
"text": "Engineering Mathematics"
},
{
"code": null,
"e": 3285,
"s": 3268,
"text": "Machine Learning"
},
{
"code": null,
"e": 3302,
"s": 3285,
"text": "Machine Learning"
},
{
"code": null,
"e": 3400,
"s": 3302,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3459,
"s": 3400,
"text": "Difference between Propositional Logic and Predicate Logic"
},
{
"code": null,
"e": 3480,
"s": 3459,
"text": "Activation Functions"
},
{
"code": null,
"e": 3505,
"s": 3480,
"text": "Logic Notations in LaTeX"
},
{
"code": null,
"e": 3546,
"s": 3505,
"text": "Mathematics | Introduction of Set theory"
},
{
"code": null,
"e": 3565,
"s": 3546,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 3589,
"s": 3565,
"text": "Naive Bayes Classifiers"
},
{
"code": null,
"e": 3612,
"s": 3589,
"text": "ML | Linear Regression"
}
] |
Paper Battery | 06 Jan, 2022
A Paper Battery is a meager, adaptable energy manufacture and storage device that is shaped by merging carbon nanotubes with an ordinary sheet of cellulose-based paper. The paper battery can act in two different ways. A battery and a supercapacitor too. These non-dangerous, adaptable batteries can be utilized as a power source to next-generation electronic gadgets, medical devices, crossbreed vehicles, and so on. Notwithstanding being expandable, paper batteries might be folded, cut, or generally formed for various applications with no loss of integrity or efficiency.
As sensors are progressively being installed in ordinary articles, there has been a relating requirement for alternative power sources in the Internet of Things (IoT). The high cellulose substance and absence of harmful synthetic compounds in paper batteries make them both biocompatible and naturally amicable, particularly when contrasted with the lithium-particle batteries utilized in many present-day electronic gadgets.
Working: The regular reusable batteries which we use in our everyday life comprise of different isolating parts which are utilized for delivering electrons with the chemical reaction of metal and electrolyte. If once the paper of the battery is plunged in ion-based based fluid, at that point the battery begins working i.e., power is created by the motion of electrons from cathode terminal to anode terminal. This is because of the chemical reaction between the electrodes of the paper battery and fluid. Because of the rapid flow of the particles within a few seconds (10sec), energy will be put away in the paper-electrode during the recharging. By stacking different paper-batteries upon one another, the yield of the paper battery can be expanded.
As the paper batteries are connected with one another all around intently for expanding their output, there is a chance of happening short between the anode terminal and cathode terminal. On the off chance that once the anode terminal contacts with the cathode terminal, at that point there will be no progression of current in the outer circuit. Along these lines, to dodge the short circuit between anode and cathode a barrier or separator is required, which can be satisfied by the paper separator.
Properties:
Biodegradable Non-Toxic Recyclable Low-Shear Strength Low Mass Density Low Resistance
Biodegradable
Non-Toxic
Recyclable
Low-Shear Strength
Low Mass Density
Low Resistance
Advantages:
Can be used by folding and rolling Works as a battery as well as a capacitor Can generate electrical energy of 1.5V The output voltage can be customized Ultra-thin in size
Can be used by folding and rolling
Works as a battery as well as a capacitor
Can generate electrical energy of 1.5V
The output voltage can be customized
Ultra-thin in size
Disadvantages:
Very Expensive Generation of E-wastage
Very Expensive
Generation of E-wastage
Application: A paper battery can really demonstrate helpful for applications where convenience and size is the main prerequisite. Current electronic supplies like smart cards, digital watches encourage the necessity of thin batteries which are dependable and non-toxic.
It can likewise be utilized for low-power gadgets like calculators, wristwatches, and remote communication gadgets like a mouse, Bluetooth earphones, keypads, and so on.
abhishek0719kadiyan
GBlog
Misc
Misc
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Jan, 2022"
},
{
"code": null,
"e": 604,
"s": 28,
"text": "A Paper Battery is a meager, adaptable energy manufacture and storage device that is shaped by merging carbon nanotubes with an ordinary sheet of cellulose-based paper. The paper battery can act in two different ways. A battery and a supercapacitor too. These non-dangerous, adaptable batteries can be utilized as a power source to next-generation electronic gadgets, medical devices, crossbreed vehicles, and so on. Notwithstanding being expandable, paper batteries might be folded, cut, or generally formed for various applications with no loss of integrity or efficiency. "
},
{
"code": null,
"e": 1031,
"s": 604,
"text": "As sensors are progressively being installed in ordinary articles, there has been a relating requirement for alternative power sources in the Internet of Things (IoT). The high cellulose substance and absence of harmful synthetic compounds in paper batteries make them both biocompatible and naturally amicable, particularly when contrasted with the lithium-particle batteries utilized in many present-day electronic gadgets. "
},
{
"code": null,
"e": 1786,
"s": 1031,
"text": "Working: The regular reusable batteries which we use in our everyday life comprise of different isolating parts which are utilized for delivering electrons with the chemical reaction of metal and electrolyte. If once the paper of the battery is plunged in ion-based based fluid, at that point the battery begins working i.e., power is created by the motion of electrons from cathode terminal to anode terminal. This is because of the chemical reaction between the electrodes of the paper battery and fluid. Because of the rapid flow of the particles within a few seconds (10sec), energy will be put away in the paper-electrode during the recharging. By stacking different paper-batteries upon one another, the yield of the paper battery can be expanded. "
},
{
"code": null,
"e": 2289,
"s": 1786,
"text": "As the paper batteries are connected with one another all around intently for expanding their output, there is a chance of happening short between the anode terminal and cathode terminal. On the off chance that once the anode terminal contacts with the cathode terminal, at that point there will be no progression of current in the outer circuit. Along these lines, to dodge the short circuit between anode and cathode a barrier or separator is required, which can be satisfied by the paper separator. "
},
{
"code": null,
"e": 2302,
"s": 2289,
"text": "Properties: "
},
{
"code": null,
"e": 2389,
"s": 2302,
"text": "Biodegradable Non-Toxic Recyclable Low-Shear Strength Low Mass Density Low Resistance "
},
{
"code": null,
"e": 2404,
"s": 2389,
"text": "Biodegradable "
},
{
"code": null,
"e": 2415,
"s": 2404,
"text": "Non-Toxic "
},
{
"code": null,
"e": 2427,
"s": 2415,
"text": "Recyclable "
},
{
"code": null,
"e": 2447,
"s": 2427,
"text": "Low-Shear Strength "
},
{
"code": null,
"e": 2465,
"s": 2447,
"text": "Low Mass Density "
},
{
"code": null,
"e": 2481,
"s": 2465,
"text": "Low Resistance "
},
{
"code": null,
"e": 2494,
"s": 2481,
"text": "Advantages: "
},
{
"code": null,
"e": 2667,
"s": 2494,
"text": "Can be used by folding and rolling Works as a battery as well as a capacitor Can generate electrical energy of 1.5V The output voltage can be customized Ultra-thin in size "
},
{
"code": null,
"e": 2703,
"s": 2667,
"text": "Can be used by folding and rolling "
},
{
"code": null,
"e": 2746,
"s": 2703,
"text": "Works as a battery as well as a capacitor "
},
{
"code": null,
"e": 2786,
"s": 2746,
"text": "Can generate electrical energy of 1.5V "
},
{
"code": null,
"e": 2824,
"s": 2786,
"text": "The output voltage can be customized "
},
{
"code": null,
"e": 2844,
"s": 2824,
"text": "Ultra-thin in size "
},
{
"code": null,
"e": 2860,
"s": 2844,
"text": "Disadvantages: "
},
{
"code": null,
"e": 2900,
"s": 2860,
"text": "Very Expensive Generation of E-wastage "
},
{
"code": null,
"e": 2916,
"s": 2900,
"text": "Very Expensive "
},
{
"code": null,
"e": 2941,
"s": 2916,
"text": "Generation of E-wastage "
},
{
"code": null,
"e": 3212,
"s": 2941,
"text": "Application: A paper battery can really demonstrate helpful for applications where convenience and size is the main prerequisite. Current electronic supplies like smart cards, digital watches encourage the necessity of thin batteries which are dependable and non-toxic. "
},
{
"code": null,
"e": 3383,
"s": 3212,
"text": "It can likewise be utilized for low-power gadgets like calculators, wristwatches, and remote communication gadgets like a mouse, Bluetooth earphones, keypads, and so on. "
},
{
"code": null,
"e": 3403,
"s": 3383,
"text": "abhishek0719kadiyan"
},
{
"code": null,
"e": 3409,
"s": 3403,
"text": "GBlog"
},
{
"code": null,
"e": 3414,
"s": 3409,
"text": "Misc"
},
{
"code": null,
"e": 3419,
"s": 3414,
"text": "Misc"
},
{
"code": null,
"e": 3424,
"s": 3419,
"text": "Misc"
}
] |
Python 3 - Tuples | A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The main difference between the tuples and the lists is that the tuples cannot be changed unlike lists. Tuples use parentheses, whereas lists use square brackets.
Creating a tuple is as simple as putting different comma-separated values. Optionally, you can put these comma-separated values between parentheses also. For example −
tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5 )
tup3 = "a", "b", "c", "d"
The empty tuple is written as two parentheses containing nothing −
tup1 = ();
To write a tuple containing a single value you have to include a comma, even though there is only one value −
tup1 = (50,)
Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so on.
To access values in tuple, use the square brackets for slicing along with the index or indices to obtain the value available at that index. For example −
#!/usr/bin/python3
tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5, 6, 7 )
print ("tup1[0]: ", tup1[0])
print ("tup2[1:5]: ", tup2[1:5])
When the above code is executed, it produces the following result −
tup1[0]: physics
tup2[1:5]: (2, 3, 4, 5)
Tuples are immutable, which means you cannot update or change the values of tuple elements. You are able to take portions of the existing tuples to create new tuples as the following example demonstrates −
#!/usr/bin/python3
tup1 = (12, 34.56)
tup2 = ('abc', 'xyz')
# Following action is not valid for tuples
# tup1[0] = 100;
# So let's create a new tuple as follows
tup3 = tup1 + tup2
print (tup3)
When the above code is executed, it produces the following result −
(12, 34.56, 'abc', 'xyz')
Removing individual tuple elements is not possible. There is, of course, nothing wrong with putting together another tuple with the undesired elements discarded.
To explicitly remove an entire tuple, just use the del statement. For example −
#!/usr/bin/python3
tup = ('physics', 'chemistry', 1997, 2000);
print (tup)
del tup;
print ("After deleting tup : ")
print (tup)
This produces the following result.
Note − An exception is raised. This is because after del tup, tuple does not exist any more.
('physics', 'chemistry', 1997, 2000)
After deleting tup :
Traceback (most recent call last):
File "test.py", line 9, in <module>
print tup;
NameError: name 'tup' is not defined
Tuples respond to the + and * operators much like strings; they mean concatenation and repetition here too, except that the result is a new tuple, not a string.
In fact, tuples respond to all of the general sequence operations we used on strings in the previous chapter.
Since tuples are sequences, indexing and slicing work the same way for tuples as they do for strings, assuming the following input −
T=('C++', 'Java', 'Python')
No enclosing Delimiters is any set of multiple objects, comma-separated, written without identifying symbols, i.e., brackets for lists, parentheses for tuples, etc., default to tuples, as indicated in these short examples.
Python includes the following tuple functions −
Gives the total length of the tuple.
Returns item from the tuple with max value.
Returns item from the tuple with min value.
Converts a list into tuple. | [
{
"code": null,
"e": 2727,
"s": 2474,
"text": "A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The main difference between the tuples and the lists is that the tuples cannot be changed unlike lists. Tuples use parentheses, whereas lists use square brackets."
},
{
"code": null,
"e": 2895,
"s": 2727,
"text": "Creating a tuple is as simple as putting different comma-separated values. Optionally, you can put these comma-separated values between parentheses also. For example −"
},
{
"code": null,
"e": 2989,
"s": 2895,
"text": "tup1 = ('physics', 'chemistry', 1997, 2000)\ntup2 = (1, 2, 3, 4, 5 )\ntup3 = \"a\", \"b\", \"c\", \"d\""
},
{
"code": null,
"e": 3056,
"s": 2989,
"text": "The empty tuple is written as two parentheses containing nothing −"
},
{
"code": null,
"e": 3068,
"s": 3056,
"text": "tup1 = ();\n"
},
{
"code": null,
"e": 3178,
"s": 3068,
"text": "To write a tuple containing a single value you have to include a comma, even though there is only one value −"
},
{
"code": null,
"e": 3192,
"s": 3178,
"text": "tup1 = (50,)\n"
},
{
"code": null,
"e": 3288,
"s": 3192,
"text": "Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so on."
},
{
"code": null,
"e": 3442,
"s": 3288,
"text": "To access values in tuple, use the square brackets for slicing along with the index or indices to obtain the value available at that index. For example −"
},
{
"code": null,
"e": 3599,
"s": 3442,
"text": "#!/usr/bin/python3\n\ntup1 = ('physics', 'chemistry', 1997, 2000)\ntup2 = (1, 2, 3, 4, 5, 6, 7 )\n\nprint (\"tup1[0]: \", tup1[0])\nprint (\"tup2[1:5]: \", tup2[1:5])"
},
{
"code": null,
"e": 3668,
"s": 3599,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 3712,
"s": 3668,
"text": "tup1[0]: physics\ntup2[1:5]: (2, 3, 4, 5)\n"
},
{
"code": null,
"e": 3918,
"s": 3712,
"text": "Tuples are immutable, which means you cannot update or change the values of tuple elements. You are able to take portions of the existing tuples to create new tuples as the following example demonstrates −"
},
{
"code": null,
"e": 4114,
"s": 3918,
"text": "#!/usr/bin/python3\n\ntup1 = (12, 34.56)\ntup2 = ('abc', 'xyz')\n\n# Following action is not valid for tuples\n# tup1[0] = 100;\n\n# So let's create a new tuple as follows\ntup3 = tup1 + tup2\nprint (tup3)"
},
{
"code": null,
"e": 4182,
"s": 4114,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 4209,
"s": 4182,
"text": "(12, 34.56, 'abc', 'xyz')\n"
},
{
"code": null,
"e": 4371,
"s": 4209,
"text": "Removing individual tuple elements is not possible. There is, of course, nothing wrong with putting together another tuple with the undesired elements discarded."
},
{
"code": null,
"e": 4451,
"s": 4371,
"text": "To explicitly remove an entire tuple, just use the del statement. For example −"
},
{
"code": null,
"e": 4581,
"s": 4451,
"text": "#!/usr/bin/python3\n\ntup = ('physics', 'chemistry', 1997, 2000);\n\nprint (tup)\ndel tup;\nprint (\"After deleting tup : \")\nprint (tup)"
},
{
"code": null,
"e": 4617,
"s": 4581,
"text": "This produces the following result."
},
{
"code": null,
"e": 4710,
"s": 4617,
"text": "Note − An exception is raised. This is because after del tup, tuple does not exist any more."
},
{
"code": null,
"e": 4897,
"s": 4710,
"text": "('physics', 'chemistry', 1997, 2000)\nAfter deleting tup :\nTraceback (most recent call last):\n File \"test.py\", line 9, in <module>\n print tup;\nNameError: name 'tup' is not defined\n"
},
{
"code": null,
"e": 5058,
"s": 4897,
"text": "Tuples respond to the + and * operators much like strings; they mean concatenation and repetition here too, except that the result is a new tuple, not a string."
},
{
"code": null,
"e": 5168,
"s": 5058,
"text": "In fact, tuples respond to all of the general sequence operations we used on strings in the previous chapter."
},
{
"code": null,
"e": 5301,
"s": 5168,
"text": "Since tuples are sequences, indexing and slicing work the same way for tuples as they do for strings, assuming the following input −"
},
{
"code": null,
"e": 5330,
"s": 5301,
"text": "T=('C++', 'Java', 'Python')\n"
},
{
"code": null,
"e": 5553,
"s": 5330,
"text": "No enclosing Delimiters is any set of multiple objects, comma-separated, written without identifying symbols, i.e., brackets for lists, parentheses for tuples, etc., default to tuples, as indicated in these short examples."
},
{
"code": null,
"e": 5601,
"s": 5553,
"text": "Python includes the following tuple functions −"
},
{
"code": null,
"e": 5638,
"s": 5601,
"text": "Gives the total length of the tuple."
},
{
"code": null,
"e": 5682,
"s": 5638,
"text": "Returns item from the tuple with max value."
},
{
"code": null,
"e": 5726,
"s": 5682,
"text": "Returns item from the tuple with min value."
}
] |
PyQt5 QDateTimeEdit – Setting QDateTime to it | 10 Jul, 2020
In this article we will see how we can set QDateTime object to the QDateTimeEdit widget. QDateTime is basically a combination of QDate and QTime i.e it has both date and time. And QDateTimeEdit widget is used to show or receive the QDateTime.
In order to do this we will use setDateTime method with the QDateTimeEdit object.
Syntax : datetimeedit.setDateTime(dt)
Argument : It takes QDateTime object as argument
Return : It returns None
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QDateTimeEdit widget datetimeedit = QDateTimeEdit(self) # setting geometry datetimeedit.setGeometry(100, 100, 150, 35) # creating a label label = QLabel("GeeksforGeeks", self) # setting geometry to the label label.setGeometry(100, 160, 200, 60) # making label multi line label.setWordWrap(True) # QDateTime dt = QDateTime(2020, 10, 10, 21, 30) # setting date time to datetimeedit datetimeedit.setDateTime(dt) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
Python PyQt-QDateTimeEdit
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Jul, 2020"
},
{
"code": null,
"e": 271,
"s": 28,
"text": "In this article we will see how we can set QDateTime object to the QDateTimeEdit widget. QDateTime is basically a combination of QDate and QTime i.e it has both date and time. And QDateTimeEdit widget is used to show or receive the QDateTime."
},
{
"code": null,
"e": 353,
"s": 271,
"text": "In order to do this we will use setDateTime method with the QDateTimeEdit object."
},
{
"code": null,
"e": 391,
"s": 353,
"text": "Syntax : datetimeedit.setDateTime(dt)"
},
{
"code": null,
"e": 440,
"s": 391,
"text": "Argument : It takes QDateTime object as argument"
},
{
"code": null,
"e": 465,
"s": 440,
"text": "Return : It returns None"
},
{
"code": null,
"e": 493,
"s": 465,
"text": "Below is the implementation"
},
{
"code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QDateTimeEdit widget datetimeedit = QDateTimeEdit(self) # setting geometry datetimeedit.setGeometry(100, 100, 150, 35) # creating a label label = QLabel(\"GeeksforGeeks\", self) # setting geometry to the label label.setGeometry(100, 160, 200, 60) # making label multi line label.setWordWrap(True) # QDateTime dt = QDateTime(2020, 10, 10, 21, 30) # setting date time to datetimeedit datetimeedit.setDateTime(dt) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 1695,
"s": 493,
"text": null
},
{
"code": null,
"e": 1704,
"s": 1695,
"text": "Output :"
},
{
"code": null,
"e": 1730,
"s": 1704,
"text": "Python PyQt-QDateTimeEdit"
},
{
"code": null,
"e": 1741,
"s": 1730,
"text": "Python-gui"
},
{
"code": null,
"e": 1753,
"s": 1741,
"text": "Python-PyQt"
},
{
"code": null,
"e": 1760,
"s": 1753,
"text": "Python"
},
{
"code": null,
"e": 1858,
"s": 1760,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1890,
"s": 1858,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1917,
"s": 1890,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1938,
"s": 1917,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1961,
"s": 1938,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2017,
"s": 1961,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2048,
"s": 2017,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2090,
"s": 2048,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2132,
"s": 2090,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2171,
"s": 2132,
"text": "Python | Get unique values from a list"
}
] |
Python Program for Find largest prime factor of a number | 17 Feb, 2018
Given a positive integer \’n\'( 1 <= n <= 1015). Find the largest prime factor of a number.
Input: 6
Output: 3
Explanation
Prime factor of 6 are- 2, 3
Largest of them is \'3\'
Input: 15
Output: 5
Python3
# Python3 code to find largest prime# factor of numberimport math # A function to find largest prime factordef maxPrimeFactors (n): # Initialize the maximum prime factor # variable with the lowest one maxPrime = -1 # Print the number of 2s that divide n while n % 2 == 0: maxPrime = 2 n >>= 1 # equivalent to n /= 2 # n must be odd at this point, # thus skip the even numbers and # iterate only for odd integers for i in range(3, int(math.sqrt(n)) + 1, 2): while n % i == 0: maxPrime = i n = n / i # This condition is to handle the # case when n is a prime number # greater than 2 if n > 2: maxPrime = n return int(maxPrime) # Driver code to test above functionn = 15print(maxPrimeFactors(n)) n = 25698751364526print(maxPrimeFactors(n)) # This code is contributed by "Sharad_Bhardwaj".
5
328513
Time complexity: Auxiliary space:
Please refer complete article on Find largest prime factor of a number for more details!
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Convert string dictionary to dictionary
Python program to add two numbers
Python Program for Binary Search (Recursive and Iterative)
Python Program for factorial of a number
Python program to find second largest number in a list
Iterate over characters of a string in Python
Python | Convert set into a list
Appending to list in Python dictionary
Python | Convert a list into a tuple
Python Program for Bubble Sort | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n17 Feb, 2018"
},
{
"code": null,
"e": 144,
"s": 52,
"text": "Given a positive integer \\’n\\'( 1 <= n <= 1015). Find the largest prime factor of a number."
},
{
"code": null,
"e": 250,
"s": 144,
"text": "Input: 6\nOutput: 3\nExplanation\nPrime factor of 6 are- 2, 3\nLargest of them is \\'3\\'\n\nInput: 15\nOutput: 5\n"
},
{
"code": null,
"e": 258,
"s": 250,
"text": "Python3"
},
{
"code": "# Python3 code to find largest prime# factor of numberimport math # A function to find largest prime factordef maxPrimeFactors (n): # Initialize the maximum prime factor # variable with the lowest one maxPrime = -1 # Print the number of 2s that divide n while n % 2 == 0: maxPrime = 2 n >>= 1 # equivalent to n /= 2 # n must be odd at this point, # thus skip the even numbers and # iterate only for odd integers for i in range(3, int(math.sqrt(n)) + 1, 2): while n % i == 0: maxPrime = i n = n / i # This condition is to handle the # case when n is a prime number # greater than 2 if n > 2: maxPrime = n return int(maxPrime) # Driver code to test above functionn = 15print(maxPrimeFactors(n)) n = 25698751364526print(maxPrimeFactors(n)) # This code is contributed by \"Sharad_Bhardwaj\".",
"e": 1182,
"s": 258,
"text": null
},
{
"code": null,
"e": 1192,
"s": 1182,
"text": "5\n328513\n"
},
{
"code": null,
"e": 1227,
"s": 1192,
"text": "Time complexity: Auxiliary space: "
},
{
"code": null,
"e": 1316,
"s": 1227,
"text": "Please refer complete article on Find largest prime factor of a number for more details!"
},
{
"code": null,
"e": 1332,
"s": 1316,
"text": "Python Programs"
},
{
"code": null,
"e": 1430,
"s": 1332,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1479,
"s": 1430,
"text": "Python | Convert string dictionary to dictionary"
},
{
"code": null,
"e": 1513,
"s": 1479,
"text": "Python program to add two numbers"
},
{
"code": null,
"e": 1572,
"s": 1513,
"text": "Python Program for Binary Search (Recursive and Iterative)"
},
{
"code": null,
"e": 1613,
"s": 1572,
"text": "Python Program for factorial of a number"
},
{
"code": null,
"e": 1668,
"s": 1613,
"text": "Python program to find second largest number in a list"
},
{
"code": null,
"e": 1714,
"s": 1668,
"text": "Iterate over characters of a string in Python"
},
{
"code": null,
"e": 1747,
"s": 1714,
"text": "Python | Convert set into a list"
},
{
"code": null,
"e": 1786,
"s": 1747,
"text": "Appending to list in Python dictionary"
},
{
"code": null,
"e": 1823,
"s": 1786,
"text": "Python | Convert a list into a tuple"
}
] |
Scala String toLowerCase() method with example | 29 Oct, 2019
The toLowerCase() method is utilized to convert all the characters in the String into the lowercase.
Method Definition: String toLowerCase()
Return Type: It returns the resultant string after converting each character of the string into the lowercase.
Example: 1#
// Scala program of toLowerCase()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying toLowerCase method val result = "NIDHI".toLowerCase() // Displays output println(result) }}
nidhi
Example: 2#
// Scala program of toLowerCase()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying toLowerCase method val result = "gEEKs".toLowerCase() // Displays output println(result) }}
geeks
Scala
Scala-Method
Scala-Strings
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inheritance in Scala
How to Install Scala with VSCode?
Scala | Option
Hello World in Scala
Scala | Traits
Scala ListBuffer
Scala Sequence
Scala | Decision Making (if, if-else, Nested if-else, if-else if)
Introduction to Scala
Scala | Functions - Basics | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Oct, 2019"
},
{
"code": null,
"e": 129,
"s": 28,
"text": "The toLowerCase() method is utilized to convert all the characters in the String into the lowercase."
},
{
"code": null,
"e": 169,
"s": 129,
"text": "Method Definition: String toLowerCase()"
},
{
"code": null,
"e": 280,
"s": 169,
"text": "Return Type: It returns the resultant string after converting each character of the string into the lowercase."
},
{
"code": null,
"e": 292,
"s": 280,
"text": "Example: 1#"
},
{
"code": "// Scala program of toLowerCase()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying toLowerCase method val result = \"NIDHI\".toLowerCase() // Displays output println(result) }} ",
"e": 582,
"s": 292,
"text": null
},
{
"code": null,
"e": 589,
"s": 582,
"text": "nidhi\n"
},
{
"code": null,
"e": 601,
"s": 589,
"text": "Example: 2#"
},
{
"code": "// Scala program of toLowerCase()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying toLowerCase method val result = \"gEEKs\".toLowerCase() // Displays output println(result) }} ",
"e": 891,
"s": 601,
"text": null
},
{
"code": null,
"e": 898,
"s": 891,
"text": "geeks\n"
},
{
"code": null,
"e": 904,
"s": 898,
"text": "Scala"
},
{
"code": null,
"e": 917,
"s": 904,
"text": "Scala-Method"
},
{
"code": null,
"e": 931,
"s": 917,
"text": "Scala-Strings"
},
{
"code": null,
"e": 937,
"s": 931,
"text": "Scala"
},
{
"code": null,
"e": 1035,
"s": 937,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1056,
"s": 1035,
"text": "Inheritance in Scala"
},
{
"code": null,
"e": 1090,
"s": 1056,
"text": "How to Install Scala with VSCode?"
},
{
"code": null,
"e": 1105,
"s": 1090,
"text": "Scala | Option"
},
{
"code": null,
"e": 1126,
"s": 1105,
"text": "Hello World in Scala"
},
{
"code": null,
"e": 1141,
"s": 1126,
"text": "Scala | Traits"
},
{
"code": null,
"e": 1158,
"s": 1141,
"text": "Scala ListBuffer"
},
{
"code": null,
"e": 1173,
"s": 1158,
"text": "Scala Sequence"
},
{
"code": null,
"e": 1239,
"s": 1173,
"text": "Scala | Decision Making (if, if-else, Nested if-else, if-else if)"
},
{
"code": null,
"e": 1261,
"s": 1239,
"text": "Introduction to Scala"
}
] |
AngularJS - Upload File | We are providing an example of Upload File. To develop this app, we have used HTML, CSS and AngularJS. Following example shows about how to upload the file using AngularJS.
<html>
<head>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>
</head>
<body ng-app = "myApp">
<div ng-controller = "myCtrl">
<input type = "file" file-model = "myFile"/>
<button ng-click = "uploadFile()">upload me</button>
</div>
<script>
var myApp = angular.module('myApp', []);
myApp.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function() {
scope.$apply(function() {
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
myApp.service('fileUpload', ['$https:', function ($https:) {
this.uploadFileToUrl = function(file, uploadUrl) {
var fd = new FormData();
fd.append('file', file);
$https:.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function() {
})
.error(function() {
});
}
}]);
myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload) {
$scope.uploadFile = function() {
var file = $scope.myFile;
console.log('file is ' );
console.dir(file);
var uploadUrl = "/fileUpload";
fileUpload.uploadFileToUrl(file, uploadUrl);
};
}]);
</script>
</body>
</html>
Open above saved code file in a web browser. See the result. | [
{
"code": null,
"e": 3006,
"s": 2833,
"text": "We are providing an example of Upload File. To develop this app, we have used HTML, CSS and AngularJS. Following example shows about how to upload the file using AngularJS."
},
{
"code": null,
"e": 4963,
"s": 3006,
"text": "<html>\n <head>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js\">\n </script>\n </head>\n \n <body ng-app = \"myApp\">\n\t\n <div ng-controller = \"myCtrl\">\n <input type = \"file\" file-model = \"myFile\"/>\n <button ng-click = \"uploadFile()\">upload me</button>\n </div>\n \n <script>\n var myApp = angular.module('myApp', []);\n \n myApp.directive('fileModel', ['$parse', function ($parse) {\n return {\n restrict: 'A',\n link: function(scope, element, attrs) {\n var model = $parse(attrs.fileModel);\n var modelSetter = model.assign;\n \n element.bind('change', function() {\n scope.$apply(function() {\n modelSetter(scope, element[0].files[0]);\n });\n });\n }\n };\n }]);\n myApp.service('fileUpload', ['$https:', function ($https:) {\n this.uploadFileToUrl = function(file, uploadUrl) {\n var fd = new FormData();\n fd.append('file', file);\n \n $https:.post(uploadUrl, fd, {\n transformRequest: angular.identity,\n headers: {'Content-Type': undefined}\n })\n .success(function() {\n })\n .error(function() {\n });\n }\n }]);\n myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload) {\n $scope.uploadFile = function() {\n \n var file = $scope.myFile;\n console.log('file is ' );\n console.dir(file);\n var uploadUrl = \"/fileUpload\";\n fileUpload.uploadFileToUrl(file, uploadUrl);\n };\n }]);\n </script>\n \n </body>\n</html>"
}
] |
How to open two files together in Python? | 24 Jan, 2021
Python provides the ability to open as well as work with multiple files at the same time. Different files can be opened in different modes, to simulate simultaneous writing or reading from these files. An arbitrary number of files can be opened with the open() method supported in Python 2.7 version or greater. The following syntax is used to open multiple files :
with open(file_1) as f1, open(file_2) as f2
file_1: specifies the path of the first file
file_2: specifies the path of the second file
Different names are provided to different files. The files can be opened in read, write or append modes respectively. The operation is performed synchronously and both the files are opened at the same time. By default, the files are opened to support read operations.
The following text files are used in the later sections of codes :
Steps used to open multiple files together in Python :
Both the files are opened with open() method using different names for each
The contents of the files can be accessed using readline() method.
Different read/write operations can be performed over the contents of these files.
Example 1:
Python3
# opening both the files in reading modeswith open("file1.txt") as f1, open("file2.txt") as f2: # reading f1 contents line1 = f1.readline() # reading f2 contents line2 = f2.readline() # printing contents of f1 followed by f2 print(line1, line2)
Output :
Geeksforgeeks is a complete portal. Try coding here!
Example 2:
The following code indicates storing the contents of one file into another.
Python3
# opening file1 in reading mode and file2 in writing modewith open('file1.txt', 'r') as f1, open('file2.txt', 'w') as f2: # writing the contents of file1 into file2 f2.write(f1.read())
Output: The contents of file2 after this operation are as follows :
Picked
Python file-handling-programs
python-file-handling
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Jan, 2021"
},
{
"code": null,
"e": 395,
"s": 28,
"text": "Python provides the ability to open as well as work with multiple files at the same time. Different files can be opened in different modes, to simulate simultaneous writing or reading from these files. An arbitrary number of files can be opened with the open() method supported in Python 2.7 version or greater. The following syntax is used to open multiple files : "
},
{
"code": null,
"e": 439,
"s": 395,
"text": "with open(file_1) as f1, open(file_2) as f2"
},
{
"code": null,
"e": 484,
"s": 439,
"text": "file_1: specifies the path of the first file"
},
{
"code": null,
"e": 530,
"s": 484,
"text": "file_2: specifies the path of the second file"
},
{
"code": null,
"e": 799,
"s": 530,
"text": "Different names are provided to different files. The files can be opened in read, write or append modes respectively. The operation is performed synchronously and both the files are opened at the same time. By default, the files are opened to support read operations. "
},
{
"code": null,
"e": 867,
"s": 799,
"text": "The following text files are used in the later sections of codes : "
},
{
"code": null,
"e": 922,
"s": 867,
"text": "Steps used to open multiple files together in Python :"
},
{
"code": null,
"e": 998,
"s": 922,
"text": "Both the files are opened with open() method using different names for each"
},
{
"code": null,
"e": 1065,
"s": 998,
"text": "The contents of the files can be accessed using readline() method."
},
{
"code": null,
"e": 1148,
"s": 1065,
"text": "Different read/write operations can be performed over the contents of these files."
},
{
"code": null,
"e": 1159,
"s": 1148,
"text": "Example 1:"
},
{
"code": null,
"e": 1167,
"s": 1159,
"text": "Python3"
},
{
"code": "# opening both the files in reading modeswith open(\"file1.txt\") as f1, open(\"file2.txt\") as f2: # reading f1 contents line1 = f1.readline() # reading f2 contents line2 = f2.readline() # printing contents of f1 followed by f2 print(line1, line2)",
"e": 1431,
"s": 1167,
"text": null
},
{
"code": null,
"e": 1440,
"s": 1431,
"text": "Output :"
},
{
"code": null,
"e": 1493,
"s": 1440,
"text": "Geeksforgeeks is a complete portal. Try coding here!"
},
{
"code": null,
"e": 1504,
"s": 1493,
"text": "Example 2:"
},
{
"code": null,
"e": 1581,
"s": 1504,
"text": "The following code indicates storing the contents of one file into another. "
},
{
"code": null,
"e": 1589,
"s": 1581,
"text": "Python3"
},
{
"code": "# opening file1 in reading mode and file2 in writing modewith open('file1.txt', 'r') as f1, open('file2.txt', 'w') as f2: # writing the contents of file1 into file2 f2.write(f1.read())",
"e": 1780,
"s": 1589,
"text": null
},
{
"code": null,
"e": 1849,
"s": 1780,
"text": "Output: The contents of file2 after this operation are as follows : "
},
{
"code": null,
"e": 1856,
"s": 1849,
"text": "Picked"
},
{
"code": null,
"e": 1886,
"s": 1856,
"text": "Python file-handling-programs"
},
{
"code": null,
"e": 1907,
"s": 1886,
"text": "python-file-handling"
},
{
"code": null,
"e": 1914,
"s": 1907,
"text": "Python"
},
{
"code": null,
"e": 2012,
"s": 1914,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2044,
"s": 2012,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2071,
"s": 2044,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2092,
"s": 2071,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2115,
"s": 2092,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2171,
"s": 2115,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2202,
"s": 2171,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2244,
"s": 2202,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2286,
"s": 2244,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2325,
"s": 2286,
"text": "Python | Get unique values from a list"
}
] |
Hashtable keys() Method in Java | 09 Oct, 2021
As we all know enumeration defines java class type so do enumerations can have constructors, methods, and instance variables. The java.util.Hashtable.keys() method of Hashtable class in Java is used to get the enumeration of the keys present in the hashtable.
Illustration:
Syntax:
public Enumeration<K> keys()
Enumeration enu = Hash_table.keys();
Return value: An enumeration of the keys of the Hashtable.
Example 1:
Java
// Java Program to Illustrate keys() method// of Hashtable class // Importing utility classesimport java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an empty Hashtable // Declaring object of integer and string type Hashtable<Integer, String> hash_table = new Hashtable<Integer, String>(); // Inserting elements into the table // using put() method // Custom input elements hash_table.put(10, "Geeks"); hash_table.put(15, "4"); hash_table.put(20, "Geeks"); hash_table.put(25, "Welcomes"); hash_table.put(30, "You"); // Print and display all entered elements in object System.out.println("The Table is: " + hash_table); // Creating an empty enumeration to store Enumeration enu = hash_table.keys(); // Display message System.out.println("The enumeration of keys are:"); // Condition holds true till there is single element // remaining using hasMoreElements() method while (enu.hasMoreElements()) { // Displaying the Enumeration System.out.println(enu.nextElement()); } }}
The Table is: {10=Geeks, 20=Geeks, 30=You, 15=4, 25=Welcomes}
The enumeration of keys are:
10
20
30
15
25
Example 2:
Java
// Java Program to illustrate keys() method// of Hashtable class // Importing utility classesimport java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an empty Hashtable // Declaring object of string and integer type Hashtable<String, Integer> hash_table = new Hashtable<String, Integer>(); // Inserting elements into the table // using put() method hash_table.put("Geeks", 10); hash_table.put("4", 15); hash_table.put("Geeks", 20); hash_table.put("Welcomes", 25); hash_table.put("You", 30); // Displaying the Hashtable System.out.println("The Table is: " + hash_table); // Creating an empty enumeration to store Enumeration enu = hash_table.keys(); // Display message System.out.println("The enumeration of keys are:"); // Condition holds true till there is single element // remaining via hasMoreElements() method while (enu.hasMoreElements()) { // Displaying the enumeration System.out.println(enu.nextElement()); } }}
The Table is: {You=30, Welcomes=25, 4=15, Geeks=20}
The enumeration of keys are:
You
Welcomes
4
Geeks
solankimayank
Java - util package
Java-Collections
Java-HashTable
Java
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": "\n09 Oct, 2021"
},
{
"code": null,
"e": 288,
"s": 28,
"text": "As we all know enumeration defines java class type so do enumerations can have constructors, methods, and instance variables. The java.util.Hashtable.keys() method of Hashtable class in Java is used to get the enumeration of the keys present in the hashtable."
},
{
"code": null,
"e": 302,
"s": 288,
"text": "Illustration:"
},
{
"code": null,
"e": 311,
"s": 302,
"text": "Syntax: "
},
{
"code": null,
"e": 377,
"s": 311,
"text": "public Enumeration<K> keys()\nEnumeration enu = Hash_table.keys();"
},
{
"code": null,
"e": 436,
"s": 377,
"text": "Return value: An enumeration of the keys of the Hashtable."
},
{
"code": null,
"e": 447,
"s": 436,
"text": "Example 1:"
},
{
"code": null,
"e": 452,
"s": 447,
"text": "Java"
},
{
"code": "// Java Program to Illustrate keys() method// of Hashtable class // Importing utility classesimport java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an empty Hashtable // Declaring object of integer and string type Hashtable<Integer, String> hash_table = new Hashtable<Integer, String>(); // Inserting elements into the table // using put() method // Custom input elements hash_table.put(10, \"Geeks\"); hash_table.put(15, \"4\"); hash_table.put(20, \"Geeks\"); hash_table.put(25, \"Welcomes\"); hash_table.put(30, \"You\"); // Print and display all entered elements in object System.out.println(\"The Table is: \" + hash_table); // Creating an empty enumeration to store Enumeration enu = hash_table.keys(); // Display message System.out.println(\"The enumeration of keys are:\"); // Condition holds true till there is single element // remaining using hasMoreElements() method while (enu.hasMoreElements()) { // Displaying the Enumeration System.out.println(enu.nextElement()); } }}",
"e": 1694,
"s": 452,
"text": null
},
{
"code": null,
"e": 1800,
"s": 1694,
"text": "The Table is: {10=Geeks, 20=Geeks, 30=You, 15=4, 25=Welcomes}\nThe enumeration of keys are:\n10\n20\n30\n15\n25"
},
{
"code": null,
"e": 1813,
"s": 1802,
"text": "Example 2:"
},
{
"code": null,
"e": 1818,
"s": 1813,
"text": "Java"
},
{
"code": "// Java Program to illustrate keys() method// of Hashtable class // Importing utility classesimport java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an empty Hashtable // Declaring object of string and integer type Hashtable<String, Integer> hash_table = new Hashtable<String, Integer>(); // Inserting elements into the table // using put() method hash_table.put(\"Geeks\", 10); hash_table.put(\"4\", 15); hash_table.put(\"Geeks\", 20); hash_table.put(\"Welcomes\", 25); hash_table.put(\"You\", 30); // Displaying the Hashtable System.out.println(\"The Table is: \" + hash_table); // Creating an empty enumeration to store Enumeration enu = hash_table.keys(); // Display message System.out.println(\"The enumeration of keys are:\"); // Condition holds true till there is single element // remaining via hasMoreElements() method while (enu.hasMoreElements()) { // Displaying the enumeration System.out.println(enu.nextElement()); } }}",
"e": 3002,
"s": 1818,
"text": null
},
{
"code": null,
"e": 3104,
"s": 3002,
"text": "The Table is: {You=30, Welcomes=25, 4=15, Geeks=20}\nThe enumeration of keys are:\nYou\nWelcomes\n4\nGeeks"
},
{
"code": null,
"e": 3120,
"s": 3106,
"text": "solankimayank"
},
{
"code": null,
"e": 3140,
"s": 3120,
"text": "Java - util package"
},
{
"code": null,
"e": 3157,
"s": 3140,
"text": "Java-Collections"
},
{
"code": null,
"e": 3172,
"s": 3157,
"text": "Java-HashTable"
},
{
"code": null,
"e": 3177,
"s": 3172,
"text": "Java"
},
{
"code": null,
"e": 3182,
"s": 3177,
"text": "Java"
},
{
"code": null,
"e": 3199,
"s": 3182,
"text": "Java-Collections"
}
] |
How to get the number of pages in a PDF document using PHP ? | 29 Jul, 2020
PHP offers inbuilt functions and extensions that can be used to count the number of pages in a document with .pdf extension. There are numerous ways by which this can be done. Following are the methods used to count the pages in a pdf document:
Method 1: Using ImageMagic extension: The extension offered by PHP is ImageMagic which is able to understand the pdf document. The command used for the same is “identify” command. So the complete PHP function dedicated to the required purpose is Imagick::identifyImage().
Method 2: Using TCPDI function: Another way to do this is by using the TCPDI function. It does not use any PHP library for performing this task. The following line of code can be used.
$pageCount = (new TCPDI())->setSourceData((string)file_get_contents($fileName));
Method 3: Using pdfinfo: For Linux users, there is a faster way to count the number of pages in a pdf document than “identity” function. The command given below can be used for the same. Before executing this command, pdfinfo needs to be installed. This command works very fast when the number of pages in the pdf document is too large. For Windows users, the pdfinfo is available as pdfinfo.exe. Here is the command:
exec(‘/usr/bin/pdfinfo ‘.$tmpfname.’ | awk \’/Pages/ {print $2}\”, $output);
Method 4: Using pdf as text file: Now, let us see the code in PHP which will tell us the number of pages in a pdf document. In this code, we have created a function “count” containing the logic. Also, in the variable “path”, the path of the pdf whose number of pages are to be counted is written. Make sure, you write the path correctly.
<?php $path = 'pdf/GFG.pdf';$totalPages = count($path); echo $totoalPages; function count($path) { $pdf = file_get_contents($path); $number = preg_match_all("/\/Page\W/", $pdf, $dummy); return $number;} ?>
Output:
4
PHP-Misc
Picked
PHP
PHP Programs
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from localserver database and display on HTML table using PHP ?
Difference between HTTP GET and POST Methods
Different ways for passing data to view in Laravel
PHP | file_exists( ) Function
PHP | Ternary Operator
How to call PHP function on the click of a Button ?
How to fetch data from localserver database and display on HTML table using PHP ?
PHP | Ternary Operator
How to create admin login page using PHP?
How to send an email using PHPMailer ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Jul, 2020"
},
{
"code": null,
"e": 273,
"s": 28,
"text": "PHP offers inbuilt functions and extensions that can be used to count the number of pages in a document with .pdf extension. There are numerous ways by which this can be done. Following are the methods used to count the pages in a pdf document:"
},
{
"code": null,
"e": 545,
"s": 273,
"text": "Method 1: Using ImageMagic extension: The extension offered by PHP is ImageMagic which is able to understand the pdf document. The command used for the same is “identify” command. So the complete PHP function dedicated to the required purpose is Imagick::identifyImage()."
},
{
"code": null,
"e": 730,
"s": 545,
"text": "Method 2: Using TCPDI function: Another way to do this is by using the TCPDI function. It does not use any PHP library for performing this task. The following line of code can be used."
},
{
"code": null,
"e": 811,
"s": 730,
"text": "$pageCount = (new TCPDI())->setSourceData((string)file_get_contents($fileName));"
},
{
"code": null,
"e": 1229,
"s": 811,
"text": "Method 3: Using pdfinfo: For Linux users, there is a faster way to count the number of pages in a pdf document than “identity” function. The command given below can be used for the same. Before executing this command, pdfinfo needs to be installed. This command works very fast when the number of pages in the pdf document is too large. For Windows users, the pdfinfo is available as pdfinfo.exe. Here is the command:"
},
{
"code": null,
"e": 1306,
"s": 1229,
"text": "exec(‘/usr/bin/pdfinfo ‘.$tmpfname.’ | awk \\’/Pages/ {print $2}\\”, $output);"
},
{
"code": null,
"e": 1644,
"s": 1306,
"text": "Method 4: Using pdf as text file: Now, let us see the code in PHP which will tell us the number of pages in a pdf document. In this code, we have created a function “count” containing the logic. Also, in the variable “path”, the path of the pdf whose number of pages are to be counted is written. Make sure, you write the path correctly."
},
{
"code": "<?php $path = 'pdf/GFG.pdf';$totalPages = count($path); echo $totoalPages; function count($path) { $pdf = file_get_contents($path); $number = preg_match_all(\"/\\/Page\\W/\", $pdf, $dummy); return $number;} ?>",
"e": 1860,
"s": 1644,
"text": null
},
{
"code": null,
"e": 1868,
"s": 1860,
"text": "Output:"
},
{
"code": null,
"e": 1870,
"s": 1868,
"text": "4"
},
{
"code": null,
"e": 1879,
"s": 1870,
"text": "PHP-Misc"
},
{
"code": null,
"e": 1886,
"s": 1879,
"text": "Picked"
},
{
"code": null,
"e": 1890,
"s": 1886,
"text": "PHP"
},
{
"code": null,
"e": 1903,
"s": 1890,
"text": "PHP Programs"
},
{
"code": null,
"e": 1920,
"s": 1903,
"text": "Web Technologies"
},
{
"code": null,
"e": 1924,
"s": 1920,
"text": "PHP"
},
{
"code": null,
"e": 2022,
"s": 1924,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2104,
"s": 2022,
"text": "How to fetch data from localserver database and display on HTML table using PHP ?"
},
{
"code": null,
"e": 2149,
"s": 2104,
"text": "Difference between HTTP GET and POST Methods"
},
{
"code": null,
"e": 2200,
"s": 2149,
"text": "Different ways for passing data to view in Laravel"
},
{
"code": null,
"e": 2230,
"s": 2200,
"text": "PHP | file_exists( ) Function"
},
{
"code": null,
"e": 2253,
"s": 2230,
"text": "PHP | Ternary Operator"
},
{
"code": null,
"e": 2305,
"s": 2253,
"text": "How to call PHP function on the click of a Button ?"
},
{
"code": null,
"e": 2387,
"s": 2305,
"text": "How to fetch data from localserver database and display on HTML table using PHP ?"
},
{
"code": null,
"e": 2410,
"s": 2387,
"text": "PHP | Ternary Operator"
},
{
"code": null,
"e": 2452,
"s": 2410,
"text": "How to create admin login page using PHP?"
}
] |
Python slice() function | 30 Sep, 2021
Python slice() function returns a slice object.
A sequence of objects of any type(string, bytes, tuple, list or range) or the object which implements __getitem__() and __len__() method then this object can be sliced using slice() method.
Syntax:
slice(stop)
slice(start, stop, step)
Parameters:
start: Starting index where the slicing of object starts.
stop: Ending index where the slicing of object stops.
step: It is an optional argument that determines the increment between each index for slicing.
Return Type: Returns a sliced object containing elements in the given range only.
Note: If only one parameter is passed then start and step is considered to be None.
Python3
# Python program to demonstrate# slice() operator # String slicingString = 'GeeksforGeeks's1 = slice(3)s2 = slice(1, 5, 2) print("String slicing")print(String[s1])print(String[s2])
Output:
String slicing
Gee
ek
Python3
# Python program to demonstrate# slice() operator # List slicingL = [1, 2, 3, 4, 5]s1 = slice(3)s2 = slice(1, 5, 2)print("List slicing")print(L[s1])print(L[s2])
Output:
List slicing
[1, 2, 3]
[2, 4]
Python3
# Python program to demonstrate# slice() operator # Tuple slicingT = (1, 2, 3, 4, 5)s1 = slice(3)s2 = slice(1, 5, 2)print("\nTuple slicing")print(T[s1])print(T[s2])
Output:
Tuple slicing
(1, 2, 3)
(2, 4)
In Python, negative sequence indexes represent positions from the end of the array. slice() function can also have negative values. In that case, the iteration will be performed backward i.e from end to start.
Python3
# Python program to demonstrate# slice() operator # String slicingString = 'GeeksforGeeks's1 = slice(-3)s2 = slice(-1, -5, -2)print("String slicing")print(String[s1])print(String[s2]) # List slicingL = [1, 2, 3, 4, 5]s1 = slice(-3)s2 = slice(-1, -5, -2)print("\nList slicing")print(L[s1])print(L[s2]) # Tuple slicingT = (1, 2, 3, 4, 5)s1 = slice(-3)s2 = slice(-1, -5, -2)print("\nTuple slicing")print(T[s1])print(T[s2])
Output:
String slicing
GeeksforGe
se
List slicing
[1, 2]
[5, 3]
Tuple slicing
(1, 2)
(5, 3)
kumar_satyam
Python-Built-in-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n30 Sep, 2021"
},
{
"code": null,
"e": 102,
"s": 53,
"text": "Python slice() function returns a slice object. "
},
{
"code": null,
"e": 293,
"s": 102,
"text": "A sequence of objects of any type(string, bytes, tuple, list or range) or the object which implements __getitem__() and __len__() method then this object can be sliced using slice() method. "
},
{
"code": null,
"e": 302,
"s": 293,
"text": "Syntax: "
},
{
"code": null,
"e": 314,
"s": 302,
"text": "slice(stop)"
},
{
"code": null,
"e": 339,
"s": 314,
"text": "slice(start, stop, step)"
},
{
"code": null,
"e": 352,
"s": 339,
"text": "Parameters: "
},
{
"code": null,
"e": 410,
"s": 352,
"text": "start: Starting index where the slicing of object starts."
},
{
"code": null,
"e": 464,
"s": 410,
"text": "stop: Ending index where the slicing of object stops."
},
{
"code": null,
"e": 559,
"s": 464,
"text": "step: It is an optional argument that determines the increment between each index for slicing."
},
{
"code": null,
"e": 643,
"s": 559,
"text": "Return Type: Returns a sliced object containing elements in the given range only. "
},
{
"code": null,
"e": 727,
"s": 643,
"text": "Note: If only one parameter is passed then start and step is considered to be None."
},
{
"code": null,
"e": 735,
"s": 727,
"text": "Python3"
},
{
"code": "# Python program to demonstrate# slice() operator # String slicingString = 'GeeksforGeeks's1 = slice(3)s2 = slice(1, 5, 2) print(\"String slicing\")print(String[s1])print(String[s2])",
"e": 916,
"s": 735,
"text": null
},
{
"code": null,
"e": 924,
"s": 916,
"text": "Output:"
},
{
"code": null,
"e": 946,
"s": 924,
"text": "String slicing\nGee\nek"
},
{
"code": null,
"e": 954,
"s": 946,
"text": "Python3"
},
{
"code": "# Python program to demonstrate# slice() operator # List slicingL = [1, 2, 3, 4, 5]s1 = slice(3)s2 = slice(1, 5, 2)print(\"List slicing\")print(L[s1])print(L[s2])",
"e": 1115,
"s": 954,
"text": null
},
{
"code": null,
"e": 1123,
"s": 1115,
"text": "Output:"
},
{
"code": null,
"e": 1153,
"s": 1123,
"text": "List slicing\n[1, 2, 3]\n[2, 4]"
},
{
"code": null,
"e": 1161,
"s": 1153,
"text": "Python3"
},
{
"code": "# Python program to demonstrate# slice() operator # Tuple slicingT = (1, 2, 3, 4, 5)s1 = slice(3)s2 = slice(1, 5, 2)print(\"\\nTuple slicing\")print(T[s1])print(T[s2])",
"e": 1326,
"s": 1161,
"text": null
},
{
"code": null,
"e": 1334,
"s": 1326,
"text": "Output:"
},
{
"code": null,
"e": 1365,
"s": 1334,
"text": "Tuple slicing\n(1, 2, 3)\n(2, 4)"
},
{
"code": null,
"e": 1575,
"s": 1365,
"text": "In Python, negative sequence indexes represent positions from the end of the array. slice() function can also have negative values. In that case, the iteration will be performed backward i.e from end to start."
},
{
"code": null,
"e": 1583,
"s": 1575,
"text": "Python3"
},
{
"code": "# Python program to demonstrate# slice() operator # String slicingString = 'GeeksforGeeks's1 = slice(-3)s2 = slice(-1, -5, -2)print(\"String slicing\")print(String[s1])print(String[s2]) # List slicingL = [1, 2, 3, 4, 5]s1 = slice(-3)s2 = slice(-1, -5, -2)print(\"\\nList slicing\")print(L[s1])print(L[s2]) # Tuple slicingT = (1, 2, 3, 4, 5)s1 = slice(-3)s2 = slice(-1, -5, -2)print(\"\\nTuple slicing\")print(T[s1])print(T[s2])",
"e": 2003,
"s": 1583,
"text": null
},
{
"code": null,
"e": 2012,
"s": 2003,
"text": "Output: "
},
{
"code": null,
"e": 2098,
"s": 2012,
"text": "String slicing\nGeeksforGe\nse\n\nList slicing\n[1, 2]\n[5, 3]\n\nTuple slicing\n(1, 2)\n(5, 3)"
},
{
"code": null,
"e": 2111,
"s": 2098,
"text": "kumar_satyam"
},
{
"code": null,
"e": 2137,
"s": 2111,
"text": "Python-Built-in-functions"
},
{
"code": null,
"e": 2144,
"s": 2137,
"text": "Python"
}
] |
Project Idea | Third -Eye : Aid for Blind | 29 Jun, 2018
Project Title: Third Eye – Aid For Blind.
Introduction:This project aims to develop a complete portable aid(Raspberry Pi) for blind pedestrians and deal with problems in existing systems efficiently. The system designed will detect an object or obstacleusing ultrasonic sensors and gives audio instructions for guidance. It also gives informationabout people looking or waving to them using face recognition.
Assumption and Constraints
Maximum range of an ultrasonic sensor is 4m.
Model won’t be able to work accurately in the crowded area.
GPS is a satellite-based radio navigation system, so it can track predefined locations only.
Raspberry pi camera module has 5-megapixel resolution and it is capable of only taking video and pictures not sound.
Object detection and face detection, recognition has limitation over accuracy.
Conceptual framework:Features Provided:
It can detect objects with the help of Ultrasonic sensor.It can detect the name of the object with the help of YOLO algorithm.It can detect the face with the help Raspberry pi camera use with face detection and recognition process.It can tell the location of the person with the help of gps used.
It can detect objects with the help of Ultrasonic sensor.
It can detect the name of the object with the help of YOLO algorithm.
It can detect the face with the help Raspberry pi camera use with face detection and recognition process.
It can tell the location of the person with the help of gps used.
Diagrams: Relevant diagrams like ER-diagram, UML diagrams, etc
Output of Face Detection:
Output of YOLO algorithm:
Use Case diagram:
System Architecture:
Activity Diagram:
Algorithms
YOLO (You Only Look Once) algorithm use to detect object in background in real time.
Face recognition using OpenCV and haar-cascades classifiers.
Tensorflow used.
Tools Used:
Used Raspberry pi to make it portable.
Use train model to detect objects.
Python Ide.
Linux terminal.
Application:The World Health Organization (WHO) reported that there are 285 million visually-impaired people worldwide.Among these individuals, there are 39 million who are totally blind. The product developed is light in weight, compact hence does not cause fatigue to the user. So this helps the blind person to be self-dependent till particular extent by giving info of surrounding objects, person, and help in keeping the track of current location.
Team :
Chandan VanwariCharvi JainAkhil Bansal
Note: This project idea is contributed for ProGeek Cup 2.0- A project competition by GeeksforGeeks.
ProGeek 2.0
Project
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n29 Jun, 2018"
},
{
"code": null,
"e": 96,
"s": 54,
"text": "Project Title: Third Eye – Aid For Blind."
},
{
"code": null,
"e": 463,
"s": 96,
"text": "Introduction:This project aims to develop a complete portable aid(Raspberry Pi) for blind pedestrians and deal with problems in existing systems efficiently. The system designed will detect an object or obstacleusing ultrasonic sensors and gives audio instructions for guidance. It also gives informationabout people looking or waving to them using face recognition."
},
{
"code": null,
"e": 490,
"s": 463,
"text": "Assumption and Constraints"
},
{
"code": null,
"e": 535,
"s": 490,
"text": "Maximum range of an ultrasonic sensor is 4m."
},
{
"code": null,
"e": 595,
"s": 535,
"text": "Model won’t be able to work accurately in the crowded area."
},
{
"code": null,
"e": 688,
"s": 595,
"text": "GPS is a satellite-based radio navigation system, so it can track predefined locations only."
},
{
"code": null,
"e": 805,
"s": 688,
"text": "Raspberry pi camera module has 5-megapixel resolution and it is capable of only taking video and pictures not sound."
},
{
"code": null,
"e": 884,
"s": 805,
"text": "Object detection and face detection, recognition has limitation over accuracy."
},
{
"code": null,
"e": 924,
"s": 884,
"text": "Conceptual framework:Features Provided:"
},
{
"code": null,
"e": 1221,
"s": 924,
"text": "It can detect objects with the help of Ultrasonic sensor.It can detect the name of the object with the help of YOLO algorithm.It can detect the face with the help Raspberry pi camera use with face detection and recognition process.It can tell the location of the person with the help of gps used."
},
{
"code": null,
"e": 1279,
"s": 1221,
"text": "It can detect objects with the help of Ultrasonic sensor."
},
{
"code": null,
"e": 1349,
"s": 1279,
"text": "It can detect the name of the object with the help of YOLO algorithm."
},
{
"code": null,
"e": 1455,
"s": 1349,
"text": "It can detect the face with the help Raspberry pi camera use with face detection and recognition process."
},
{
"code": null,
"e": 1521,
"s": 1455,
"text": "It can tell the location of the person with the help of gps used."
},
{
"code": null,
"e": 1585,
"s": 1521,
"text": "Diagrams: Relevant diagrams like ER-diagram, UML diagrams, etc"
},
{
"code": null,
"e": 1611,
"s": 1585,
"text": "Output of Face Detection:"
},
{
"code": null,
"e": 1637,
"s": 1611,
"text": "Output of YOLO algorithm:"
},
{
"code": null,
"e": 1655,
"s": 1637,
"text": "Use Case diagram:"
},
{
"code": null,
"e": 1676,
"s": 1655,
"text": "System Architecture:"
},
{
"code": null,
"e": 1694,
"s": 1676,
"text": "Activity Diagram:"
},
{
"code": null,
"e": 1705,
"s": 1694,
"text": "Algorithms"
},
{
"code": null,
"e": 1790,
"s": 1705,
"text": "YOLO (You Only Look Once) algorithm use to detect object in background in real time."
},
{
"code": null,
"e": 1851,
"s": 1790,
"text": "Face recognition using OpenCV and haar-cascades classifiers."
},
{
"code": null,
"e": 1868,
"s": 1851,
"text": "Tensorflow used."
},
{
"code": null,
"e": 1880,
"s": 1868,
"text": "Tools Used:"
},
{
"code": null,
"e": 1919,
"s": 1880,
"text": "Used Raspberry pi to make it portable."
},
{
"code": null,
"e": 1954,
"s": 1919,
"text": "Use train model to detect objects."
},
{
"code": null,
"e": 1966,
"s": 1954,
"text": "Python Ide."
},
{
"code": null,
"e": 1982,
"s": 1966,
"text": "Linux terminal."
},
{
"code": null,
"e": 2435,
"s": 1982,
"text": "Application:The World Health Organization (WHO) reported that there are 285 million visually-impaired people worldwide.Among these individuals, there are 39 million who are totally blind. The product developed is light in weight, compact hence does not cause fatigue to the user. So this helps the blind person to be self-dependent till particular extent by giving info of surrounding objects, person, and help in keeping the track of current location."
},
{
"code": null,
"e": 2442,
"s": 2435,
"text": "Team :"
},
{
"code": null,
"e": 2481,
"s": 2442,
"text": "Chandan VanwariCharvi JainAkhil Bansal"
},
{
"code": null,
"e": 2581,
"s": 2481,
"text": "Note: This project idea is contributed for ProGeek Cup 2.0- A project competition by GeeksforGeeks."
},
{
"code": null,
"e": 2593,
"s": 2581,
"text": "ProGeek 2.0"
},
{
"code": null,
"e": 2601,
"s": 2593,
"text": "Project"
}
] |
Stein’s Algorithm for finding GCD | 04 Jul, 2022
Stein’s algorithm or binary GCD algorithm is an algorithm that computes the greatest common divisor of two non-negative integers. Stein’s algorithm replaces division with arithmetic shifts, comparisons, and subtraction.
Examples:
Input: a = 17, b = 34
Output : 17
Input: a = 50, b = 49
Output: 1
Algorithm to find GCD using Stein’s algorithm gcd(a, b)
If both a and b are 0, gcd is zero gcd(0, 0) = 0.gcd(a, 0) = a and gcd(0, b) = b because everything divides 0.If a and b are both even, gcd(a, b) = 2*gcd(a/2, b/2) because 2 is a common divisor. Multiplication with 2 can be done with bitwise shift operator.If a is even and b is odd, gcd(a, b) = gcd(a/2, b). Similarly, if a is odd and b is even, then gcd(a, b) = gcd(a, b/2). It is because 2 is not a common divisor.If both a and b are odd, then gcd(a, b) = gcd(|a-b|/2, b). Note that difference of two odd numbers is evenRepeat steps 3–5 until a = b, or until a = 0. In either case, the GCD is power(2, k) * b, where power(2, k) is 2 raise to the power of k and k is the number of common factors of 2 found in step 3.
If both a and b are 0, gcd is zero gcd(0, 0) = 0.
gcd(a, 0) = a and gcd(0, b) = b because everything divides 0.
If a and b are both even, gcd(a, b) = 2*gcd(a/2, b/2) because 2 is a common divisor. Multiplication with 2 can be done with bitwise shift operator.
If a is even and b is odd, gcd(a, b) = gcd(a/2, b). Similarly, if a is odd and b is even, then gcd(a, b) = gcd(a, b/2). It is because 2 is not a common divisor.
If both a and b are odd, then gcd(a, b) = gcd(|a-b|/2, b). Note that difference of two odd numbers is even
Repeat steps 3–5 until a = b, or until a = 0. In either case, the GCD is power(2, k) * b, where power(2, k) is 2 raise to the power of k and k is the number of common factors of 2 found in step 3.
Iterative Implementation
C++
Java
Python3
C#
PHP
Javascript
// Iterative C++ program to// implement Stein's Algorithm#include <bits/stdc++.h>using namespace std; // Function to implement// Stein's Algorithmint gcd(int a, int b){ /* GCD(0, b) == b; GCD(a, 0) == a, GCD(0, 0) == 0 */ if (a == 0) return b; if (b == 0) return a; /*Finding K, where K is the greatest power of 2 that divides both a and b. */ int k; for (k = 0; ((a | b) & 1) == 0; ++k) { a >>= 1; b >>= 1; } /* Dividing a by 2 until a becomes odd */ while ((a & 1) == 0) a >>= 1; /* From here on, 'a' is always odd. */ do { /* If b is even, remove all factor of 2 in b */ while ((b & 1) == 0) b >>= 1; /* Now a and b are both odd. Swap if necessary so a <= b, then set b = b - a (which is even).*/ if (a > b) swap(a, b); // Swap u and v. b = (b - a); }while (b != 0); /* restore common factors of 2 */ return a << k;} // Driver codeint main(){ int a = 34, b = 17; printf("Gcd of given numbers is %d\n", gcd(a, b)); return 0;}
// Iterative Java program to// implement Stein's Algorithmimport java.io.*; class GFG { // Function to implement Stein's // Algorithm static int gcd(int a, int b) { // GCD(0, b) == b; GCD(a, 0) == a, // GCD(0, 0) == 0 if (a == 0) return b; if (b == 0) return a; // Finding K, where K is the greatest // power of 2 that divides both a and b int k; for (k = 0; ((a | b) & 1) == 0; ++k) { a >>= 1; b >>= 1; } // Dividing a by 2 until a becomes odd while ((a & 1) == 0) a >>= 1; // From here on, 'a' is always odd. do { // If b is even, remove // all factor of 2 in b while ((b & 1) == 0) b >>= 1; // Now a and b are both odd. Swap // if necessary so a <= b, then set // b = b - a (which is even) if (a > b) { // Swap u and v. int temp = a; a = b; b = temp; } b = (b - a); } while (b != 0); // restore common factors of 2 return a << k; } // Driver code public static void main(String args[]) { int a = 34, b = 17; System.out.println("Gcd of given " + "numbers is " + gcd(a, b)); }} // This code is contributed by Nikita Tiwari
# Iterative Python 3 program to# implement Stein's Algorithm # Function to implement# Stein's Algorithm def gcd(a, b): # GCD(0, b) == b; GCD(a, 0) == a, # GCD(0, 0) == 0 if (a == 0): return b if (b == 0): return a # Finding K, where K is the # greatest power of 2 that # divides both a and b. k = 0 while(((a | b) & 1) == 0): a = a >> 1 b = b >> 1 k = k + 1 # Dividing a by 2 until a becomes odd while ((a & 1) == 0): a = a >> 1 # From here on, 'a' is always odd. while(b != 0): # If b is even, remove all # factor of 2 in b while ((b & 1) == 0): b = b >> 1 # Now a and b are both odd. Swap if # necessary so a <= b, then set # b = b - a (which is even). if (a > b): # Swap u and v. temp = a a = b b = temp b = (b - a) # restore common factors of 2 return (a << k) # Driver codea = 34b = 17 print("Gcd of given numbers is ", gcd(a, b)) # This code is contributed by Nikita Tiwari.
// Iterative C# program to implement// Stein's Algorithmusing System; class GFG { // Function to implement Stein's // Algorithm static int gcd(int a, int b) { // GCD(0, b) == b; GCD(a, 0) == a, // GCD(0, 0) == 0 if (a == 0) return b; if (b == 0) return a; // Finding K, where K is the greatest // power of 2 that divides both a and b int k; for (k = 0; ((a | b) & 1) == 0; ++k) { a >>= 1; b >>= 1; } // Dividing a by 2 until a becomes odd while ((a & 1) == 0) a >>= 1; // From here on, 'a' is always odd do { // If b is even, remove // all factor of 2 in b while ((b & 1) == 0) b >>= 1; /* Now a and b are both odd. Swap if necessary so a <= b, then set b = b - a (which is even).*/ if (a > b) { // Swap u and v. int temp = a; a = b; b = temp; } b = (b - a); } while (b != 0); /* restore common factors of 2 */ return a << k; } // Driver code public static void Main() { int a = 34, b = 17; Console.Write("Gcd of given " + "numbers is " + gcd(a, b)); }} // This code is contributed by nitin mittal
<?php// Iterative php program to// implement Stein's Algorithm // Function to implement// Stein's Algorithmfunction gcd($a, $b){ // GCD(0, b) == b; GCD(a, 0) == a, // GCD(0, 0) == 0 if ($a == 0) return $b; if ($b == 0) return $a; // Finding K, where K is the greatest // power of 2 that divides both a and b. $k; for ($k = 0; (($a | $b) & 1) == 0; ++$k) { $a >>= 1; $b >>= 1; } // Dividing a by 2 until a becomes odd while (($a & 1) == 0) $a >>= 1; // From here on, 'a' is always odd. do { // If b is even, remove // all factor of 2 in b while (($b & 1) == 0) $b >>= 1; // Now a and b are both odd. Swap // if necessary so a <= b, then set // b = b - a (which is even) if ($a > $b) swap($a, $b); // Swap u and v. $b = ($b - $a); } while ($b != 0); // restore common factors of 2 return $a << $k;} // Driver code$a = 34; $b = 17;echo "Gcd of given numbers is " . gcd($a, $b); // This code is contributed by ajit?>
<script> // Iterative JavaScript program to// implement Stein's Algorithm // Function to implement// Stein's Algorithmfunction gcd( a, b){ /* GCD(0, b) == b; GCD(a, 0) == a, GCD(0, 0) == 0 */ if (a == 0) return b; if (b == 0) return a; /*Finding K, where K is the greatest power of 2 that divides both a and b. */ let k; for (k = 0; ((a | b) & 1) == 0; ++k) { a >>= 1; b >>= 1; } /* Dividing a by 2 until a becomes odd */ while ((a & 1) == 0) a >>= 1; /* From here on, 'a' is always odd. */ do { /* If b is even, remove all factor of 2 in b */ while ((b & 1) == 0) b >>= 1; /* Now a and b are both odd. Swap if necessary so a <= b, then set b = b - a (which is even).*/ if (a > b){ let t = a; a = b; b = t; } b = (b - a); }while (b != 0); /* restore common factors of 2 */ return a << k;} // Driver code let a = 34, b = 17; document.write("Gcd of given numbers is "+ gcd(a, b)); // This code contributed by gauravrajput1 </script>
Gcd of given numbers is 17
Time Complexity: O(N*N)Auxiliary Space: O(1)
Recursive Implementation
C++
Java
Python3
C#
PHP
Javascript
// Recursive C++ program to// implement Stein's Algorithm#include <bits/stdc++.h>using namespace std; // Function to implement// Stein's Algorithmint gcd(int a, int b){ if (a == b) return a; // GCD(0, b) == b; GCD(a, 0) == a, // GCD(0, 0) == 0 if (a == 0) return b; if (b == 0) return a; // look for factors of 2 if (~a & 1) // a is even { if (b & 1) // b is odd return gcd(a >> 1, b); else // both a and b are even return gcd(a >> 1, b >> 1) << 1; } if (~b & 1) // a is odd, b is even return gcd(a, b >> 1); // reduce larger number if (a > b) return gcd((a - b) >> 1, b); return gcd((b - a) >> 1, a);} // Driver codeint main(){ int a = 34, b = 17; printf("Gcd of given numbers is %d\n", gcd(a, b)); return 0;}
// Recursive Java program to// implement Stein's Algorithmimport java.io.*; class GFG { // Function to implement // Stein's Algorithm static int gcd(int a, int b) { if (a == b) return a; // GCD(0, b) == b; GCD(a, 0) == a, // GCD(0, 0) == 0 if (a == 0) return b; if (b == 0) return a; // look for factors of 2 if ((~a & 1) == 1) // a is even { if ((b & 1) == 1) // b is odd return gcd(a >> 1, b); else // both a and b are even return gcd(a >> 1, b >> 1) << 1; } // a is odd, b is even if ((~b & 1) == 1) return gcd(a, b >> 1); // reduce larger number if (a > b) return gcd((a - b) >> 1, b); return gcd((b - a) >> 1, a); } // Driver code public static void main(String args[]) { int a = 34, b = 17; System.out.println("Gcd of given" + "numbers is " + gcd(a, b)); }} // This code is contributed by Nikita Tiwari
# Recursive Python 3 program to# implement Stein's Algorithm # Function to implement# Stein's Algorithm def gcd(a, b): if (a == b): return a # GCD(0, b) == b; GCD(a, 0) == a, # GCD(0, 0) == 0 if (a == 0): return b if (b == 0): return a # look for factors of 2 # a is even if ((~a & 1) == 1): # b is odd if ((b & 1) == 1): return gcd(a >> 1, b) else: # both a and b are even return (gcd(a >> 1, b >> 1) << 1) # a is odd, b is even if ((~b & 1) == 1): return gcd(a, b >> 1) # reduce larger number if (a > b): return gcd((a - b) >> 1, b) return gcd((b - a) >> 1, a) # Driver codea, b = 34, 17print("Gcd of given numbers is ", gcd(a, b)) # This code is contributed# by Nikita Tiwari.
// Recursive C# program to// implement Stein's Algorithmusing System; class GFG { // Function to implement // Stein's Algorithm static int gcd(int a, int b) { if (a == b) return a; // GCD(0, b) == b; // GCD(a, 0) == a, // GCD(0, 0) == 0 if (a == 0) return b; if (b == 0) return a; // look for factors of 2 // a is even if ((~a & 1) == 1) { // b is odd if ((b & 1) == 1) return gcd(a >> 1, b); else // both a and b are even return gcd(a >> 1, b >> 1) << 1; } // a is odd, b is even if ((~b & 1) == 1) return gcd(a, b >> 1); // reduce larger number if (a > b) return gcd((a - b) >> 1, b); return gcd((b - a) >> 1, a); } // Driver code public static void Main() { int a = 34, b = 17; Console.Write("Gcd of given" + "numbers is " + gcd(a, b)); }} // This code is contributed by nitin mittal.
<?php// Recursive PHP program to// implement Stein's Algorithm // Function to implement// Stein's Algorithmfunction gcd($a, $b){ if ($a == $b) return $a; /* GCD(0, b) == b; GCD(a, 0) == a, GCD(0, 0) == 0 */ if ($a == 0) return $b; if ($b == 0) return $a; // look for factors of 2 if (~$a & 1) // a is even { if ($b & 1) // b is odd return gcd($a >> 1, $b); else // both a and b are even return gcd($a >> 1, $b >> 1) << 1; } if (~$b & 1) // a is odd, b is even return gcd($a, $b >> 1); // reduce larger number if ($a > $b) return gcd(($a - $b) >> 1, $b); return gcd(($b - $a) >> 1, $a);} // Driver code$a = 34; $b = 17;echo "Gcd of given numbers is: ", gcd($a, $b); // This code is contributed by aj_36?>
<script> // JavaScript program to// implement Stein's Algorithm // Function to implement // Stein's Algorithm function gcd(a, b) { if (a == b) return a; // GCD(0, b) == b; GCD(a, 0) == a, // GCD(0, 0) == 0 if (a == 0) return b; if (b == 0) return a; // look for factors of 2 if ((~a & 1) == 1) // a is even { if ((b & 1) == 1) // b is odd return gcd(a >> 1, b); else // both a and b are even return gcd(a >> 1, b >> 1) << 1; } // a is odd, b is even if ((~b & 1) == 1) return gcd(a, b >> 1); // reduce larger number if (a > b) return gcd((a - b) >> 1, b); return gcd((b - a) >> 1, a); } // Driver Code let a = 34, b = 17; document.write("Gcd of given " + "numbers is " + gcd(a, b)); </script>
Gcd of given numbers is 17
Time Complexity: O(N*N) where N is the number of bits in the larger number.Auxiliary Space: O(N*N) where N is the number of bits in the larger number.
You may also like – Basic and Extended Euclidean Algorithm
Advantages over Euclid’s GCD Algorithm
Stein’s algorithm is optimized version of Euclid’s GCD Algorithm.
it is more efficient by using the bitwise shift operator.
This article is contributed by Aarti_Rathi and Rahul Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nitin mittal
jit_t
sodiumcloridep
GauravRajput1
code_hunt
amartyaghoshgfg
germanshephered48
amansinghkushwaha2003
codewithrathi
bencivengadante
GCD-LCM
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Prime Numbers
Minimum number of jumps to reach end
Find minimum number of coins that make a given value
The Knight's tour problem | Backtracking-1
Algorithm to solve Rubik's Cube
Program for Decimal to Binary Conversion
Modulo 10^9+7 (1000000007)
Modulo Operator (%) in C/C++ with Examples | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n04 Jul, 2022"
},
{
"code": null,
"e": 272,
"s": 52,
"text": "Stein’s algorithm or binary GCD algorithm is an algorithm that computes the greatest common divisor of two non-negative integers. Stein’s algorithm replaces division with arithmetic shifts, comparisons, and subtraction."
},
{
"code": null,
"e": 283,
"s": 272,
"text": "Examples: "
},
{
"code": null,
"e": 351,
"s": 283,
"text": "Input: a = 17, b = 34 \nOutput : 17\n\nInput: a = 50, b = 49\nOutput: 1"
},
{
"code": null,
"e": 408,
"s": 351,
"text": "Algorithm to find GCD using Stein’s algorithm gcd(a, b) "
},
{
"code": null,
"e": 1128,
"s": 408,
"text": "If both a and b are 0, gcd is zero gcd(0, 0) = 0.gcd(a, 0) = a and gcd(0, b) = b because everything divides 0.If a and b are both even, gcd(a, b) = 2*gcd(a/2, b/2) because 2 is a common divisor. Multiplication with 2 can be done with bitwise shift operator.If a is even and b is odd, gcd(a, b) = gcd(a/2, b). Similarly, if a is odd and b is even, then gcd(a, b) = gcd(a, b/2). It is because 2 is not a common divisor.If both a and b are odd, then gcd(a, b) = gcd(|a-b|/2, b). Note that difference of two odd numbers is evenRepeat steps 3–5 until a = b, or until a = 0. In either case, the GCD is power(2, k) * b, where power(2, k) is 2 raise to the power of k and k is the number of common factors of 2 found in step 3."
},
{
"code": null,
"e": 1178,
"s": 1128,
"text": "If both a and b are 0, gcd is zero gcd(0, 0) = 0."
},
{
"code": null,
"e": 1240,
"s": 1178,
"text": "gcd(a, 0) = a and gcd(0, b) = b because everything divides 0."
},
{
"code": null,
"e": 1388,
"s": 1240,
"text": "If a and b are both even, gcd(a, b) = 2*gcd(a/2, b/2) because 2 is a common divisor. Multiplication with 2 can be done with bitwise shift operator."
},
{
"code": null,
"e": 1549,
"s": 1388,
"text": "If a is even and b is odd, gcd(a, b) = gcd(a/2, b). Similarly, if a is odd and b is even, then gcd(a, b) = gcd(a, b/2). It is because 2 is not a common divisor."
},
{
"code": null,
"e": 1656,
"s": 1549,
"text": "If both a and b are odd, then gcd(a, b) = gcd(|a-b|/2, b). Note that difference of two odd numbers is even"
},
{
"code": null,
"e": 1853,
"s": 1656,
"text": "Repeat steps 3–5 until a = b, or until a = 0. In either case, the GCD is power(2, k) * b, where power(2, k) is 2 raise to the power of k and k is the number of common factors of 2 found in step 3."
},
{
"code": null,
"e": 1878,
"s": 1853,
"text": "Iterative Implementation"
},
{
"code": null,
"e": 1882,
"s": 1878,
"text": "C++"
},
{
"code": null,
"e": 1887,
"s": 1882,
"text": "Java"
},
{
"code": null,
"e": 1895,
"s": 1887,
"text": "Python3"
},
{
"code": null,
"e": 1898,
"s": 1895,
"text": "C#"
},
{
"code": null,
"e": 1902,
"s": 1898,
"text": "PHP"
},
{
"code": null,
"e": 1913,
"s": 1902,
"text": "Javascript"
},
{
"code": "// Iterative C++ program to// implement Stein's Algorithm#include <bits/stdc++.h>using namespace std; // Function to implement// Stein's Algorithmint gcd(int a, int b){ /* GCD(0, b) == b; GCD(a, 0) == a, GCD(0, 0) == 0 */ if (a == 0) return b; if (b == 0) return a; /*Finding K, where K is the greatest power of 2 that divides both a and b. */ int k; for (k = 0; ((a | b) & 1) == 0; ++k) { a >>= 1; b >>= 1; } /* Dividing a by 2 until a becomes odd */ while ((a & 1) == 0) a >>= 1; /* From here on, 'a' is always odd. */ do { /* If b is even, remove all factor of 2 in b */ while ((b & 1) == 0) b >>= 1; /* Now a and b are both odd. Swap if necessary so a <= b, then set b = b - a (which is even).*/ if (a > b) swap(a, b); // Swap u and v. b = (b - a); }while (b != 0); /* restore common factors of 2 */ return a << k;} // Driver codeint main(){ int a = 34, b = 17; printf(\"Gcd of given numbers is %d\\n\", gcd(a, b)); return 0;}",
"e": 3032,
"s": 1913,
"text": null
},
{
"code": "// Iterative Java program to// implement Stein's Algorithmimport java.io.*; class GFG { // Function to implement Stein's // Algorithm static int gcd(int a, int b) { // GCD(0, b) == b; GCD(a, 0) == a, // GCD(0, 0) == 0 if (a == 0) return b; if (b == 0) return a; // Finding K, where K is the greatest // power of 2 that divides both a and b int k; for (k = 0; ((a | b) & 1) == 0; ++k) { a >>= 1; b >>= 1; } // Dividing a by 2 until a becomes odd while ((a & 1) == 0) a >>= 1; // From here on, 'a' is always odd. do { // If b is even, remove // all factor of 2 in b while ((b & 1) == 0) b >>= 1; // Now a and b are both odd. Swap // if necessary so a <= b, then set // b = b - a (which is even) if (a > b) { // Swap u and v. int temp = a; a = b; b = temp; } b = (b - a); } while (b != 0); // restore common factors of 2 return a << k; } // Driver code public static void main(String args[]) { int a = 34, b = 17; System.out.println(\"Gcd of given \" + \"numbers is \" + gcd(a, b)); }} // This code is contributed by Nikita Tiwari",
"e": 4498,
"s": 3032,
"text": null
},
{
"code": "# Iterative Python 3 program to# implement Stein's Algorithm # Function to implement# Stein's Algorithm def gcd(a, b): # GCD(0, b) == b; GCD(a, 0) == a, # GCD(0, 0) == 0 if (a == 0): return b if (b == 0): return a # Finding K, where K is the # greatest power of 2 that # divides both a and b. k = 0 while(((a | b) & 1) == 0): a = a >> 1 b = b >> 1 k = k + 1 # Dividing a by 2 until a becomes odd while ((a & 1) == 0): a = a >> 1 # From here on, 'a' is always odd. while(b != 0): # If b is even, remove all # factor of 2 in b while ((b & 1) == 0): b = b >> 1 # Now a and b are both odd. Swap if # necessary so a <= b, then set # b = b - a (which is even). if (a > b): # Swap u and v. temp = a a = b b = temp b = (b - a) # restore common factors of 2 return (a << k) # Driver codea = 34b = 17 print(\"Gcd of given numbers is \", gcd(a, b)) # This code is contributed by Nikita Tiwari.",
"e": 5590,
"s": 4498,
"text": null
},
{
"code": "// Iterative C# program to implement// Stein's Algorithmusing System; class GFG { // Function to implement Stein's // Algorithm static int gcd(int a, int b) { // GCD(0, b) == b; GCD(a, 0) == a, // GCD(0, 0) == 0 if (a == 0) return b; if (b == 0) return a; // Finding K, where K is the greatest // power of 2 that divides both a and b int k; for (k = 0; ((a | b) & 1) == 0; ++k) { a >>= 1; b >>= 1; } // Dividing a by 2 until a becomes odd while ((a & 1) == 0) a >>= 1; // From here on, 'a' is always odd do { // If b is even, remove // all factor of 2 in b while ((b & 1) == 0) b >>= 1; /* Now a and b are both odd. Swap if necessary so a <= b, then set b = b - a (which is even).*/ if (a > b) { // Swap u and v. int temp = a; a = b; b = temp; } b = (b - a); } while (b != 0); /* restore common factors of 2 */ return a << k; } // Driver code public static void Main() { int a = 34, b = 17; Console.Write(\"Gcd of given \" + \"numbers is \" + gcd(a, b)); }} // This code is contributed by nitin mittal",
"e": 7016,
"s": 5590,
"text": null
},
{
"code": "<?php// Iterative php program to// implement Stein's Algorithm // Function to implement// Stein's Algorithmfunction gcd($a, $b){ // GCD(0, b) == b; GCD(a, 0) == a, // GCD(0, 0) == 0 if ($a == 0) return $b; if ($b == 0) return $a; // Finding K, where K is the greatest // power of 2 that divides both a and b. $k; for ($k = 0; (($a | $b) & 1) == 0; ++$k) { $a >>= 1; $b >>= 1; } // Dividing a by 2 until a becomes odd while (($a & 1) == 0) $a >>= 1; // From here on, 'a' is always odd. do { // If b is even, remove // all factor of 2 in b while (($b & 1) == 0) $b >>= 1; // Now a and b are both odd. Swap // if necessary so a <= b, then set // b = b - a (which is even) if ($a > $b) swap($a, $b); // Swap u and v. $b = ($b - $a); } while ($b != 0); // restore common factors of 2 return $a << $k;} // Driver code$a = 34; $b = 17;echo \"Gcd of given numbers is \" . gcd($a, $b); // This code is contributed by ajit?>",
"e": 8131,
"s": 7016,
"text": null
},
{
"code": "<script> // Iterative JavaScript program to// implement Stein's Algorithm // Function to implement// Stein's Algorithmfunction gcd( a, b){ /* GCD(0, b) == b; GCD(a, 0) == a, GCD(0, 0) == 0 */ if (a == 0) return b; if (b == 0) return a; /*Finding K, where K is the greatest power of 2 that divides both a and b. */ let k; for (k = 0; ((a | b) & 1) == 0; ++k) { a >>= 1; b >>= 1; } /* Dividing a by 2 until a becomes odd */ while ((a & 1) == 0) a >>= 1; /* From here on, 'a' is always odd. */ do { /* If b is even, remove all factor of 2 in b */ while ((b & 1) == 0) b >>= 1; /* Now a and b are both odd. Swap if necessary so a <= b, then set b = b - a (which is even).*/ if (a > b){ let t = a; a = b; b = t; } b = (b - a); }while (b != 0); /* restore common factors of 2 */ return a << k;} // Driver code let a = 34, b = 17; document.write(\"Gcd of given numbers is \"+ gcd(a, b)); // This code contributed by gauravrajput1 </script>",
"e": 9269,
"s": 8131,
"text": null
},
{
"code": null,
"e": 9296,
"s": 9269,
"text": "Gcd of given numbers is 17"
},
{
"code": null,
"e": 9341,
"s": 9296,
"text": "Time Complexity: O(N*N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 9366,
"s": 9341,
"text": "Recursive Implementation"
},
{
"code": null,
"e": 9370,
"s": 9366,
"text": "C++"
},
{
"code": null,
"e": 9375,
"s": 9370,
"text": "Java"
},
{
"code": null,
"e": 9383,
"s": 9375,
"text": "Python3"
},
{
"code": null,
"e": 9386,
"s": 9383,
"text": "C#"
},
{
"code": null,
"e": 9390,
"s": 9386,
"text": "PHP"
},
{
"code": null,
"e": 9401,
"s": 9390,
"text": "Javascript"
},
{
"code": "// Recursive C++ program to// implement Stein's Algorithm#include <bits/stdc++.h>using namespace std; // Function to implement// Stein's Algorithmint gcd(int a, int b){ if (a == b) return a; // GCD(0, b) == b; GCD(a, 0) == a, // GCD(0, 0) == 0 if (a == 0) return b; if (b == 0) return a; // look for factors of 2 if (~a & 1) // a is even { if (b & 1) // b is odd return gcd(a >> 1, b); else // both a and b are even return gcd(a >> 1, b >> 1) << 1; } if (~b & 1) // a is odd, b is even return gcd(a, b >> 1); // reduce larger number if (a > b) return gcd((a - b) >> 1, b); return gcd((b - a) >> 1, a);} // Driver codeint main(){ int a = 34, b = 17; printf(\"Gcd of given numbers is %d\\n\", gcd(a, b)); return 0;}",
"e": 10236,
"s": 9401,
"text": null
},
{
"code": "// Recursive Java program to// implement Stein's Algorithmimport java.io.*; class GFG { // Function to implement // Stein's Algorithm static int gcd(int a, int b) { if (a == b) return a; // GCD(0, b) == b; GCD(a, 0) == a, // GCD(0, 0) == 0 if (a == 0) return b; if (b == 0) return a; // look for factors of 2 if ((~a & 1) == 1) // a is even { if ((b & 1) == 1) // b is odd return gcd(a >> 1, b); else // both a and b are even return gcd(a >> 1, b >> 1) << 1; } // a is odd, b is even if ((~b & 1) == 1) return gcd(a, b >> 1); // reduce larger number if (a > b) return gcd((a - b) >> 1, b); return gcd((b - a) >> 1, a); } // Driver code public static void main(String args[]) { int a = 34, b = 17; System.out.println(\"Gcd of given\" + \"numbers is \" + gcd(a, b)); }} // This code is contributed by Nikita Tiwari",
"e": 11325,
"s": 10236,
"text": null
},
{
"code": "# Recursive Python 3 program to# implement Stein's Algorithm # Function to implement# Stein's Algorithm def gcd(a, b): if (a == b): return a # GCD(0, b) == b; GCD(a, 0) == a, # GCD(0, 0) == 0 if (a == 0): return b if (b == 0): return a # look for factors of 2 # a is even if ((~a & 1) == 1): # b is odd if ((b & 1) == 1): return gcd(a >> 1, b) else: # both a and b are even return (gcd(a >> 1, b >> 1) << 1) # a is odd, b is even if ((~b & 1) == 1): return gcd(a, b >> 1) # reduce larger number if (a > b): return gcd((a - b) >> 1, b) return gcd((b - a) >> 1, a) # Driver codea, b = 34, 17print(\"Gcd of given numbers is \", gcd(a, b)) # This code is contributed# by Nikita Tiwari.",
"e": 12148,
"s": 11325,
"text": null
},
{
"code": "// Recursive C# program to// implement Stein's Algorithmusing System; class GFG { // Function to implement // Stein's Algorithm static int gcd(int a, int b) { if (a == b) return a; // GCD(0, b) == b; // GCD(a, 0) == a, // GCD(0, 0) == 0 if (a == 0) return b; if (b == 0) return a; // look for factors of 2 // a is even if ((~a & 1) == 1) { // b is odd if ((b & 1) == 1) return gcd(a >> 1, b); else // both a and b are even return gcd(a >> 1, b >> 1) << 1; } // a is odd, b is even if ((~b & 1) == 1) return gcd(a, b >> 1); // reduce larger number if (a > b) return gcd((a - b) >> 1, b); return gcd((b - a) >> 1, a); } // Driver code public static void Main() { int a = 34, b = 17; Console.Write(\"Gcd of given\" + \"numbers is \" + gcd(a, b)); }} // This code is contributed by nitin mittal.",
"e": 13246,
"s": 12148,
"text": null
},
{
"code": "<?php// Recursive PHP program to// implement Stein's Algorithm // Function to implement// Stein's Algorithmfunction gcd($a, $b){ if ($a == $b) return $a; /* GCD(0, b) == b; GCD(a, 0) == a, GCD(0, 0) == 0 */ if ($a == 0) return $b; if ($b == 0) return $a; // look for factors of 2 if (~$a & 1) // a is even { if ($b & 1) // b is odd return gcd($a >> 1, $b); else // both a and b are even return gcd($a >> 1, $b >> 1) << 1; } if (~$b & 1) // a is odd, b is even return gcd($a, $b >> 1); // reduce larger number if ($a > $b) return gcd(($a - $b) >> 1, $b); return gcd(($b - $a) >> 1, $a);} // Driver code$a = 34; $b = 17;echo \"Gcd of given numbers is: \", gcd($a, $b); // This code is contributed by aj_36?>",
"e": 14088,
"s": 13246,
"text": null
},
{
"code": "<script> // JavaScript program to// implement Stein's Algorithm // Function to implement // Stein's Algorithm function gcd(a, b) { if (a == b) return a; // GCD(0, b) == b; GCD(a, 0) == a, // GCD(0, 0) == 0 if (a == 0) return b; if (b == 0) return a; // look for factors of 2 if ((~a & 1) == 1) // a is even { if ((b & 1) == 1) // b is odd return gcd(a >> 1, b); else // both a and b are even return gcd(a >> 1, b >> 1) << 1; } // a is odd, b is even if ((~b & 1) == 1) return gcd(a, b >> 1); // reduce larger number if (a > b) return gcd((a - b) >> 1, b); return gcd((b - a) >> 1, a); } // Driver Code let a = 34, b = 17; document.write(\"Gcd of given \" + \"numbers is \" + gcd(a, b)); </script>",
"e": 15080,
"s": 14088,
"text": null
},
{
"code": null,
"e": 15107,
"s": 15080,
"text": "Gcd of given numbers is 17"
},
{
"code": null,
"e": 15258,
"s": 15107,
"text": "Time Complexity: O(N*N) where N is the number of bits in the larger number.Auxiliary Space: O(N*N) where N is the number of bits in the larger number."
},
{
"code": null,
"e": 15317,
"s": 15258,
"text": "You may also like – Basic and Extended Euclidean Algorithm"
},
{
"code": null,
"e": 15356,
"s": 15317,
"text": "Advantages over Euclid’s GCD Algorithm"
},
{
"code": null,
"e": 15422,
"s": 15356,
"text": "Stein’s algorithm is optimized version of Euclid’s GCD Algorithm."
},
{
"code": null,
"e": 15480,
"s": 15422,
"text": "it is more efficient by using the bitwise shift operator."
},
{
"code": null,
"e": 15917,
"s": 15480,
"text": "This article is contributed by Aarti_Rathi and Rahul Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 15930,
"s": 15917,
"text": "nitin mittal"
},
{
"code": null,
"e": 15936,
"s": 15930,
"text": "jit_t"
},
{
"code": null,
"e": 15951,
"s": 15936,
"text": "sodiumcloridep"
},
{
"code": null,
"e": 15965,
"s": 15951,
"text": "GauravRajput1"
},
{
"code": null,
"e": 15975,
"s": 15965,
"text": "code_hunt"
},
{
"code": null,
"e": 15991,
"s": 15975,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 16009,
"s": 15991,
"text": "germanshephered48"
},
{
"code": null,
"e": 16031,
"s": 16009,
"text": "amansinghkushwaha2003"
},
{
"code": null,
"e": 16045,
"s": 16031,
"text": "codewithrathi"
},
{
"code": null,
"e": 16061,
"s": 16045,
"text": "bencivengadante"
},
{
"code": null,
"e": 16069,
"s": 16061,
"text": "GCD-LCM"
},
{
"code": null,
"e": 16082,
"s": 16069,
"text": "Mathematical"
},
{
"code": null,
"e": 16095,
"s": 16082,
"text": "Mathematical"
},
{
"code": null,
"e": 16193,
"s": 16095,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 16217,
"s": 16193,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 16238,
"s": 16217,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 16252,
"s": 16238,
"text": "Prime Numbers"
},
{
"code": null,
"e": 16289,
"s": 16252,
"text": "Minimum number of jumps to reach end"
},
{
"code": null,
"e": 16342,
"s": 16289,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 16385,
"s": 16342,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 16417,
"s": 16385,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 16458,
"s": 16417,
"text": "Program for Decimal to Binary Conversion"
},
{
"code": null,
"e": 16485,
"s": 16458,
"text": "Modulo 10^9+7 (1000000007)"
}
] |
Rearrange a binary string as alternate x and y occurrences | 09 Jun, 2022
Given a binary string s and two integers x and y are given. Task is to arrange the given string in such a way so that ‘0’ comes X-time then ‘1’ comes Y-time and so on until one of the ‘0’ or ‘1’ is finished. Then concatenate rest of the string and print the final string. Given : x or y can not be 0Examples:
Input : s = "0011"
x = 1
y = 1
Output : 0101
x is 1 and y is 1. So first we print
'0' one time the '1' one time and
then we print '0', after printing '0',
all 0's are vanished from the given
string so we concatenate rest of the
string which is '1'.
Input : s = '1011011'
x = 1
y = 1
Output : 0101111
1. Count number of 0’s and 1’s in the string. 2. Run a loop until either one of the alphabets is finished. 2.1. First print ‘0’ upto x and decrement count of 0. 2.2. Then print ‘1’ upto y and decrement count of 1.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to arrange given string#include <bits/stdc++.h>using namespace std; // Function which arrange the given stringvoid arrangeString(string str, int x, int y){ int count_0 = 0; int count_1 = 0; int len = str.length(); // Counting number of 0's and 1's in the // given string. for (int i = 0; i < len; i++) { if (str[i] == '0') count_0++; else count_1++; } // Printing first all 0's x-times // and decrement count of 0's x-times // and do the similar task with '1' while (count_0 > 0 || count_1 > 0) { for (int j = 0; j < x && count_0 > 0; j++) { if (count_0 > 0) { cout << "0"; count_0--; } } for (int j = 0; j < y && count_1 > 0; j++) { if (count_1 > 0) { cout << "1"; count_1--; } } }} // Driver Codeint main(){ string str = "01101101101101101000000"; int x = 1; int y = 2; arrangeString(str, x, y); return 0;}
// Java program to arrange given stringimport java.io.*; class GFG{ // Function which arrange the given string static void arrangeString(String str, int x, int y) { int count_0 = 0; int count_1 = 0; int len = str.length(); // Counting number of 0's and 1's in the // given string. for (int i = 0; i < len; i++) { if (str.charAt(i) == '0') count_0++; else count_1++; } // Printing first all 0's x-times // and decrement count of 0's x-times // and do the similar task with '1' while (count_0 > 0 || count_1 > 0) { for (int j = 0; j < x && count_0 > 0; j++) { if (count_0 > 0) { System.out.print ("0"); count_0--; } } for (int j = 0; j < y && count_1 > 0; j++) { if (count_1 > 0) { System.out.print("1"); count_1--; } } } } // Driver Code public static void main (String[] args) { String str = "01101101101101101000000"; int x = 1; int y = 2; arrangeString(str, x, y); }} // This code is contributed by vt_m.
# Python3 program to arrange given string # Function which arrange the given stringdef arrangeString(str1,x,y): count_0=0 count_1 =0 n = len(str1) # Counting number of 0's and 1's in the # given string. for i in range(n): if str1[i] == '0': count_0 +=1 else: count_1 +=1 # Printing first all 0's x-times # and decrement count of 0's x-times # and do the similar task with '1' while count_0>0 or count_1>0: for i in range(0,x): if count_0>0: print("0",end="") count_0 -=1 for j in range(0,y): if count_1>0: print("1",end="") count_1 -=1 # Driver codeif __name__=='__main__': str1 = "01101101101101101000000" x = 1 y = 2 arrangeString(str1, x, y) # This code is contributed by# Shrikant13
// C# program to arrange given stringusing System; class GFG { // Function which arrange the // given string static void arrangeString(string str, int x, int y) { int count_0 = 0; int count_1 = 0; int len = str.Length; // Counting number of 0's and 1's // in the given string. for (int i = 0; i < len; i++) { if (str[i] == '0') count_0++; else count_1++; } // Printing first all 0's x-times // and decrement count of 0's x-times // and do the similar task with '1' while (count_0 > 0 || count_1 > 0) { for (int j = 0; j < x && count_0 > 0; j++) { if (count_0 > 0) { Console.Write("0"); count_0--; } } for (int j = 0; j < y && count_1 > 0; j++) { if (count_1 > 0) { Console.Write("1"); count_1--; } } } } // Driver Code public static void Main () { string str = "01101101101101101000000"; int x = 1; int y = 2; arrangeString(str, x, y); }} // This code is contributed by vt_m.
<?php// PHP program to arrange given string // Function which arrange// the given stringfunction arrangeString($str, $x, $y){ $count_0 = 0; $count_1 = 0; $len =strlen($str); // Counting number of 0's and // 1's in the given string. for ( $i = 0; $i < $len; $i++) { if ($str[$i] == '0') $count_0++; else $count_1++; } // Printing first all 0's x-times // and decrement count of 0's x-times // and do the similar task with '1' while ($count_0 > 0 || $count_1 > 0) { for ($j = 0; $j < $x && $count_0 > 0; $j++) { if ($count_0 > 0) { echo "0"; $count_0--; } } for ($j = 0; $j < $y && $count_1 > 0; $j++) { if ($count_1 > 0) { echo "1"; $count_1--; } } }} // Driver Code $str = "01101101101101101000000"; $x = 1; $y = 2; arrangeString($str, $x, $y); // This code is contributed by m_kit?>
<script> // Javascript program to arrange given string // Function which arrange the // given string function arrangeString(str, x, y) { let count_0 = 0; let count_1 = 0; let len = str.length; // Counting number of 0's and 1's // in the given string. for (let i = 0; i < len; i++) { if (str[i] == '0') count_0++; else count_1++; } // Printing first all 0's x-times // and decrement count of 0's x-times // and do the similar task with '1' while (count_0 > 0 || count_1 > 0) { for (let j = 0; j < x && count_0 > 0; j++) { if (count_0 > 0) { document.write("0"); count_0--; } } for (let j = 0; j < y && count_1 > 0; j++) { if (count_1 > 0) { document.write("1"); count_1--; } } } } let str = "01101101101101101000000"; let x = 1; let y = 2; arrangeString(str, x, y); </script>
Output:
01101101101101101000000
Time Complexity: O(N2)Auxiliary Space: O(1)
This article is contributed by Sahil Rajput. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
vt_m
jit_t
shrikanth13
decode2207
codewithmini
array-rearrange
binary-string
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different Methods to Reverse a String in C++
Check for Balanced Brackets in an expression (well-formedness) using Stack
Python program to check if a string is palindrome or not
KMP Algorithm for Pattern Searching
Longest Palindromic Substring | Set 1
Length of the longest substring without repeating characters
Convert string to char array in C++
Top 50 String Coding Problems for Interviews
Check whether two strings are anagram of each other
What is Data Structure: Types, Classifications and Applications | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n09 Jun, 2022"
},
{
"code": null,
"e": 363,
"s": 52,
"text": "Given a binary string s and two integers x and y are given. Task is to arrange the given string in such a way so that ‘0’ comes X-time then ‘1’ comes Y-time and so on until one of the ‘0’ or ‘1’ is finished. Then concatenate rest of the string and print the final string. Given : x or y can not be 0Examples: "
},
{
"code": null,
"e": 699,
"s": 363,
"text": "Input : s = \"0011\"\n x = 1\n y = 1\nOutput : 0101\nx is 1 and y is 1. So first we print\n'0' one time the '1' one time and \nthen we print '0', after printing '0',\nall 0's are vanished from the given\nstring so we concatenate rest of the \nstring which is '1'. \n\nInput : s = '1011011'\n x = 1\n y = 1\nOutput : 0101111"
},
{
"code": null,
"e": 925,
"s": 701,
"text": "1. Count number of 0’s and 1’s in the string. 2. Run a loop until either one of the alphabets is finished. 2.1. First print ‘0’ upto x and decrement count of 0. 2.2. Then print ‘1’ upto y and decrement count of 1. "
},
{
"code": null,
"e": 929,
"s": 925,
"text": "C++"
},
{
"code": null,
"e": 934,
"s": 929,
"text": "Java"
},
{
"code": null,
"e": 942,
"s": 934,
"text": "Python3"
},
{
"code": null,
"e": 945,
"s": 942,
"text": "C#"
},
{
"code": null,
"e": 949,
"s": 945,
"text": "PHP"
},
{
"code": null,
"e": 960,
"s": 949,
"text": "Javascript"
},
{
"code": "// C++ program to arrange given string#include <bits/stdc++.h>using namespace std; // Function which arrange the given stringvoid arrangeString(string str, int x, int y){ int count_0 = 0; int count_1 = 0; int len = str.length(); // Counting number of 0's and 1's in the // given string. for (int i = 0; i < len; i++) { if (str[i] == '0') count_0++; else count_1++; } // Printing first all 0's x-times // and decrement count of 0's x-times // and do the similar task with '1' while (count_0 > 0 || count_1 > 0) { for (int j = 0; j < x && count_0 > 0; j++) { if (count_0 > 0) { cout << \"0\"; count_0--; } } for (int j = 0; j < y && count_1 > 0; j++) { if (count_1 > 0) { cout << \"1\"; count_1--; } } }} // Driver Codeint main(){ string str = \"01101101101101101000000\"; int x = 1; int y = 2; arrangeString(str, x, y); return 0;}",
"e": 1958,
"s": 960,
"text": null
},
{
"code": "// Java program to arrange given stringimport java.io.*; class GFG{ // Function which arrange the given string static void arrangeString(String str, int x, int y) { int count_0 = 0; int count_1 = 0; int len = str.length(); // Counting number of 0's and 1's in the // given string. for (int i = 0; i < len; i++) { if (str.charAt(i) == '0') count_0++; else count_1++; } // Printing first all 0's x-times // and decrement count of 0's x-times // and do the similar task with '1' while (count_0 > 0 || count_1 > 0) { for (int j = 0; j < x && count_0 > 0; j++) { if (count_0 > 0) { System.out.print (\"0\"); count_0--; } } for (int j = 0; j < y && count_1 > 0; j++) { if (count_1 > 0) { System.out.print(\"1\"); count_1--; } } } } // Driver Code public static void main (String[] args) { String str = \"01101101101101101000000\"; int x = 1; int y = 2; arrangeString(str, x, y); }} // This code is contributed by vt_m.",
"e": 3315,
"s": 1958,
"text": null
},
{
"code": "# Python3 program to arrange given string # Function which arrange the given stringdef arrangeString(str1,x,y): count_0=0 count_1 =0 n = len(str1) # Counting number of 0's and 1's in the # given string. for i in range(n): if str1[i] == '0': count_0 +=1 else: count_1 +=1 # Printing first all 0's x-times # and decrement count of 0's x-times # and do the similar task with '1' while count_0>0 or count_1>0: for i in range(0,x): if count_0>0: print(\"0\",end=\"\") count_0 -=1 for j in range(0,y): if count_1>0: print(\"1\",end=\"\") count_1 -=1 # Driver codeif __name__=='__main__': str1 = \"01101101101101101000000\" x = 1 y = 2 arrangeString(str1, x, y) # This code is contributed by# Shrikant13",
"e": 4178,
"s": 3315,
"text": null
},
{
"code": "// C# program to arrange given stringusing System; class GFG { // Function which arrange the // given string static void arrangeString(string str, int x, int y) { int count_0 = 0; int count_1 = 0; int len = str.Length; // Counting number of 0's and 1's // in the given string. for (int i = 0; i < len; i++) { if (str[i] == '0') count_0++; else count_1++; } // Printing first all 0's x-times // and decrement count of 0's x-times // and do the similar task with '1' while (count_0 > 0 || count_1 > 0) { for (int j = 0; j < x && count_0 > 0; j++) { if (count_0 > 0) { Console.Write(\"0\"); count_0--; } } for (int j = 0; j < y && count_1 > 0; j++) { if (count_1 > 0) { Console.Write(\"1\"); count_1--; } } } } // Driver Code public static void Main () { string str = \"01101101101101101000000\"; int x = 1; int y = 2; arrangeString(str, x, y); }} // This code is contributed by vt_m.",
"e": 5607,
"s": 4178,
"text": null
},
{
"code": "<?php// PHP program to arrange given string // Function which arrange// the given stringfunction arrangeString($str, $x, $y){ $count_0 = 0; $count_1 = 0; $len =strlen($str); // Counting number of 0's and // 1's in the given string. for ( $i = 0; $i < $len; $i++) { if ($str[$i] == '0') $count_0++; else $count_1++; } // Printing first all 0's x-times // and decrement count of 0's x-times // and do the similar task with '1' while ($count_0 > 0 || $count_1 > 0) { for ($j = 0; $j < $x && $count_0 > 0; $j++) { if ($count_0 > 0) { echo \"0\"; $count_0--; } } for ($j = 0; $j < $y && $count_1 > 0; $j++) { if ($count_1 > 0) { echo \"1\"; $count_1--; } } }} // Driver Code $str = \"01101101101101101000000\"; $x = 1; $y = 2; arrangeString($str, $x, $y); // This code is contributed by m_kit?>",
"e": 6679,
"s": 5607,
"text": null
},
{
"code": "<script> // Javascript program to arrange given string // Function which arrange the // given string function arrangeString(str, x, y) { let count_0 = 0; let count_1 = 0; let len = str.length; // Counting number of 0's and 1's // in the given string. for (let i = 0; i < len; i++) { if (str[i] == '0') count_0++; else count_1++; } // Printing first all 0's x-times // and decrement count of 0's x-times // and do the similar task with '1' while (count_0 > 0 || count_1 > 0) { for (let j = 0; j < x && count_0 > 0; j++) { if (count_0 > 0) { document.write(\"0\"); count_0--; } } for (let j = 0; j < y && count_1 > 0; j++) { if (count_1 > 0) { document.write(\"1\"); count_1--; } } } } let str = \"01101101101101101000000\"; let x = 1; let y = 2; arrangeString(str, x, y); </script>",
"e": 7906,
"s": 6679,
"text": null
},
{
"code": null,
"e": 7916,
"s": 7906,
"text": "Output: "
},
{
"code": null,
"e": 7940,
"s": 7916,
"text": "01101101101101101000000"
},
{
"code": null,
"e": 7984,
"s": 7940,
"text": "Time Complexity: O(N2)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 8405,
"s": 7984,
"text": "This article is contributed by Sahil Rajput. 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": 8410,
"s": 8405,
"text": "vt_m"
},
{
"code": null,
"e": 8416,
"s": 8410,
"text": "jit_t"
},
{
"code": null,
"e": 8428,
"s": 8416,
"text": "shrikanth13"
},
{
"code": null,
"e": 8439,
"s": 8428,
"text": "decode2207"
},
{
"code": null,
"e": 8452,
"s": 8439,
"text": "codewithmini"
},
{
"code": null,
"e": 8468,
"s": 8452,
"text": "array-rearrange"
},
{
"code": null,
"e": 8482,
"s": 8468,
"text": "binary-string"
},
{
"code": null,
"e": 8490,
"s": 8482,
"text": "Strings"
},
{
"code": null,
"e": 8498,
"s": 8490,
"text": "Strings"
},
{
"code": null,
"e": 8596,
"s": 8498,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8641,
"s": 8596,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 8716,
"s": 8641,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
},
{
"code": null,
"e": 8773,
"s": 8716,
"text": "Python program to check if a string is palindrome or not"
},
{
"code": null,
"e": 8809,
"s": 8773,
"text": "KMP Algorithm for Pattern Searching"
},
{
"code": null,
"e": 8847,
"s": 8809,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 8908,
"s": 8847,
"text": "Length of the longest substring without repeating characters"
},
{
"code": null,
"e": 8944,
"s": 8908,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 8989,
"s": 8944,
"text": "Top 50 String Coding Problems for Interviews"
},
{
"code": null,
"e": 9041,
"s": 8989,
"text": "Check whether two strings are anagram of each other"
}
] |
Check if a given Binary Tree is Heap | 25 Mar, 2022
Given a binary tree, we need to check it has heap property or not, Binary tree need to fulfill the following two conditions for being a heap –
It should be a complete tree (i.e. all levels except last should be full).Every node’s value should be greater than or equal to its child node (considering max-heap).
It should be a complete tree (i.e. all levels except last should be full).
Every node’s value should be greater than or equal to its child node (considering max-heap).
For example this tree contains heap property –
While this doesn’t –
We check each of the above condition separately, for checking completeness isComplete and for checking heap isHeapUtil function are written. Detail about isComplete function can be found here.isHeapUtil function is written considering the following things –
Every Node can have 2 children, 0 child (last level nodes) or 1 child (there can be at most one such node).If Node has No child then it’s a leaf node and returns true (Base case)If Node has one child (it must be left child because it is a complete tree) then we need to compare this node with its single child only.If the Node has both child then check heap property at Node at recur for both subtrees. Complete code.
Every Node can have 2 children, 0 child (last level nodes) or 1 child (there can be at most one such node).
If Node has No child then it’s a leaf node and returns true (Base case)
If Node has one child (it must be left child because it is a complete tree) then we need to compare this node with its single child only.
If the Node has both child then check heap property at Node at recur for both subtrees. Complete code.
Below is the implementation of the above approach:
C++
C
Java
Python3
C#
Javascript
/* C++ program to checks if abinary tree is max heap or not */#include <bits/stdc++.h> using namespace std; /* Tree node structure */struct Node{ int key; struct Node *left; struct Node *right;}; /* Helper function thatallocates a new node */struct Node *newNode(int k){ struct Node *node = new Node; node->key = k; node->right = node->left = NULL; return node;} /* This function counts thenumber of nodes in a binary tree */unsigned int countNodes(struct Node* root){ if (root == NULL) return (0); return (1 + countNodes(root->left) + countNodes(root->right));} /* This function checks if thebinary tree is complete or not */bool isCompleteUtil (struct Node* root, unsigned int index, unsigned int number_nodes){ // An empty tree is complete if (root == NULL) return (true); // If index assigned to // current node is more than // number of nodes in tree, // then tree is not complete if (index >= number_nodes) return (false); // Recur for left and right subtrees return (isCompleteUtil(root->left, 2*index + 1, number_nodes) && isCompleteUtil(root->right, 2*index + 2, number_nodes));} // This Function checks the// heap property in the tree.bool isHeapUtil(struct Node* root){ // Base case : single // node satisfies property if (root->left == NULL && root->right == NULL) return (true); // node will be in // second last level if (root->right == NULL) { // check heap property at Node // No recursive call , // because no need to check last level return (root->key >= root->left->key); } else { // Check heap property at Node and // Recursive check heap // property at left and right subtree if (root->key >= root->left->key && root->key >= root->right->key) return ((isHeapUtil(root->left)) && (isHeapUtil(root->right))); else return (false); }} // Function to check binary// tree is a Heap or Not.bool isHeap(struct Node* root){ // These two are used // in isCompleteUtil() unsigned int node_count = countNodes(root); unsigned int index = 0; if (isCompleteUtil(root, index, node_count) && isHeapUtil(root)) return true; return false;} // Driver codeint main(){ struct Node* root = NULL; root = newNode(10); root->left = newNode(9); root->right = newNode(8); root->left->left = newNode(7); root->left->right = newNode(6); root->right->left = newNode(5); root->right->right = newNode(4); root->left->left->left = newNode(3); root->left->left->right = newNode(2); root->left->right->left = newNode(1); // Function call if (isHeap(root)) cout << "Given binary tree is a Heap\n"; else cout << "Given binary tree is not a Heap\n"; return 0;} // This code is contributed by shubhamsingh10
/* C program to checks if a binary tree is max heap or not */#include <stdbool.h>#include <stdio.h>#include <stdlib.h> /* Tree node structure */struct Node { int key; struct Node* left; struct Node* right;}; /* Helper functionthat allocates a new node */struct Node* newNode(int k){ struct Node* node = (struct Node*)malloc(sizeof(struct Node)); node->key = k; node->right = node->left = NULL; return node;} /* This function counts the number of nodes in a binary tree */unsigned int countNodes(struct Node* root){ if (root == NULL) return (0); return (1 + countNodes(root->left) + countNodes(root->right));} /* This function checks if the binary tree is complete or * not */bool isCompleteUtil(struct Node* root, unsigned int index, unsigned int number_nodes){ // An empty tree is complete if (root == NULL) return (true); // If index assigned to current // node is more than // number of nodes in tree, // then tree is not complete if (index >= number_nodes) return (false); // Recur for left and right subtrees return (isCompleteUtil(root->left, 2 * index + 1, number_nodes) && isCompleteUtil(root->right, 2 * index + 2, number_nodes));} // This Function checks the// heap property in the tree.bool isHeapUtil(struct Node* root){ // Base case : single // node satisfies property if (root->left == NULL && root->right == NULL) return (true); // node will be in second last level if (root->right == NULL) { // check heap property at Node // No recursive call , // because no need to check last level return (root->key >= root->left->key); } else { // Check heap property at Node and // Recursive check heap property // at left and right subtree if (root->key >= root->left->key && root->key >= root->right->key) return ((isHeapUtil(root->left)) && (isHeapUtil(root->right))); else return (false); }} // Function to check binary// tree is a Heap or Not.bool isHeap(struct Node* root){ // These two are used in // isCompleteUtil() unsigned int node_count = countNodes(root); unsigned int index = 0; if (isCompleteUtil(root, index, node_count) && isHeapUtil(root)) return true; return false;} // Driver Codeint main(){ struct Node* root = NULL; root = newNode(10); root->left = newNode(9); root->right = newNode(8); root->left->left = newNode(7); root->left->right = newNode(6); root->right->left = newNode(5); root->right->right = newNode(4); root->left->left->left = newNode(3); root->left->left->right = newNode(2); root->left->right->left = newNode(1); if (isHeap(root)) printf("Given binary tree is a Heap\n"); else printf("Given binary tree is not a Heap\n"); return 0;}
/* Java program to checks * if a binary tree is max heap or not */ // A Binary Tree nodeclass Node { int key; Node left, right; Node(int k) { key = k; left = right = null; }} class Is_BinaryTree_MaxHeap{ /* This function counts the number of nodes in a binary * tree */ int countNodes(Node root) { if (root == null) return 0; return (1 + countNodes(root.left) + countNodes(root.right)); } /* This function checks if the binary tree is complete * or not */ boolean isCompleteUtil(Node root, int index, int number_nodes) { // An empty tree is complete if (root == null) return true; // If index assigned to current // node is more than number of // nodes in tree, then tree is // not complete if (index >= number_nodes) return false; // Recur for left and right subtrees return isCompleteUtil(root.left, 2 * index + 1, number_nodes) && isCompleteUtil(root.right, 2 * index + 2, number_nodes); } // This Function checks // the heap property in the tree. boolean isHeapUtil(Node root) { // Base case : single // node satisfies property if (root.left == null && root.right == null) return true; // node will be in second last level if (root.right == null) { // check heap property at Node // No recursive call , // because no need to check last level return root.key >= root.left.key; } else { // Check heap property at Node and // Recursive check heap property at left and // right subtree if (root.key >= root.left.key && root.key >= root.right.key) return isHeapUtil(root.left) && isHeapUtil(root.right); else return false; } } // Function to check binary // tree is a Heap or Not. boolean isHeap(Node root) { if (root == null) return true; // These two are used // in isCompleteUtil() int node_count = countNodes(root); if (isCompleteUtil(root, 0, node_count) == true && isHeapUtil(root) == true) return true; return false; } // driver function to // test the above functions public static void main(String args[]) { Is_BinaryTree_MaxHeap bt = new Is_BinaryTree_MaxHeap(); Node root = new Node(10); root.left = new Node(9); root.right = new Node(8); root.left.left = new Node(7); root.left.right = new Node(6); root.right.left = new Node(5); root.right.right = new Node(4); root.left.left.left = new Node(3); root.left.left.right = new Node(2); root.left.right.left = new Node(1); if (bt.isHeap(root) == true) System.out.println( "Given binary tree is a Heap"); else System.out.println( "Given binary tree is not a Heap"); }} // This code has been contributed by Amit Khandelwal
# To check if a binary tree# is a MAX Heap or not class GFG: def __init__(self, value): self.key = value self.left = None self.right = None def count_nodes(self, root): if root is None: return 0 else: return (1 + self.count_nodes(root.left) + self.count_nodes(root.right)) def heap_property_util(self, root): if (root.left is None and root.right is None): return True if root.right is None: return root.key >= root.left.key else: if (root.key >= root.left.key and root.key >= root.right.key): return (self.heap_property_util(root.left) and self.heap_property_util(root.right)) else: return False def complete_tree_util(self, root, index, node_count): if root is None: return True if index >= node_count: return False return (self.complete_tree_util(root.left, 2 * index + 1, node_count) and self.complete_tree_util(root.right, 2 * index + 2, node_count)) def check_if_heap(self): node_count = self.count_nodes(self) if (self.complete_tree_util(self, 0, node_count) and self.heap_property_util(self)): return True else: return False # Driver Coderoot = GFG(5)root.left = GFG(2)root.right = GFG(3)root.left.left = GFG(1) if root.check_if_heap(): print("Given binary tree is a heap")else: print("Given binary tree is not a Heap") # This code has been# contributed by Yash Agrawal
/* C# program to checks if abinary tree is max heap or not */using System; // A Binary Tree nodepublic class Node { public int key; public Node left, right; public Node(int k) { key = k; left = right = null; }} class Is_BinaryTree_MaxHeap{ /* This function counts the number of nodes in a binary tree */ int countNodes(Node root) { if (root == null) return 0; return (1 + countNodes(root.left) + countNodes(root.right)); } /* This function checks if the binary tree is complete or not */ Boolean isCompleteUtil(Node root, int index, int number_nodes) { // An empty tree is complete if (root == null) return true; // If index assigned to // current node is more than // number of nodes in tree, then // tree is notcomplete if (index >= number_nodes) return false; // Recur for left and right subtrees return isCompleteUtil(root.left, 2 * index + 1, number_nodes) && isCompleteUtil(root.right, 2 * index + 2, number_nodes); } // This Function checks the // heap property in the tree. Boolean isHeapUtil(Node root) { // Base case : single // node satisfies property if (root.left == null && root.right == null) return true; // node will be in second last level if (root.right == null) { // check heap property at Node // No recursive call , // because no need to check last level return root.key >= root.left.key; } else { // Check heap property at Node and // Recursive check heap // property at left and // right subtree if (root.key >= root.left.key && root.key >= root.right.key) return isHeapUtil(root.left) && isHeapUtil(root.right); else return false; } } // Function to check binary // tree is a Heap or Not. Boolean isHeap(Node root) { if (root == null) return true; // These two are used in isCompleteUtil() int node_count = countNodes(root); if (isCompleteUtil(root, 0, node_count) == true && isHeapUtil(root) == true) return true; return false; } // Driver code public static void Main(String[] args) { Is_BinaryTree_MaxHeap bt = new Is_BinaryTree_MaxHeap(); Node root = new Node(10); root.left = new Node(9); root.right = new Node(8); root.left.left = new Node(7); root.left.right = new Node(6); root.right.left = new Node(5); root.right.right = new Node(4); root.left.left.left = new Node(3); root.left.left.right = new Node(2); root.left.right.left = new Node(1); if (bt.isHeap(root) == true) Console.WriteLine( "Given binary tree is a Heap"); else Console.WriteLine( "Given binary tree is not a Heap"); }} // This code has been contributed by Arnab Kundu
<script>/* Javascript program to checks if abinary tree is max heap or not */ // A Binary Tree nodeclass Node { constructor(k) { this.key = k; this.left = null; this.right = null; }} /* This function counts the numberof nodes in a binary tree */function countNodes(root){ if (root == null) return 0; return (1 + countNodes(root.left) + countNodes(root.right));} /* This function checks if thebinary tree is complete or not */function isCompleteUtil(root, index, number_nodes){ // An empty tree is complete if (root == null) return true; // If index assigned to // current node is more than // number of nodes in tree, then // tree is notcomplete if (index >= number_nodes) return false; // Recur for left and right subtrees return isCompleteUtil(root.left, 2 * index + 1, number_nodes) && isCompleteUtil(root.right, 2 * index + 2, number_nodes);} // This Function checks the// heap property in the tree.function isHeapUtil(root){ // Base case : single // node satisfies property if (root.left == null && root.right == null) return true; // node will be in second last level if (root.right == null) { // check heap property at Node // No recursive call , // because no need to check last level return root.key >= root.left.key; } else { // Check heap property at Node and // Recursive check heap // property at left and // right subtree if (root.key >= root.left.key && root.key >= root.right.key) return isHeapUtil(root.left) && isHeapUtil(root.right); else return false; }} // Function to check binary// tree is a Heap or Not.function isHeap(root){ if (root == null) return true; // These two are used in isCompleteUtil() var node_count = countNodes(root); if (isCompleteUtil(root, 0, node_count) == true && isHeapUtil(root) == true) return true; return false;} // Driver codevar root = new Node(10);root.left = new Node(9);root.right = new Node(8);root.left.left = new Node(7);root.left.right = new Node(6);root.right.left = new Node(5);root.right.right = new Node(4);root.left.left.left = new Node(3);root.left.left.right = new Node(2);root.left.right.left = new Node(1);if (isHeap(root) == true) document.write( "Given binary tree is a Heap");else document.write( "Given binary tree is not a Heap"); // This code is contributed by rrrtnx.</script>
Given binary tree is a Heap
Method 2: (Iterative approach using level order traversal)
C++
Java
C#
Javascript
// C++ program to checks if a// binary tree is max heap or not#include <bits/stdc++.h> using namespace std; // Tree node structurestruct Node { int data; struct Node* left; struct Node* right;}; // To add a new nodestruct Node* newNode(int k){ struct Node* node = new Node; node->data = k; node->right = node->left = NULL; return node;} bool isHeap(Node* root){ // Your code here queue<Node*> q; q.push(root); bool nullish = false; while (!q.empty()) { Node* temp = q.front(); q.pop(); if (temp->left) { if (nullish || temp->left->data > temp->data) { return false; } q.push(temp->left); } else { nullish = true; } if (temp->right) { if (nullish || temp->right->data > temp->data) { return false; } q.push(temp->right); } else { nullish = true; } } return true;} // Driver codeint main(){ struct Node* root = NULL; root = newNode(10); root->left = newNode(9); root->right = newNode(8); root->left->left = newNode(7); root->left->right = newNode(6); root->right->left = newNode(5); root->right->right = newNode(4); root->left->left->left = newNode(3); root->left->left->right = newNode(2); root->left->right->left = newNode(1); // Function call if (isHeap(root)) cout << "Given binary tree is a Heap\n"; else cout << "Given binary tree is not a Heap\n"; return 0;}
// Java program to checks if a// binary tree is max heap or notimport java.util.*;class GFG{ // Tree node structure static class Node { int data; Node left; Node right; }; // To add a new node static Node newNode(int k) { Node node = new Node(); node.data = k; node.right = node.left = null; return node; } static boolean isHeap(Node root) { Queue<Node> q = new LinkedList<>(); q.add(root); boolean nullish = false; while (!q.isEmpty()) { Node temp = q.peek(); q.remove(); if (temp.left != null) { if (nullish || temp.left.data > temp.data) { return false; } q.add(temp.left); } else { nullish = true; } if (temp.right != null) { if (nullish || temp.right.data > temp.data) { return false; } q.add(temp.right); } else { nullish = true; } } return true; } // Driver code public static void main(String[] args) { Node root = null; root = newNode(10); root.left = newNode(9); root.right = newNode(8); root.left.left = newNode(7); root.left.right = newNode(6); root.right.left = newNode(5); root.right.right = newNode(4); root.left.left.left = newNode(3); root.left.left.right = newNode(2); root.left.right.left = newNode(1); // Function call if (isHeap(root)) System.out.print("Given binary tree is a Heap\n"); else System.out.print("Given binary tree is not a Heap\n"); }} // This code is contributed by Rajput-Ji
// C# program to checks if a// binary tree is max heap or notusing System;using System.Collections.Generic;public class GFG{ // Tree node structure public class Node { public int data; public Node left; public Node right; }; // To add a new node static Node newNode(int k) { Node node = new Node(); node.data = k; node.right = node.left = null; return node; } static bool isHeap(Node root) { Queue<Node> q = new Queue<Node>(); q.Enqueue(root); bool nullish = false; while (q.Count!=0) { Node temp = q.Peek(); q.Dequeue(); if (temp.left != null) { if (nullish || temp.left.data > temp.data) { return false; } q.Enqueue(temp.left); } else { nullish = true; } if (temp.right != null) { if (nullish || temp.right.data > temp.data) { return false; } q.Enqueue(temp.right); } else { nullish = true; } } return true; } // Driver code public static void Main(String[] args) { Node root = null; root = newNode(10); root.left = newNode(9); root.right = newNode(8); root.left.left = newNode(7); root.left.right = newNode(6); root.right.left = newNode(5); root.right.right = newNode(4); root.left.left.left = newNode(3); root.left.left.right = newNode(2); root.left.right.left = newNode(1); // Function call if (isHeap(root)) Console.Write("Given binary tree is a Heap\n"); else Console.Write("Given binary tree is not a Heap\n"); }} // This code is contributed by aashish1995
<script> // JavaScript program to checks if a // binary tree is max heap or not class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } // To add a new node function newNode(k) { let node = new Node(k); return node; } function isHeap(root) { let q = []; q.push(root); let nullish = false; while (q.length > 0) { let temp = q[0]; q.shift(); if (temp.left != null) { if (nullish || temp.left.data > temp.data) { return false; } q.push(temp.left); } else { nullish = true; } if (temp.right != null) { if (nullish || temp.right.data > temp.data) { return false; } q.push(temp.right); } else { nullish = true; } } return true; } let root = null; root = newNode(10); root.left = newNode(9); root.right = newNode(8); root.left.left = newNode(7); root.left.right = newNode(6); root.right.left = newNode(5); root.right.right = newNode(4); root.left.left.left = newNode(3); root.left.left.right = newNode(2); root.left.right.left = newNode(1); // Function call if (isHeap(root)) document.write("Given binary tree is a Heap" + "</br>"); else document.write("Given binary tree is not a Heap" + "</br>"); </script>
Given binary tree is a Heap
This article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
scorncer17
Akanksha_Rai
andrew1234
SHUBHAMSINGH10
devilwebdev
Rajput-Ji
aashish1995
rrrtnx
suresh07
amartyaghoshgfg
simmytarika5
arynkr
Hike
Binary Search Tree
Heap
Tree
Hike
Binary Search Tree
Tree
Heap
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Binary Search Tree | Set 1 (Search and Insertion)
AVL Tree | Set 1 (Insertion)
Binary Search Tree | Set 2 (Delete)
A program to check if a binary tree is BST or not
Find postorder traversal of BST from preorder traversal
HeapSort
K'th Smallest/Largest Element in Unsorted Array | Set 1
Introduction to Data Structures
Huffman Coding | Greedy Algo-3
Sliding Window Maximum (Maximum of all subarrays of size k) | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n25 Mar, 2022"
},
{
"code": null,
"e": 198,
"s": 54,
"text": "Given a binary tree, we need to check it has heap property or not, Binary tree need to fulfill the following two conditions for being a heap – "
},
{
"code": null,
"e": 365,
"s": 198,
"text": "It should be a complete tree (i.e. all levels except last should be full).Every node’s value should be greater than or equal to its child node (considering max-heap)."
},
{
"code": null,
"e": 440,
"s": 365,
"text": "It should be a complete tree (i.e. all levels except last should be full)."
},
{
"code": null,
"e": 533,
"s": 440,
"text": "Every node’s value should be greater than or equal to its child node (considering max-heap)."
},
{
"code": null,
"e": 581,
"s": 533,
"text": "For example this tree contains heap property – "
},
{
"code": null,
"e": 602,
"s": 581,
"text": "While this doesn’t –"
},
{
"code": null,
"e": 862,
"s": 602,
"text": "We check each of the above condition separately, for checking completeness isComplete and for checking heap isHeapUtil function are written. Detail about isComplete function can be found here.isHeapUtil function is written considering the following things – "
},
{
"code": null,
"e": 1280,
"s": 862,
"text": "Every Node can have 2 children, 0 child (last level nodes) or 1 child (there can be at most one such node).If Node has No child then it’s a leaf node and returns true (Base case)If Node has one child (it must be left child because it is a complete tree) then we need to compare this node with its single child only.If the Node has both child then check heap property at Node at recur for both subtrees. Complete code."
},
{
"code": null,
"e": 1388,
"s": 1280,
"text": "Every Node can have 2 children, 0 child (last level nodes) or 1 child (there can be at most one such node)."
},
{
"code": null,
"e": 1460,
"s": 1388,
"text": "If Node has No child then it’s a leaf node and returns true (Base case)"
},
{
"code": null,
"e": 1598,
"s": 1460,
"text": "If Node has one child (it must be left child because it is a complete tree) then we need to compare this node with its single child only."
},
{
"code": null,
"e": 1701,
"s": 1598,
"text": "If the Node has both child then check heap property at Node at recur for both subtrees. Complete code."
},
{
"code": null,
"e": 1752,
"s": 1701,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1756,
"s": 1752,
"text": "C++"
},
{
"code": null,
"e": 1758,
"s": 1756,
"text": "C"
},
{
"code": null,
"e": 1763,
"s": 1758,
"text": "Java"
},
{
"code": null,
"e": 1771,
"s": 1763,
"text": "Python3"
},
{
"code": null,
"e": 1774,
"s": 1771,
"text": "C#"
},
{
"code": null,
"e": 1785,
"s": 1774,
"text": "Javascript"
},
{
"code": "/* C++ program to checks if abinary tree is max heap or not */#include <bits/stdc++.h> using namespace std; /* Tree node structure */struct Node{ int key; struct Node *left; struct Node *right;}; /* Helper function thatallocates a new node */struct Node *newNode(int k){ struct Node *node = new Node; node->key = k; node->right = node->left = NULL; return node;} /* This function counts thenumber of nodes in a binary tree */unsigned int countNodes(struct Node* root){ if (root == NULL) return (0); return (1 + countNodes(root->left) + countNodes(root->right));} /* This function checks if thebinary tree is complete or not */bool isCompleteUtil (struct Node* root, unsigned int index, unsigned int number_nodes){ // An empty tree is complete if (root == NULL) return (true); // If index assigned to // current node is more than // number of nodes in tree, // then tree is not complete if (index >= number_nodes) return (false); // Recur for left and right subtrees return (isCompleteUtil(root->left, 2*index + 1, number_nodes) && isCompleteUtil(root->right, 2*index + 2, number_nodes));} // This Function checks the// heap property in the tree.bool isHeapUtil(struct Node* root){ // Base case : single // node satisfies property if (root->left == NULL && root->right == NULL) return (true); // node will be in // second last level if (root->right == NULL) { // check heap property at Node // No recursive call , // because no need to check last level return (root->key >= root->left->key); } else { // Check heap property at Node and // Recursive check heap // property at left and right subtree if (root->key >= root->left->key && root->key >= root->right->key) return ((isHeapUtil(root->left)) && (isHeapUtil(root->right))); else return (false); }} // Function to check binary// tree is a Heap or Not.bool isHeap(struct Node* root){ // These two are used // in isCompleteUtil() unsigned int node_count = countNodes(root); unsigned int index = 0; if (isCompleteUtil(root, index, node_count) && isHeapUtil(root)) return true; return false;} // Driver codeint main(){ struct Node* root = NULL; root = newNode(10); root->left = newNode(9); root->right = newNode(8); root->left->left = newNode(7); root->left->right = newNode(6); root->right->left = newNode(5); root->right->right = newNode(4); root->left->left->left = newNode(3); root->left->left->right = newNode(2); root->left->right->left = newNode(1); // Function call if (isHeap(root)) cout << \"Given binary tree is a Heap\\n\"; else cout << \"Given binary tree is not a Heap\\n\"; return 0;} // This code is contributed by shubhamsingh10",
"e": 4858,
"s": 1785,
"text": null
},
{
"code": "/* C program to checks if a binary tree is max heap or not */#include <stdbool.h>#include <stdio.h>#include <stdlib.h> /* Tree node structure */struct Node { int key; struct Node* left; struct Node* right;}; /* Helper functionthat allocates a new node */struct Node* newNode(int k){ struct Node* node = (struct Node*)malloc(sizeof(struct Node)); node->key = k; node->right = node->left = NULL; return node;} /* This function counts the number of nodes in a binary tree */unsigned int countNodes(struct Node* root){ if (root == NULL) return (0); return (1 + countNodes(root->left) + countNodes(root->right));} /* This function checks if the binary tree is complete or * not */bool isCompleteUtil(struct Node* root, unsigned int index, unsigned int number_nodes){ // An empty tree is complete if (root == NULL) return (true); // If index assigned to current // node is more than // number of nodes in tree, // then tree is not complete if (index >= number_nodes) return (false); // Recur for left and right subtrees return (isCompleteUtil(root->left, 2 * index + 1, number_nodes) && isCompleteUtil(root->right, 2 * index + 2, number_nodes));} // This Function checks the// heap property in the tree.bool isHeapUtil(struct Node* root){ // Base case : single // node satisfies property if (root->left == NULL && root->right == NULL) return (true); // node will be in second last level if (root->right == NULL) { // check heap property at Node // No recursive call , // because no need to check last level return (root->key >= root->left->key); } else { // Check heap property at Node and // Recursive check heap property // at left and right subtree if (root->key >= root->left->key && root->key >= root->right->key) return ((isHeapUtil(root->left)) && (isHeapUtil(root->right))); else return (false); }} // Function to check binary// tree is a Heap or Not.bool isHeap(struct Node* root){ // These two are used in // isCompleteUtil() unsigned int node_count = countNodes(root); unsigned int index = 0; if (isCompleteUtil(root, index, node_count) && isHeapUtil(root)) return true; return false;} // Driver Codeint main(){ struct Node* root = NULL; root = newNode(10); root->left = newNode(9); root->right = newNode(8); root->left->left = newNode(7); root->left->right = newNode(6); root->right->left = newNode(5); root->right->right = newNode(4); root->left->left->left = newNode(3); root->left->left->right = newNode(2); root->left->right->left = newNode(1); if (isHeap(root)) printf(\"Given binary tree is a Heap\\n\"); else printf(\"Given binary tree is not a Heap\\n\"); return 0;}",
"e": 7942,
"s": 4858,
"text": null
},
{
"code": "/* Java program to checks * if a binary tree is max heap or not */ // A Binary Tree nodeclass Node { int key; Node left, right; Node(int k) { key = k; left = right = null; }} class Is_BinaryTree_MaxHeap{ /* This function counts the number of nodes in a binary * tree */ int countNodes(Node root) { if (root == null) return 0; return (1 + countNodes(root.left) + countNodes(root.right)); } /* This function checks if the binary tree is complete * or not */ boolean isCompleteUtil(Node root, int index, int number_nodes) { // An empty tree is complete if (root == null) return true; // If index assigned to current // node is more than number of // nodes in tree, then tree is // not complete if (index >= number_nodes) return false; // Recur for left and right subtrees return isCompleteUtil(root.left, 2 * index + 1, number_nodes) && isCompleteUtil(root.right, 2 * index + 2, number_nodes); } // This Function checks // the heap property in the tree. boolean isHeapUtil(Node root) { // Base case : single // node satisfies property if (root.left == null && root.right == null) return true; // node will be in second last level if (root.right == null) { // check heap property at Node // No recursive call , // because no need to check last level return root.key >= root.left.key; } else { // Check heap property at Node and // Recursive check heap property at left and // right subtree if (root.key >= root.left.key && root.key >= root.right.key) return isHeapUtil(root.left) && isHeapUtil(root.right); else return false; } } // Function to check binary // tree is a Heap or Not. boolean isHeap(Node root) { if (root == null) return true; // These two are used // in isCompleteUtil() int node_count = countNodes(root); if (isCompleteUtil(root, 0, node_count) == true && isHeapUtil(root) == true) return true; return false; } // driver function to // test the above functions public static void main(String args[]) { Is_BinaryTree_MaxHeap bt = new Is_BinaryTree_MaxHeap(); Node root = new Node(10); root.left = new Node(9); root.right = new Node(8); root.left.left = new Node(7); root.left.right = new Node(6); root.right.left = new Node(5); root.right.right = new Node(4); root.left.left.left = new Node(3); root.left.left.right = new Node(2); root.left.right.left = new Node(1); if (bt.isHeap(root) == true) System.out.println( \"Given binary tree is a Heap\"); else System.out.println( \"Given binary tree is not a Heap\"); }} // This code has been contributed by Amit Khandelwal",
"e": 11299,
"s": 7942,
"text": null
},
{
"code": "# To check if a binary tree# is a MAX Heap or not class GFG: def __init__(self, value): self.key = value self.left = None self.right = None def count_nodes(self, root): if root is None: return 0 else: return (1 + self.count_nodes(root.left) + self.count_nodes(root.right)) def heap_property_util(self, root): if (root.left is None and root.right is None): return True if root.right is None: return root.key >= root.left.key else: if (root.key >= root.left.key and root.key >= root.right.key): return (self.heap_property_util(root.left) and self.heap_property_util(root.right)) else: return False def complete_tree_util(self, root, index, node_count): if root is None: return True if index >= node_count: return False return (self.complete_tree_util(root.left, 2 * index + 1, node_count) and self.complete_tree_util(root.right, 2 * index + 2, node_count)) def check_if_heap(self): node_count = self.count_nodes(self) if (self.complete_tree_util(self, 0, node_count) and self.heap_property_util(self)): return True else: return False # Driver Coderoot = GFG(5)root.left = GFG(2)root.right = GFG(3)root.left.left = GFG(1) if root.check_if_heap(): print(\"Given binary tree is a heap\")else: print(\"Given binary tree is not a Heap\") # This code has been# contributed by Yash Agrawal",
"e": 13053,
"s": 11299,
"text": null
},
{
"code": "/* C# program to checks if abinary tree is max heap or not */using System; // A Binary Tree nodepublic class Node { public int key; public Node left, right; public Node(int k) { key = k; left = right = null; }} class Is_BinaryTree_MaxHeap{ /* This function counts the number of nodes in a binary tree */ int countNodes(Node root) { if (root == null) return 0; return (1 + countNodes(root.left) + countNodes(root.right)); } /* This function checks if the binary tree is complete or not */ Boolean isCompleteUtil(Node root, int index, int number_nodes) { // An empty tree is complete if (root == null) return true; // If index assigned to // current node is more than // number of nodes in tree, then // tree is notcomplete if (index >= number_nodes) return false; // Recur for left and right subtrees return isCompleteUtil(root.left, 2 * index + 1, number_nodes) && isCompleteUtil(root.right, 2 * index + 2, number_nodes); } // This Function checks the // heap property in the tree. Boolean isHeapUtil(Node root) { // Base case : single // node satisfies property if (root.left == null && root.right == null) return true; // node will be in second last level if (root.right == null) { // check heap property at Node // No recursive call , // because no need to check last level return root.key >= root.left.key; } else { // Check heap property at Node and // Recursive check heap // property at left and // right subtree if (root.key >= root.left.key && root.key >= root.right.key) return isHeapUtil(root.left) && isHeapUtil(root.right); else return false; } } // Function to check binary // tree is a Heap or Not. Boolean isHeap(Node root) { if (root == null) return true; // These two are used in isCompleteUtil() int node_count = countNodes(root); if (isCompleteUtil(root, 0, node_count) == true && isHeapUtil(root) == true) return true; return false; } // Driver code public static void Main(String[] args) { Is_BinaryTree_MaxHeap bt = new Is_BinaryTree_MaxHeap(); Node root = new Node(10); root.left = new Node(9); root.right = new Node(8); root.left.left = new Node(7); root.left.right = new Node(6); root.right.left = new Node(5); root.right.right = new Node(4); root.left.left.left = new Node(3); root.left.left.right = new Node(2); root.left.right.left = new Node(1); if (bt.isHeap(root) == true) Console.WriteLine( \"Given binary tree is a Heap\"); else Console.WriteLine( \"Given binary tree is not a Heap\"); }} // This code has been contributed by Arnab Kundu",
"e": 16426,
"s": 13053,
"text": null
},
{
"code": "<script>/* Javascript program to checks if abinary tree is max heap or not */ // A Binary Tree nodeclass Node { constructor(k) { this.key = k; this.left = null; this.right = null; }} /* This function counts the numberof nodes in a binary tree */function countNodes(root){ if (root == null) return 0; return (1 + countNodes(root.left) + countNodes(root.right));} /* This function checks if thebinary tree is complete or not */function isCompleteUtil(root, index, number_nodes){ // An empty tree is complete if (root == null) return true; // If index assigned to // current node is more than // number of nodes in tree, then // tree is notcomplete if (index >= number_nodes) return false; // Recur for left and right subtrees return isCompleteUtil(root.left, 2 * index + 1, number_nodes) && isCompleteUtil(root.right, 2 * index + 2, number_nodes);} // This Function checks the// heap property in the tree.function isHeapUtil(root){ // Base case : single // node satisfies property if (root.left == null && root.right == null) return true; // node will be in second last level if (root.right == null) { // check heap property at Node // No recursive call , // because no need to check last level return root.key >= root.left.key; } else { // Check heap property at Node and // Recursive check heap // property at left and // right subtree if (root.key >= root.left.key && root.key >= root.right.key) return isHeapUtil(root.left) && isHeapUtil(root.right); else return false; }} // Function to check binary// tree is a Heap or Not.function isHeap(root){ if (root == null) return true; // These two are used in isCompleteUtil() var node_count = countNodes(root); if (isCompleteUtil(root, 0, node_count) == true && isHeapUtil(root) == true) return true; return false;} // Driver codevar root = new Node(10);root.left = new Node(9);root.right = new Node(8);root.left.left = new Node(7);root.left.right = new Node(6);root.right.left = new Node(5);root.right.right = new Node(4);root.left.left.left = new Node(3);root.left.left.right = new Node(2);root.left.right.left = new Node(1);if (isHeap(root) == true) document.write( \"Given binary tree is a Heap\");else document.write( \"Given binary tree is not a Heap\"); // This code is contributed by rrrtnx.</script>",
"e": 19149,
"s": 16426,
"text": null
},
{
"code": null,
"e": 19178,
"s": 19149,
"text": "Given binary tree is a Heap\n"
},
{
"code": null,
"e": 19237,
"s": 19178,
"text": "Method 2: (Iterative approach using level order traversal)"
},
{
"code": null,
"e": 19241,
"s": 19237,
"text": "C++"
},
{
"code": null,
"e": 19246,
"s": 19241,
"text": "Java"
},
{
"code": null,
"e": 19249,
"s": 19246,
"text": "C#"
},
{
"code": null,
"e": 19260,
"s": 19249,
"text": "Javascript"
},
{
"code": "// C++ program to checks if a// binary tree is max heap or not#include <bits/stdc++.h> using namespace std; // Tree node structurestruct Node { int data; struct Node* left; struct Node* right;}; // To add a new nodestruct Node* newNode(int k){ struct Node* node = new Node; node->data = k; node->right = node->left = NULL; return node;} bool isHeap(Node* root){ // Your code here queue<Node*> q; q.push(root); bool nullish = false; while (!q.empty()) { Node* temp = q.front(); q.pop(); if (temp->left) { if (nullish || temp->left->data > temp->data) { return false; } q.push(temp->left); } else { nullish = true; } if (temp->right) { if (nullish || temp->right->data > temp->data) { return false; } q.push(temp->right); } else { nullish = true; } } return true;} // Driver codeint main(){ struct Node* root = NULL; root = newNode(10); root->left = newNode(9); root->right = newNode(8); root->left->left = newNode(7); root->left->right = newNode(6); root->right->left = newNode(5); root->right->right = newNode(4); root->left->left->left = newNode(3); root->left->left->right = newNode(2); root->left->right->left = newNode(1); // Function call if (isHeap(root)) cout << \"Given binary tree is a Heap\\n\"; else cout << \"Given binary tree is not a Heap\\n\"; return 0;}",
"e": 20921,
"s": 19260,
"text": null
},
{
"code": "// Java program to checks if a// binary tree is max heap or notimport java.util.*;class GFG{ // Tree node structure static class Node { int data; Node left; Node right; }; // To add a new node static Node newNode(int k) { Node node = new Node(); node.data = k; node.right = node.left = null; return node; } static boolean isHeap(Node root) { Queue<Node> q = new LinkedList<>(); q.add(root); boolean nullish = false; while (!q.isEmpty()) { Node temp = q.peek(); q.remove(); if (temp.left != null) { if (nullish || temp.left.data > temp.data) { return false; } q.add(temp.left); } else { nullish = true; } if (temp.right != null) { if (nullish || temp.right.data > temp.data) { return false; } q.add(temp.right); } else { nullish = true; } } return true; } // Driver code public static void main(String[] args) { Node root = null; root = newNode(10); root.left = newNode(9); root.right = newNode(8); root.left.left = newNode(7); root.left.right = newNode(6); root.right.left = newNode(5); root.right.right = newNode(4); root.left.left.left = newNode(3); root.left.left.right = newNode(2); root.left.right.left = newNode(1); // Function call if (isHeap(root)) System.out.print(\"Given binary tree is a Heap\\n\"); else System.out.print(\"Given binary tree is not a Heap\\n\"); }} // This code is contributed by Rajput-Ji",
"e": 22544,
"s": 20921,
"text": null
},
{
"code": "// C# program to checks if a// binary tree is max heap or notusing System;using System.Collections.Generic;public class GFG{ // Tree node structure public class Node { public int data; public Node left; public Node right; }; // To add a new node static Node newNode(int k) { Node node = new Node(); node.data = k; node.right = node.left = null; return node; } static bool isHeap(Node root) { Queue<Node> q = new Queue<Node>(); q.Enqueue(root); bool nullish = false; while (q.Count!=0) { Node temp = q.Peek(); q.Dequeue(); if (temp.left != null) { if (nullish || temp.left.data > temp.data) { return false; } q.Enqueue(temp.left); } else { nullish = true; } if (temp.right != null) { if (nullish || temp.right.data > temp.data) { return false; } q.Enqueue(temp.right); } else { nullish = true; } } return true; } // Driver code public static void Main(String[] args) { Node root = null; root = newNode(10); root.left = newNode(9); root.right = newNode(8); root.left.left = newNode(7); root.left.right = newNode(6); root.right.left = newNode(5); root.right.right = newNode(4); root.left.left.left = newNode(3); root.left.left.right = newNode(2); root.left.right.left = newNode(1); // Function call if (isHeap(root)) Console.Write(\"Given binary tree is a Heap\\n\"); else Console.Write(\"Given binary tree is not a Heap\\n\"); }} // This code is contributed by aashish1995",
"e": 24199,
"s": 22544,
"text": null
},
{
"code": "<script> // JavaScript program to checks if a // binary tree is max heap or not class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } // To add a new node function newNode(k) { let node = new Node(k); return node; } function isHeap(root) { let q = []; q.push(root); let nullish = false; while (q.length > 0) { let temp = q[0]; q.shift(); if (temp.left != null) { if (nullish || temp.left.data > temp.data) { return false; } q.push(temp.left); } else { nullish = true; } if (temp.right != null) { if (nullish || temp.right.data > temp.data) { return false; } q.push(temp.right); } else { nullish = true; } } return true; } let root = null; root = newNode(10); root.left = newNode(9); root.right = newNode(8); root.left.left = newNode(7); root.left.right = newNode(6); root.right.left = newNode(5); root.right.right = newNode(4); root.left.left.left = newNode(3); root.left.left.right = newNode(2); root.left.right.left = newNode(1); // Function call if (isHeap(root)) document.write(\"Given binary tree is a Heap\" + \"</br>\"); else document.write(\"Given binary tree is not a Heap\" + \"</br>\"); </script>",
"e": 25792,
"s": 24199,
"text": null
},
{
"code": null,
"e": 25821,
"s": 25792,
"text": "Given binary tree is a Heap\n"
},
{
"code": null,
"e": 25993,
"s": 25821,
"text": "This article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 26004,
"s": 25993,
"text": "scorncer17"
},
{
"code": null,
"e": 26017,
"s": 26004,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 26028,
"s": 26017,
"text": "andrew1234"
},
{
"code": null,
"e": 26043,
"s": 26028,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 26055,
"s": 26043,
"text": "devilwebdev"
},
{
"code": null,
"e": 26065,
"s": 26055,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 26077,
"s": 26065,
"text": "aashish1995"
},
{
"code": null,
"e": 26084,
"s": 26077,
"text": "rrrtnx"
},
{
"code": null,
"e": 26093,
"s": 26084,
"text": "suresh07"
},
{
"code": null,
"e": 26109,
"s": 26093,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 26122,
"s": 26109,
"text": "simmytarika5"
},
{
"code": null,
"e": 26129,
"s": 26122,
"text": "arynkr"
},
{
"code": null,
"e": 26134,
"s": 26129,
"text": "Hike"
},
{
"code": null,
"e": 26153,
"s": 26134,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 26158,
"s": 26153,
"text": "Heap"
},
{
"code": null,
"e": 26163,
"s": 26158,
"text": "Tree"
},
{
"code": null,
"e": 26168,
"s": 26163,
"text": "Hike"
},
{
"code": null,
"e": 26187,
"s": 26168,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 26192,
"s": 26187,
"text": "Tree"
},
{
"code": null,
"e": 26197,
"s": 26192,
"text": "Heap"
},
{
"code": null,
"e": 26295,
"s": 26197,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26345,
"s": 26295,
"text": "Binary Search Tree | Set 1 (Search and Insertion)"
},
{
"code": null,
"e": 26374,
"s": 26345,
"text": "AVL Tree | Set 1 (Insertion)"
},
{
"code": null,
"e": 26410,
"s": 26374,
"text": "Binary Search Tree | Set 2 (Delete)"
},
{
"code": null,
"e": 26460,
"s": 26410,
"text": "A program to check if a binary tree is BST or not"
},
{
"code": null,
"e": 26516,
"s": 26460,
"text": "Find postorder traversal of BST from preorder traversal"
},
{
"code": null,
"e": 26525,
"s": 26516,
"text": "HeapSort"
},
{
"code": null,
"e": 26581,
"s": 26525,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 1"
},
{
"code": null,
"e": 26613,
"s": 26581,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 26644,
"s": 26613,
"text": "Huffman Coding | Greedy Algo-3"
}
] |
How to enable row selection in a JTable with Java | To enable row selection, use the setRowSelectionAllowed () method and set it to TRUE −
table.setCell setRowSelectionAllowed(true);
The following is an example to enable row selection in a JTable −
package my;
import java.awt.Color;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.TitledBorder;
public class SwingDemo {
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), "ODI Rankings", TitledBorder.CENTER, TitledBorder.TOP));
String[][] rec = {
{ "1", "Steve", "AUS" },
{ "2", "Virat", "IND" },
{ "3", "Kane", "NZ" },
{ "4", "David", "AUS" },
{ "5", "Ben", "ENG" },
{ "6", "Eion", "ENG" },
};
String[] header = { "Rank", "Player", "Country" };
JTable table = new JTable(rec, header);
table.setShowHorizontalLines(true);
table.setGridColor(Color.orange);
table.setRowSelectionAllowed(true);
panel.add(new JScrollPane(table));
frame.add(panel);
frame.setSize(550, 400);
frame.setVisible(true);
}
}
The output is as follows. Here, we have selected a row. We can select a row now since setRowSelectionAllowed() is set TRUE above − | [
{
"code": null,
"e": 1149,
"s": 1062,
"text": "To enable row selection, use the setRowSelectionAllowed () method and set it to TRUE −"
},
{
"code": null,
"e": 1193,
"s": 1149,
"text": "table.setCell setRowSelectionAllowed(true);"
},
{
"code": null,
"e": 1259,
"s": 1193,
"text": "The following is an example to enable row selection in a JTable −"
},
{
"code": null,
"e": 2371,
"s": 1259,
"text": "package my;\nimport java.awt.Color;\nimport javax.swing.BorderFactory;\nimport javax.swing.JFrame;\nimport javax.swing.JPanel;\nimport javax.swing.JScrollPane;\nimport javax.swing.JTable;\nimport javax.swing.border.TitledBorder;\npublic class SwingDemo {\n public static void main(String[] args) {\n JFrame frame = new JFrame();\n JPanel panel = new JPanel();\n panel.setBorder(BorderFactory.createTitledBorder(\n BorderFactory.createEtchedBorder(), \"ODI Rankings\", TitledBorder.CENTER, TitledBorder.TOP));\n String[][] rec = {\n { \"1\", \"Steve\", \"AUS\" },\n { \"2\", \"Virat\", \"IND\" },\n { \"3\", \"Kane\", \"NZ\" },\n { \"4\", \"David\", \"AUS\" },\n { \"5\", \"Ben\", \"ENG\" },\n { \"6\", \"Eion\", \"ENG\" },\n };\n String[] header = { \"Rank\", \"Player\", \"Country\" };\n JTable table = new JTable(rec, header);\n table.setShowHorizontalLines(true);\n table.setGridColor(Color.orange);\n table.setRowSelectionAllowed(true);\n panel.add(new JScrollPane(table));\n frame.add(panel);\n frame.setSize(550, 400);\n frame.setVisible(true);\n }\n}"
},
{
"code": null,
"e": 2502,
"s": 2371,
"text": "The output is as follows. Here, we have selected a row. We can select a row now since setRowSelectionAllowed() is set TRUE above −"
}
] |
How to parse an URL in JavaScript? | It is very simple to parse an URL in javascript by using DOM method rather than Regular expressions. If regular expressions are used then code will be much more complicated. In DOM method just a function call will return the parsed URL.
In the following example, initially a function is created and then an anchor tag "a" is created inside it using a DOM method. Later on the provided URL was assigned to the anchor tag using href. Now, when function returns the parts of the URL, it tries to return the parsed parts as shown in the output. Since the url is parsed, JSON.stringify() method is used so as to display the output.
Live Demo
<html>
<body>
<script>
function URL(url) {
var urlParser = document.createElement('a');
urlParser.href = url;
return {
protocol: urlParser.protocol,
host: urlParser.host,
hostname: urlParser.hostname,
port: urlParser.port,
pathname: urlParser.pathname,
search: urlParser.search,
hash: urlParser.hash
};
}
document.write(JSON.stringify(URL("https://www.youtube.com/watch?v=tNJJSrfKYwQ")));
</script>
</body>
</html>
{"protocol":"https:","host":"www.youtube.com","hostname":"www.youtube.com","port":"","pathname":"/watch","search":"?v=tNJJSrfKYwQ","hash":""} | [
{
"code": null,
"e": 1300,
"s": 1062,
"text": "It is very simple to parse an URL in javascript by using DOM method rather than Regular expressions. If regular expressions are used then code will be much more complicated. In DOM method just a function call will return the parsed URL. "
},
{
"code": null,
"e": 1690,
"s": 1300,
"text": "In the following example, initially a function is created and then an anchor tag \"a\" is created inside it using a DOM method. Later on the provided URL was assigned to the anchor tag using href. Now, when function returns the parts of the URL, it tries to return the parsed parts as shown in the output. Since the url is parsed, JSON.stringify() method is used so as to display the output."
},
{
"code": null,
"e": 1700,
"s": 1690,
"text": "Live Demo"
},
{
"code": null,
"e": 2211,
"s": 1700,
"text": "<html>\n<body>\n<script>\n function URL(url) {\n var urlParser = document.createElement('a');\n urlParser.href = url;\n return {\n protocol: urlParser.protocol,\n host: urlParser.host,\n hostname: urlParser.hostname,\n port: urlParser.port,\n pathname: urlParser.pathname,\n search: urlParser.search,\n hash: urlParser.hash\n };\n }\n document.write(JSON.stringify(URL(\"https://www.youtube.com/watch?v=tNJJSrfKYwQ\")));\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2353,
"s": 2211,
"text": "{\"protocol\":\"https:\",\"host\":\"www.youtube.com\",\"hostname\":\"www.youtube.com\",\"port\":\"\",\"pathname\":\"/watch\",\"search\":\"?v=tNJJSrfKYwQ\",\"hash\":\"\"}"
}
] |
Using Neural Networks to solve Ordinary Differential Equations | by Caio Davi | Towards Data Science | The idea of solving an ODE using a Neural Network was first described by Lagaris et al. The insight behind it is basically training a neural network to satisfy the conditions required by a differential equation. In other words, we need to find a function whose derivative satisfies the ODE conditions. This article will be going through the underlying mathematical foundations of this concept, and then we will implement it using TensorFlow. All the contents are also available in a Google Collab Notebook here.
Let’s say we have an ODE system, given by:
Hence, we can understand the differential operation as a function on the domain t with a known initial condition u(0)=u0. As we know, Neural Networks are known as universal approximators. We will take advantage of this property of Neural Networks to use them to approximate the solution of the given ODE:
Also, we may agree that the derivative of NN(t) will give us a similar equation:
So, if NN(t) is really close to the true solution, then we could say that its derivative is also close to the derivative of the true solution, i.e.:
Thus, we can turn this condition into our loss function. We have the given derivative function f(u,t) and we can calculate the Neural Network derivative NN′(t) at each step. This motivates the following loss function (which is the mean squared error of the two values):
You may remember the initial condition, we still need to handle that. The most straight-forward way would do this by adding an initial condition term to the cost function. It would look like this:
While that would work, it may not be the best approach. We all know the crucial importance of the loss function on the training of the Neural Network, and we also know that the number of terms on this function will impact directly the stability of our training. More terms on the loss function would (usually) imply unstable training. To avoid it, we can encode the initial condition into the loss in a more efficient way. Let’s define a new function and use it instead of directly using the neural network:
It’s easy to see that g(t) will always satisfy the initial condition since g(0) will lead to tNN(t)=0, leaving just the initial condition on the expression. This way, we can train g(t) to satisfy the ODE system instead of the Neural Network. Then, it will automatically be a solution to the derivative function. We can incorporate this new idea into our loss function:
We are about to implement the described method in python using the TensorFlow library. In order to have a better understanding of the method, we will use a low-level design, avoiding a number of possible optimizations provided by the library. Our focus, at this moment, is to clearly understand and implement the ODE-solver Neural Network. For this reason, we will also choose a simply ODE:
We can easily solve this problem by integrating both sides of the solution, leading to u+C=x2+C, and after fitting C to obey the initial condition we have u=x2+1. Nevertheless, instead of solve it analytically, let’s try to solve using Neural Nets.
For this example, we will create an MLP Neural Net with 2 hidden layers, sigmoid activation functions, and a gradient descent optimizer algorithm. Other topologies may also be used, this is just an example. We encourage you to try different approaches to this method.
Defining Variables
f0 = 1inf_s = np.sqrt(np.finfo(np.float32).eps)learning_rate = 0.01training_steps = 5000batch_size = 100display_step = 500# Network Parametersn_input = 1 # input layer number of neuronsn_hidden_1 = 32 # 1st layer number of neuronsn_hidden_2 = 32 # 2nd layer number of neuronsn_output = 1 # output layer number of neuronsweights = {'h1': tf.Variable(tf.random.normal([n_input, n_hidden_1])),'h2': tf.Variable(tf.random.normal([n_hidden_1, n_hidden_2])),'out': tf.Variable(tf.random.normal([n_hidden_2, n_output]))}biases = {'b1': tf.Variable(tf.random.normal([n_hidden_1])),'b2': tf.Variable(tf.random.normal([n_hidden_2])),'out': tf.Variable(tf.random.normal([n_output]))}# Stochastic gradient descent optimizer.optimizer = tf.optimizers.SGD(learning_rate)
Defining the Model and Loss Function
# Create modeldef multilayer_perceptron(x): x = np.array([[[x]]], dtype='float32') layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1']) layer_1 = tf.nn.sigmoid(layer_1) layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2']) layer_2 = tf.nn.sigmoid(layer_2) output = tf.matmul(layer_2, weights['out']) + biases['out'] return tf.nn.sigmoid(output)# Universal Approximatordef g(x): return x * multilayer_perceptron(x) + f0# Given EDOdef f(x): return 2*x# Custom loss function to approximate the derivativesdef custom_loss(): summation = [] for x in np.linspace(-1,1,10): dNN = (g(x+inf_s)-g(x))/inf_s summation.append((dNN - f(x))**2) return tf.sqrt(tf.reduce_mean(tf.abs(summation)))
Notice that we don’t have any parameters on our loss function. Usually, the loss function would compare the prediction with the actual data. In our case, we don’t need data points.
Since we know the ODE function ruling this model, we can calculate the expected value at each point x. You may also notice that we are always calculating the loss using 10 points in the interval {-1,1}. It might not be enough for all possible functions, but given the simplicity of our example, I think we are gonna be ok.
The Neural Network Derivative is expressed by the variable dNN in the code. We are just using the differentiation definition:
Train Function
def train_step(): with tf.GradientTape() as tape: loss = custom_loss() trainable_variables=list(weights.values())+list(biases.values()) gradients = tape.gradient(loss, trainable_variables) optimizer.apply_gradients(zip(gradients, trainable_variables))# Training the Model:for i in range(training_steps): train_step() if i % display_step == 0: print("loss: %f " % (custom_loss()))
Plotting the Results
# True Solution (found analitically)def true_solution(x): return x**2 + 1X = np.linspace(0, 1, 100)result = []for i in X: result.append(g(i).numpy()[0][0][0])S = true_solution(X)plt.plot(X, result)plt.plot(X, S)plt.show()
This will yield us the following plot:
It is quite an approximation, mostly if we remember that was no dataset used to training. It might be even better if we had used more collocation points to calculate the loss function, or if we keep the training a little longer. We invite the reader to try out the code and make these adjustments or even try other ODEs. You can find all the contents of this post in a Google Collab Notebook here. Have fun! And thank you for the reading. | [
{
"code": null,
"e": 559,
"s": 47,
"text": "The idea of solving an ODE using a Neural Network was first described by Lagaris et al. The insight behind it is basically training a neural network to satisfy the conditions required by a differential equation. In other words, we need to find a function whose derivative satisfies the ODE conditions. This article will be going through the underlying mathematical foundations of this concept, and then we will implement it using TensorFlow. All the contents are also available in a Google Collab Notebook here."
},
{
"code": null,
"e": 602,
"s": 559,
"text": "Let’s say we have an ODE system, given by:"
},
{
"code": null,
"e": 907,
"s": 602,
"text": "Hence, we can understand the differential operation as a function on the domain t with a known initial condition u(0)=u0. As we know, Neural Networks are known as universal approximators. We will take advantage of this property of Neural Networks to use them to approximate the solution of the given ODE:"
},
{
"code": null,
"e": 988,
"s": 907,
"text": "Also, we may agree that the derivative of NN(t) will give us a similar equation:"
},
{
"code": null,
"e": 1137,
"s": 988,
"text": "So, if NN(t) is really close to the true solution, then we could say that its derivative is also close to the derivative of the true solution, i.e.:"
},
{
"code": null,
"e": 1407,
"s": 1137,
"text": "Thus, we can turn this condition into our loss function. We have the given derivative function f(u,t) and we can calculate the Neural Network derivative NN′(t) at each step. This motivates the following loss function (which is the mean squared error of the two values):"
},
{
"code": null,
"e": 1604,
"s": 1407,
"text": "You may remember the initial condition, we still need to handle that. The most straight-forward way would do this by adding an initial condition term to the cost function. It would look like this:"
},
{
"code": null,
"e": 2112,
"s": 1604,
"text": "While that would work, it may not be the best approach. We all know the crucial importance of the loss function on the training of the Neural Network, and we also know that the number of terms on this function will impact directly the stability of our training. More terms on the loss function would (usually) imply unstable training. To avoid it, we can encode the initial condition into the loss in a more efficient way. Let’s define a new function and use it instead of directly using the neural network:"
},
{
"code": null,
"e": 2481,
"s": 2112,
"text": "It’s easy to see that g(t) will always satisfy the initial condition since g(0) will lead to tNN(t)=0, leaving just the initial condition on the expression. This way, we can train g(t) to satisfy the ODE system instead of the Neural Network. Then, it will automatically be a solution to the derivative function. We can incorporate this new idea into our loss function:"
},
{
"code": null,
"e": 2872,
"s": 2481,
"text": "We are about to implement the described method in python using the TensorFlow library. In order to have a better understanding of the method, we will use a low-level design, avoiding a number of possible optimizations provided by the library. Our focus, at this moment, is to clearly understand and implement the ODE-solver Neural Network. For this reason, we will also choose a simply ODE:"
},
{
"code": null,
"e": 3121,
"s": 2872,
"text": "We can easily solve this problem by integrating both sides of the solution, leading to u+C=x2+C, and after fitting C to obey the initial condition we have u=x2+1. Nevertheless, instead of solve it analytically, let’s try to solve using Neural Nets."
},
{
"code": null,
"e": 3389,
"s": 3121,
"text": "For this example, we will create an MLP Neural Net with 2 hidden layers, sigmoid activation functions, and a gradient descent optimizer algorithm. Other topologies may also be used, this is just an example. We encourage you to try different approaches to this method."
},
{
"code": null,
"e": 3408,
"s": 3389,
"text": "Defining Variables"
},
{
"code": null,
"e": 4172,
"s": 3408,
"text": "f0 = 1inf_s = np.sqrt(np.finfo(np.float32).eps)learning_rate = 0.01training_steps = 5000batch_size = 100display_step = 500# Network Parametersn_input = 1 # input layer number of neuronsn_hidden_1 = 32 # 1st layer number of neuronsn_hidden_2 = 32 # 2nd layer number of neuronsn_output = 1 # output layer number of neuronsweights = {'h1': tf.Variable(tf.random.normal([n_input, n_hidden_1])),'h2': tf.Variable(tf.random.normal([n_hidden_1, n_hidden_2])),'out': tf.Variable(tf.random.normal([n_hidden_2, n_output]))}biases = {'b1': tf.Variable(tf.random.normal([n_hidden_1])),'b2': tf.Variable(tf.random.normal([n_hidden_2])),'out': tf.Variable(tf.random.normal([n_output]))}# Stochastic gradient descent optimizer.optimizer = tf.optimizers.SGD(learning_rate)"
},
{
"code": null,
"e": 4209,
"s": 4172,
"text": "Defining the Model and Loss Function"
},
{
"code": null,
"e": 4928,
"s": 4209,
"text": "# Create modeldef multilayer_perceptron(x): x = np.array([[[x]]], dtype='float32') layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1']) layer_1 = tf.nn.sigmoid(layer_1) layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2']) layer_2 = tf.nn.sigmoid(layer_2) output = tf.matmul(layer_2, weights['out']) + biases['out'] return tf.nn.sigmoid(output)# Universal Approximatordef g(x): return x * multilayer_perceptron(x) + f0# Given EDOdef f(x): return 2*x# Custom loss function to approximate the derivativesdef custom_loss(): summation = [] for x in np.linspace(-1,1,10): dNN = (g(x+inf_s)-g(x))/inf_s summation.append((dNN - f(x))**2) return tf.sqrt(tf.reduce_mean(tf.abs(summation)))"
},
{
"code": null,
"e": 5109,
"s": 4928,
"text": "Notice that we don’t have any parameters on our loss function. Usually, the loss function would compare the prediction with the actual data. In our case, we don’t need data points."
},
{
"code": null,
"e": 5432,
"s": 5109,
"text": "Since we know the ODE function ruling this model, we can calculate the expected value at each point x. You may also notice that we are always calculating the loss using 10 points in the interval {-1,1}. It might not be enough for all possible functions, but given the simplicity of our example, I think we are gonna be ok."
},
{
"code": null,
"e": 5558,
"s": 5432,
"text": "The Neural Network Derivative is expressed by the variable dNN in the code. We are just using the differentiation definition:"
},
{
"code": null,
"e": 5573,
"s": 5558,
"text": "Train Function"
},
{
"code": null,
"e": 5965,
"s": 5573,
"text": "def train_step(): with tf.GradientTape() as tape: loss = custom_loss() trainable_variables=list(weights.values())+list(biases.values()) gradients = tape.gradient(loss, trainable_variables) optimizer.apply_gradients(zip(gradients, trainable_variables))# Training the Model:for i in range(training_steps): train_step() if i % display_step == 0: print(\"loss: %f \" % (custom_loss()))"
},
{
"code": null,
"e": 5986,
"s": 5965,
"text": "Plotting the Results"
},
{
"code": null,
"e": 6210,
"s": 5986,
"text": "# True Solution (found analitically)def true_solution(x): return x**2 + 1X = np.linspace(0, 1, 100)result = []for i in X: result.append(g(i).numpy()[0][0][0])S = true_solution(X)plt.plot(X, result)plt.plot(X, S)plt.show()"
},
{
"code": null,
"e": 6249,
"s": 6210,
"text": "This will yield us the following plot:"
}
] |
Initialize HashSet in Java | A set is a collection which does not allows duplicate values. HashSet is an implementation of a Set. Following are the ways in which we can initialize a HashSet in Java.
Using constructor − Pass a collection to Constructor to initialize an HashSet.
Using constructor − Pass a collection to Constructor to initialize an HashSet.
Using addAll() − Pass a collection to Collections.addAll() to initialize an HashSet.
Using addAll() − Pass a collection to Collections.addAll() to initialize an HashSet.
Using unmodifiableSet() − Pass a collection to Collections.unmodifiableSet() to get a unmodifiable Set.
Using unmodifiableSet() − Pass a collection to Collections.unmodifiableSet() to get a unmodifiable Set.
Using add() − Using add(element) method of Set.
Using add() − Using add(element) method of Set.
Following is an example of using above ways.
Infinity
Now consider the following code snippet.
Live Demo
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Tester{
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1,2,3,4,5,6);
//Scenario 1
Set<Integer> set1 = new HashSet<>(list);
System.out.println(set1);
//Scenario 2
Set<Integer> set2 = new HashSet<>(list);
Collections.addAll(set2, 1,2,3,4,5,6);
System.out.println(set2);
//Scenario 3
Set<Integer> set3 = Collections.unmodifiableSet(set2);
System.out.println(set3);
//Scenario 4
Set<Integer> set4 = new HashSet<>();
set4.add(1);set4.add(2);set4.add(3);
set4.add(4);set4.add(5);set4.add(6);
System.out.println(set4);
}
}
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6] | [
{
"code": null,
"e": 1232,
"s": 1062,
"text": "A set is a collection which does not allows duplicate values. HashSet is an implementation of a Set. Following are the ways in which we can initialize a HashSet in Java."
},
{
"code": null,
"e": 1311,
"s": 1232,
"text": "Using constructor − Pass a collection to Constructor to initialize an HashSet."
},
{
"code": null,
"e": 1390,
"s": 1311,
"text": "Using constructor − Pass a collection to Constructor to initialize an HashSet."
},
{
"code": null,
"e": 1475,
"s": 1390,
"text": "Using addAll() − Pass a collection to Collections.addAll() to initialize an HashSet."
},
{
"code": null,
"e": 1560,
"s": 1475,
"text": "Using addAll() − Pass a collection to Collections.addAll() to initialize an HashSet."
},
{
"code": null,
"e": 1664,
"s": 1560,
"text": "Using unmodifiableSet() − Pass a collection to Collections.unmodifiableSet() to get a unmodifiable Set."
},
{
"code": null,
"e": 1768,
"s": 1664,
"text": "Using unmodifiableSet() − Pass a collection to Collections.unmodifiableSet() to get a unmodifiable Set."
},
{
"code": null,
"e": 1816,
"s": 1768,
"text": "Using add() − Using add(element) method of Set."
},
{
"code": null,
"e": 1864,
"s": 1816,
"text": "Using add() − Using add(element) method of Set."
},
{
"code": null,
"e": 1909,
"s": 1864,
"text": "Following is an example of using above ways."
},
{
"code": null,
"e": 1918,
"s": 1909,
"text": "Infinity"
},
{
"code": null,
"e": 1959,
"s": 1918,
"text": "Now consider the following code snippet."
},
{
"code": null,
"e": 1970,
"s": 1959,
"text": " Live Demo"
},
{
"code": null,
"e": 2761,
"s": 1970,
"text": "import java.util.Arrays;\nimport java.util.Collections;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\npublic class Tester{\n public static void main(String[] args) {\n\n List<Integer> list = Arrays.asList(1,2,3,4,5,6);\n //Scenario 1\n Set<Integer> set1 = new HashSet<>(list);\n System.out.println(set1);\n\n //Scenario 2\n Set<Integer> set2 = new HashSet<>(list);\n Collections.addAll(set2, 1,2,3,4,5,6);\n System.out.println(set2);\n\n //Scenario 3\n Set<Integer> set3 = Collections.unmodifiableSet(set2);\n System.out.println(set3);\n\n //Scenario 4\n Set<Integer> set4 = new HashSet<>();\n set4.add(1);set4.add(2);set4.add(3);\n set4.add(4);set4.add(5);set4.add(6);\n System.out.println(set4);\n }\n}"
},
{
"code": null,
"e": 2837,
"s": 2761,
"text": "[1, 2, 3, 4, 5, 6]\n[1, 2, 3, 4, 5, 6]\n[1, 2, 3, 4, 5, 6]\n[1, 2, 3, 4, 5, 6]"
}
] |
Will a finally block execute after a return statement in a method in Java? | Yes, the finally block will be executed even after a return statement in a method.
The finally block will always execute even an exception occurred or not in Java. If we call the System.exit() method explicitly in the finally block then only it will not be executed. There are few situations where the finally will not be executed like JVM crash, power failure, software crash and etc. Other than these conditions, the finally block will be always executed.
public class FinallyBlockAfterReturnTest {
public static void main(String[] args) {
System.out.println(count());
}
public static int count() {
try {
return 1;
} catch(Exception e) {
return 2;
} finally {
System.out.println("Finally block will execute even after a return statement in a method");
}
}
}
Finally block will always excute even after a return statement in a method
1 | [
{
"code": null,
"e": 1146,
"s": 1062,
"text": "Yes, the finally block will be executed even after a return statement in a method. "
},
{
"code": null,
"e": 1521,
"s": 1146,
"text": "The finally block will always execute even an exception occurred or not in Java. If we call the System.exit() method explicitly in the finally block then only it will not be executed. There are few situations where the finally will not be executed like JVM crash, power failure, software crash and etc. Other than these conditions, the finally block will be always executed."
},
{
"code": null,
"e": 1892,
"s": 1521,
"text": "public class FinallyBlockAfterReturnTest {\n public static void main(String[] args) {\n System.out.println(count());\n }\n public static int count() {\n try {\n return 1;\n } catch(Exception e) {\n return 2;\n } finally {\n System.out.println(\"Finally block will execute even after a return statement in a method\");\n }\n }\n}"
},
{
"code": null,
"e": 1969,
"s": 1892,
"text": "Finally block will always excute even after a return statement in a method\n1"
}
] |
Clearing a Dictionary using Javascript | We'll implement a clear() function that simply clears the contents of the container. For example,
clear() {
this.container = {}
}
You can test this using −
const myMap = new MyMap();
myMap.put("key1", "value1");
myMap.put("key2", "value2");
myMap.display();
myMap.clear();
myMap.display();
This will give the output −
{ key1: 'value1', key2: 'value2' }
You can use the clear method in the same way in ES6 maps as well. For example,
const myMap = new Map([
["key1", "value1"],
["key2", "value2"]
]);
console.log(myMap)
myMap.clear();
console.log(myMap)
This will give the output −
Map { 'key1' => 'value1', 'key2' => 'value2' }
Map {} | [
{
"code": null,
"e": 1161,
"s": 1062,
"text": "We'll implement a clear() function that simply clears the contents of the container. For example, "
},
{
"code": null,
"e": 1196,
"s": 1161,
"text": "clear() {\n this.container = {}\n}"
},
{
"code": null,
"e": 1223,
"s": 1196,
"text": "You can test this using − "
},
{
"code": null,
"e": 1359,
"s": 1223,
"text": "const myMap = new MyMap();\nmyMap.put(\"key1\", \"value1\");\nmyMap.put(\"key2\", \"value2\");\n \nmyMap.display();\nmyMap.clear();\nmyMap.display();"
},
{
"code": null,
"e": 1387,
"s": 1359,
"text": "This will give the output −"
},
{
"code": null,
"e": 1422,
"s": 1387,
"text": "{ key1: 'value1', key2: 'value2' }"
},
{
"code": null,
"e": 1501,
"s": 1422,
"text": "You can use the clear method in the same way in ES6 maps as well. For example,"
},
{
"code": null,
"e": 1628,
"s": 1501,
"text": "const myMap = new Map([\n [\"key1\", \"value1\"],\n [\"key2\", \"value2\"]\n]);\n\nconsole.log(myMap)\nmyMap.clear();\nconsole.log(myMap)"
},
{
"code": null,
"e": 1656,
"s": 1628,
"text": "This will give the output −"
},
{
"code": null,
"e": 1710,
"s": 1656,
"text": "Map { 'key1' => 'value1', 'key2' => 'value2' }\nMap {}"
}
] |
Find x, y, z that satisfy 2/n = 1/x + 1/y + 1/z - GeeksforGeeks | 21 Apr, 2021
Given n, find x, y, z such that x, y, z satisfy the equation “2/n = 1/x + 1/y + 1/z”There are multiple x, y and z that satisfy the equation print anyone of them, if not possible then print -1.Examples:
Input : 3
Output : 3 4 12
Explanation: here 3 4 and 12 satisfy
the given equation
Input : 7
Output : 7 8 56
Note that for n = 1 there is no solution, and for n > 1 there is solution x = n, y = n+1, z = n·(n+1).To come to this solution, represent 2/n as 1/n+1/n and reduce the problem to represent 1/n as a sum of two fractions. Let’s find the difference between 1/n and 1/(n+1) and get a fraction 1/(n*(n+1)), so the solution is
2/n = 1/n + 1/(n+1) + 1/(n*(n+1))
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find x y z that// satisfies 2/n = 1/x + 1/y + 1/z...#include <bits/stdc++.h>using namespace std; // function to find x y and z that// satisfy given equation.void printXYZ(int n){ if (n == 1) cout << -1; else cout << "x is " << n << "\ny is " << n + 1 << "\nz is " << n * (n + 1);} // driver program to test the above functionint main(){ int n = 7; printXYZ(n); return 0;}
// Java program to find x y z that// satisfies 2/n = 1/x + 1/y + 1/z...import java.io.*; class Sums { // function to find x y and z that // satisfy given equation. static void printXYZ(int n){ if (n == 1) System.out.println(-1); else{ System.out.println("x is "+ n); System.out.println("y is "+ (n+1)); System.out.println("z is "+ (n * (n + 1))); } } // Driver program to test the above function public static void main (String[] args) { int n = 7; printXYZ(n); }} // This code is contributed by Chinmoy Lenka
# Python3 code to find x y z that# satisfies 2/n = 1/x + 1/y + 1/z... # function to find x y and z that# satisfy given equation.def printXYZ( n ): if n == 1: print(-1) else: print("x is " , n ) print("y is " ,n + 1) print("z is " ,n * (n + 1)) # driver code to test the above functionn = 7printXYZ(n) # This code is contributed by "Sharad_Bhardwaj".
// C# program to find x y z that// satisfies 2/n = 1/x + 1/y + 1/z...using System; class GFG{ // function to find x y and z that // satisfy given equation. static void printXYZ(int n) { if (n == 1) Console.WriteLine(-1); else { Console.WriteLine("x is "+ n); Console.WriteLine("y is "+ (n+1)); Console.WriteLine("z is "+ (n * (n + 1))); } } // Driver program public static void Main () { int n = 7; printXYZ(n); }} // This code is contributed by vt_m
<?php// PHP program to find x y z that// satisfies 2/n = 1/x + 1/y + 1/z... // function to find x y and z that// satisfy given equation.function printXYZ($n){ if ($n == 1) echo -1; else echo "x is " , $n , "\ny is " , $n + 1 , "\nz is ", $n * ($n + 1);} // Driver Code $n = 7; printXYZ($n); // This code is contributed by anuj_67.?>
<script> // Javascript program to find x y z that// satisfies 2/n = 1/x + 1/y + 1/z... // function to find x y and z that// satisfy given equation.function printXYZ(n){ if (n == 1) document.write(-1); else document.write("x is " + n + "<br>y is " + (n + 1) + "<br>z is " + n * (n + 1));} // driver program to test the above function let n = 7; printXYZ(n); </script>
Output:
x is 7
y is 8
z is 56
Time complexity: O(1)Alternate Solution We can write 2/n = 1/n + 1/n. And further as 2/n = 1/n + 1/2n + 1/2n.
vt_m
subhammahato348
Fraction
Mathematical
School Programming
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Program to print prime numbers from 1 to N.
Program to multiply two matrices
Fizz Buzz Implementation
Modular multiplicative inverse
Python Dictionary
Arrays in C/C++
Inheritance in C++
Reverse a string in Java
Interfaces in Java | [
{
"code": null,
"e": 24692,
"s": 24664,
"text": "\n21 Apr, 2021"
},
{
"code": null,
"e": 24896,
"s": 24692,
"text": "Given n, find x, y, z such that x, y, z satisfy the equation “2/n = 1/x + 1/y + 1/z”There are multiple x, y and z that satisfy the equation print anyone of them, if not possible then print -1.Examples: "
},
{
"code": null,
"e": 25007,
"s": 24896,
"text": "Input : 3\nOutput : 3 4 12\nExplanation: here 3 4 and 12 satisfy \nthe given equation\n\nInput : 7\nOutput : 7 8 56 "
},
{
"code": null,
"e": 25331,
"s": 25009,
"text": "Note that for n = 1 there is no solution, and for n > 1 there is solution x = n, y = n+1, z = n·(n+1).To come to this solution, represent 2/n as 1/n+1/n and reduce the problem to represent 1/n as a sum of two fractions. Let’s find the difference between 1/n and 1/(n+1) and get a fraction 1/(n*(n+1)), so the solution is "
},
{
"code": null,
"e": 25366,
"s": 25331,
"text": "2/n = 1/n + 1/(n+1) + 1/(n*(n+1)) "
},
{
"code": null,
"e": 25372,
"s": 25368,
"text": "C++"
},
{
"code": null,
"e": 25377,
"s": 25372,
"text": "Java"
},
{
"code": null,
"e": 25385,
"s": 25377,
"text": "Python3"
},
{
"code": null,
"e": 25388,
"s": 25385,
"text": "C#"
},
{
"code": null,
"e": 25392,
"s": 25388,
"text": "PHP"
},
{
"code": null,
"e": 25403,
"s": 25392,
"text": "Javascript"
},
{
"code": "// CPP program to find x y z that// satisfies 2/n = 1/x + 1/y + 1/z...#include <bits/stdc++.h>using namespace std; // function to find x y and z that// satisfy given equation.void printXYZ(int n){ if (n == 1) cout << -1; else cout << \"x is \" << n << \"\\ny is \" << n + 1 << \"\\nz is \" << n * (n + 1);} // driver program to test the above functionint main(){ int n = 7; printXYZ(n); return 0;}",
"e": 25849,
"s": 25403,
"text": null
},
{
"code": "// Java program to find x y z that// satisfies 2/n = 1/x + 1/y + 1/z...import java.io.*; class Sums { // function to find x y and z that // satisfy given equation. static void printXYZ(int n){ if (n == 1) System.out.println(-1); else{ System.out.println(\"x is \"+ n); System.out.println(\"y is \"+ (n+1)); System.out.println(\"z is \"+ (n * (n + 1))); } } // Driver program to test the above function public static void main (String[] args) { int n = 7; printXYZ(n); }} // This code is contributed by Chinmoy Lenka",
"e": 26447,
"s": 25849,
"text": null
},
{
"code": "# Python3 code to find x y z that# satisfies 2/n = 1/x + 1/y + 1/z... # function to find x y and z that# satisfy given equation.def printXYZ( n ): if n == 1: print(-1) else: print(\"x is \" , n ) print(\"y is \" ,n + 1) print(\"z is \" ,n * (n + 1)) # driver code to test the above functionn = 7printXYZ(n) # This code is contributed by \"Sharad_Bhardwaj\".",
"e": 26831,
"s": 26447,
"text": null
},
{
"code": "// C# program to find x y z that// satisfies 2/n = 1/x + 1/y + 1/z...using System; class GFG{ // function to find x y and z that // satisfy given equation. static void printXYZ(int n) { if (n == 1) Console.WriteLine(-1); else { Console.WriteLine(\"x is \"+ n); Console.WriteLine(\"y is \"+ (n+1)); Console.WriteLine(\"z is \"+ (n * (n + 1))); } } // Driver program public static void Main () { int n = 7; printXYZ(n); }} // This code is contributed by vt_m",
"e": 27400,
"s": 26831,
"text": null
},
{
"code": "<?php// PHP program to find x y z that// satisfies 2/n = 1/x + 1/y + 1/z... // function to find x y and z that// satisfy given equation.function printXYZ($n){ if ($n == 1) echo -1; else echo \"x is \" , $n , \"\\ny is \" , $n + 1 , \"\\nz is \", $n * ($n + 1);} // Driver Code $n = 7; printXYZ($n); // This code is contributed by anuj_67.?>",
"e": 27799,
"s": 27400,
"text": null
},
{
"code": "<script> // Javascript program to find x y z that// satisfies 2/n = 1/x + 1/y + 1/z... // function to find x y and z that// satisfy given equation.function printXYZ(n){ if (n == 1) document.write(-1); else document.write(\"x is \" + n + \"<br>y is \" + (n + 1) + \"<br>z is \" + n * (n + 1));} // driver program to test the above function let n = 7; printXYZ(n); </script>",
"e": 28219,
"s": 27799,
"text": null
},
{
"code": null,
"e": 28228,
"s": 28219,
"text": "Output: "
},
{
"code": null,
"e": 28250,
"s": 28228,
"text": "x is 7\ny is 8\nz is 56"
},
{
"code": null,
"e": 28361,
"s": 28250,
"text": "Time complexity: O(1)Alternate Solution We can write 2/n = 1/n + 1/n. And further as 2/n = 1/n + 1/2n + 1/2n. "
},
{
"code": null,
"e": 28366,
"s": 28361,
"text": "vt_m"
},
{
"code": null,
"e": 28382,
"s": 28366,
"text": "subhammahato348"
},
{
"code": null,
"e": 28391,
"s": 28382,
"text": "Fraction"
},
{
"code": null,
"e": 28404,
"s": 28391,
"text": "Mathematical"
},
{
"code": null,
"e": 28423,
"s": 28404,
"text": "School Programming"
},
{
"code": null,
"e": 28436,
"s": 28423,
"text": "Mathematical"
},
{
"code": null,
"e": 28534,
"s": 28436,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28566,
"s": 28534,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 28610,
"s": 28566,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 28643,
"s": 28610,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 28668,
"s": 28643,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 28699,
"s": 28668,
"text": "Modular multiplicative inverse"
},
{
"code": null,
"e": 28717,
"s": 28699,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28733,
"s": 28717,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 28752,
"s": 28733,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 28777,
"s": 28752,
"text": "Reverse a string in Java"
}
] |
kill command in Linux with Examples - GeeksforGeeks | 22 May, 2019
kill command in Linux (located in /bin/kill), is a built-in command which is used to terminate processes manually. kill command sends a signal to a process which terminates the process. If the user doesn’t specify any signal which is to be sent along with kill command then default TERM signal is sent that terminates the process.
1. kill -l :To display all the available signals you can use below command option:
Syntax:
$kill -l
Signals can be specified in three ways:
By number (e.g. -5)
With SIG prefix (e.g. -SIGkill)
Without SIG prefix (e.g. -kill)
Note:
Negative PID values are used to indicate the process group ID. If you pass a process group ID then all the process within that group will receive the signal.
A PID of -1 is very special as it indicates all the processes except kill and init, which is the parent process of all processes on the system.
To display a list of running processes use the command ps and this will show you running processes with their PID number. To specify which process should receive the kill signal we need to provide the PID.Syntax:$ps
Syntax:
$ps
2. kill pid : To show how to use a PID with the kill command.
Syntax:
$kill pid
3. kill -s : To show how to send signal to processes.
Syntax:
kill {-signal | -s signal} pid
4. kill -L :This command is used to list available signals in a table format.
Syntax:
kill {-l | --list[=signal] | -L | --table}
linux-command
Linux-system-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
tar command in Linux with examples
UDP Server-Client implementation in C
'crontab' in Linux with Examples
Conditional Statements | Shell Script
Cat command in Linux with examples
touch command in Linux with Examples
Mutex lock for Linux Thread Synchronization
echo command in Linux with Examples
Tail command in Linux with examples
Compiling with g++ | [
{
"code": null,
"e": 24555,
"s": 24527,
"text": "\n22 May, 2019"
},
{
"code": null,
"e": 24886,
"s": 24555,
"text": "kill command in Linux (located in /bin/kill), is a built-in command which is used to terminate processes manually. kill command sends a signal to a process which terminates the process. If the user doesn’t specify any signal which is to be sent along with kill command then default TERM signal is sent that terminates the process."
},
{
"code": null,
"e": 24969,
"s": 24886,
"text": "1. kill -l :To display all the available signals you can use below command option:"
},
{
"code": null,
"e": 24977,
"s": 24969,
"text": "Syntax:"
},
{
"code": null,
"e": 24987,
"s": 24977,
"text": "$kill -l\n"
},
{
"code": null,
"e": 25027,
"s": 24987,
"text": "Signals can be specified in three ways:"
},
{
"code": null,
"e": 25047,
"s": 25027,
"text": "By number (e.g. -5)"
},
{
"code": null,
"e": 25079,
"s": 25047,
"text": "With SIG prefix (e.g. -SIGkill)"
},
{
"code": null,
"e": 25111,
"s": 25079,
"text": "Without SIG prefix (e.g. -kill)"
},
{
"code": null,
"e": 25117,
"s": 25111,
"text": "Note:"
},
{
"code": null,
"e": 25275,
"s": 25117,
"text": "Negative PID values are used to indicate the process group ID. If you pass a process group ID then all the process within that group will receive the signal."
},
{
"code": null,
"e": 25419,
"s": 25275,
"text": "A PID of -1 is very special as it indicates all the processes except kill and init, which is the parent process of all processes on the system."
},
{
"code": null,
"e": 25636,
"s": 25419,
"text": "To display a list of running processes use the command ps and this will show you running processes with their PID number. To specify which process should receive the kill signal we need to provide the PID.Syntax:$ps\n"
},
{
"code": null,
"e": 25644,
"s": 25636,
"text": "Syntax:"
},
{
"code": null,
"e": 25649,
"s": 25644,
"text": "$ps\n"
},
{
"code": null,
"e": 25711,
"s": 25649,
"text": "2. kill pid : To show how to use a PID with the kill command."
},
{
"code": null,
"e": 25719,
"s": 25711,
"text": "Syntax:"
},
{
"code": null,
"e": 25730,
"s": 25719,
"text": "$kill pid\n"
},
{
"code": null,
"e": 25784,
"s": 25730,
"text": "3. kill -s : To show how to send signal to processes."
},
{
"code": null,
"e": 25792,
"s": 25784,
"text": "Syntax:"
},
{
"code": null,
"e": 25825,
"s": 25792,
"text": "kill {-signal | -s signal} pid \n"
},
{
"code": null,
"e": 25903,
"s": 25825,
"text": "4. kill -L :This command is used to list available signals in a table format."
},
{
"code": null,
"e": 25911,
"s": 25903,
"text": "Syntax:"
},
{
"code": null,
"e": 25956,
"s": 25911,
"text": "kill {-l | --list[=signal] | -L | --table} \n"
},
{
"code": null,
"e": 25970,
"s": 25956,
"text": "linux-command"
},
{
"code": null,
"e": 25992,
"s": 25970,
"text": "Linux-system-commands"
},
{
"code": null,
"e": 25999,
"s": 25992,
"text": "Picked"
},
{
"code": null,
"e": 26010,
"s": 25999,
"text": "Linux-Unix"
},
{
"code": null,
"e": 26108,
"s": 26010,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26117,
"s": 26108,
"text": "Comments"
},
{
"code": null,
"e": 26130,
"s": 26117,
"text": "Old Comments"
},
{
"code": null,
"e": 26165,
"s": 26130,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 26203,
"s": 26165,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 26236,
"s": 26203,
"text": "'crontab' in Linux with Examples"
},
{
"code": null,
"e": 26274,
"s": 26236,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 26309,
"s": 26274,
"text": "Cat command in Linux with examples"
},
{
"code": null,
"e": 26346,
"s": 26309,
"text": "touch command in Linux with Examples"
},
{
"code": null,
"e": 26390,
"s": 26346,
"text": "Mutex lock for Linux Thread Synchronization"
},
{
"code": null,
"e": 26426,
"s": 26390,
"text": "echo command in Linux with Examples"
},
{
"code": null,
"e": 26462,
"s": 26426,
"text": "Tail command in Linux with examples"
}
] |
MFC - Combo Boxes | A combo box consists of a list box combined with either a static control or edit control. it is represented by CComboBox class. The list-box portion of the control may be displayed at all times or may only drop down when the user selects the drop-down arrow next to the control.
AddString
Adds a string to the end of the list in the list box of a combo box, or at the sorted position for list boxes with the CBS_SORT style.
Clear
Deletes (clears) the current selection, if any, in the edit control.
CompareItem
Called by the framework to determine the relative position of a new list item in a sorted ownerdrawn combo box.
Copy
Copies the current selection, if any, onto the Clipboard in CF_TEXT format.
Create
Creates the combo box and attaches it to the CComboBox object.
Cut
Deletes (cuts) the current selection, if any, in the edit control and copies the deleted text onto the Clipboard in CF_TEXT format.
DeleteItem
Called by the framework when a list item is deleted from an owner-drawn combo box.
DeleteString
Deletes a string from the list box of a combo box.
Dir
Adds a list of file names to the list box of a combo box.
DrawItem
Called by the framework when a visual aspect of an owner-drawn combo box changes.
FindString
Finds the first string that contains the specified prefix in the list box of a combo box.
FindStringExact
Finds the first list-box string (in a combo box) that matches the specified string.
GetComboBoxInfo
Retrieves information about the CComboBox object.
GetCount
Retrieves the number of items in the list box of a combo box.
GetCueBanner
Gets the cue text that is displayed for a combo box control.
GetCurSel
Retrieves the index of the currently selected item, if any, in the list box of a combo box.
GetDroppedControlRect
Retrieves the screen coordinates of the visible (dropped down) list box of a drop-down combo box.
GetDroppedState
Determines whether the list box of a drop-down combo box is visible (dropped down).
GetDroppedWidth
Retrieves the minimum allowed width for the drop-down list-box portion of a combo box.
GetEditSel
Gets the starting and ending character positions of the current selection in the edit control of a combo box.
GetExtendedUI
Determines whether a combo box has the default user interface or the extended user interface
GetHorizontalExtent
Returns the width in pixels that the list-box portion of the combo box can be scrolled horizontally.
GetItemData
Retrieves the applicationsupplied 32-bit value associated with the specified combo-box item.
GetItemDataPtr
Retrieves the applicationsupplied 32-bit pointer that is associated with the specified combo-box item.
GetItemHeight
Retrieves the height of list items in a combo box.
GetLBText
Gets a string from the list box of a combo box.
GetLBTextLen
Gets the length of a string in the list box of a combo box.
GetLocale
Retrieves the locale identifier for a combo box.
GetMinVisible
Gets the minimum number of visible items in the drop-down list of the current combo box.
GetTopIndex
Returns the index of the first visible item in the list-box portion of the combo box.
InitStorage
Preallocates blocks of memory for items and strings in the listbox portion of the combo box.
InsertString
Inserts a string into the list box of a combo box.
LimitText
Limits the length of the text that the user can enter into the edit control of a combo box.
MeasureItem
Called by the framework to determine combo box dimensions when an ownerdrawn combo box is created
Paste
Inserts the data from the Clipboard into the edit control at the current cursor position. Data is inserted only if the Clipboard contains data in CF_TEXT format.
ResetContent
Removes all items from the list box and edit control of a combo box.
SelectString
Searches for a string in the list box of a combo box and, if the string is found, selects the string in the list box and copies the string to the edit control.
SetCueBanner
Sets the cue text that is displayed for a combo box control.
SetCurSel
Selects a string in the list box of a combo box.
SetDroppedWidth
Sets the minimum allowed width for the drop-down list-box portion of a combo box.
SetEditSel
Selects characters in the edit control of a combo box.
SetExtendedUI
Selects either the default user interface or the extended user interface for a combo box that has the CBS_DROPDOWN or CBS_DROPDOWNLIST style.
SetHorizontalExtent
Sets the width in pixels that the list-box portion of the combo box can be scrolled horizontally.
SetItemData
Sets the 32-bit value associated with the specified item in a combo box.
SetItemDataPtr
Sets the 32-bit pointer associated with the specified item in a combo box.
SetItemHeight
Sets the height of list items in a combo box or the height of the edit-control (or static-text) portion of a combo box.
SetLocale
Sets the locale identifier for a combo box.
SetMinVisibleItems
Sets the minimum number of visible items in the drop-down list of the current combo box.
SetTopIndex
Tells the list-box portion of the combo box to display the item with the specified index at the top.
ShowDropDown
Shows or hides the list box of a combo box that has the CBS_DROPDOWN or CBS_DROPDOWNLIST style.
Here is the list of messages mapping for Combobox control −
Let us look into an example of Radio button by creating a new MFC dialog based application.
Step 1 − Drag a Combo box and remove the Caption of Static Text control.
Step 2 − Add a control variable m_comboBoxCtrl for combobox and value variable m_strTextCtrl for Static Text control.
Step 3 − Add event handler for selection change of combo box.
Step 4 − Add the following code in OnInitDialog() to load the combo box.
for (int i = 0; i<10; i++) {
str.Format(_T("Item %d"), i);
m_comboBoxCtrl.AddString(str);
}
Step 5 − Here is the implementation of event handler.
void CMFCComboBoxDlg::OnCbnSelchangeCombo1() {
// TODO: Add your control notification handler code here
m_comboBoxCtrl.GetLBText(m_comboBoxCtrl.GetCurSel(), m_strTextCtrl);
UpdateData(FALSE);
}
Step 6 − When the above code is compiled and executed, you will see the following output.
Step 7 − When you select any item then it will be displayed on the Text Control.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2346,
"s": 2067,
"text": "A combo box consists of a list box combined with either a static control or edit control. it is represented by CComboBox class. The list-box portion of the control may be displayed at all times or may only drop down when the user selects the drop-down arrow next to the control."
},
{
"code": null,
"e": 2356,
"s": 2346,
"text": "AddString"
},
{
"code": null,
"e": 2491,
"s": 2356,
"text": "Adds a string to the end of the list in the list box of a combo box, or at the sorted position for list boxes with the CBS_SORT style."
},
{
"code": null,
"e": 2497,
"s": 2491,
"text": "Clear"
},
{
"code": null,
"e": 2566,
"s": 2497,
"text": "Deletes (clears) the current selection, if any, in the edit control."
},
{
"code": null,
"e": 2578,
"s": 2566,
"text": "CompareItem"
},
{
"code": null,
"e": 2690,
"s": 2578,
"text": "Called by the framework to determine the relative position of a new list item in a sorted ownerdrawn combo box."
},
{
"code": null,
"e": 2695,
"s": 2690,
"text": "Copy"
},
{
"code": null,
"e": 2771,
"s": 2695,
"text": "Copies the current selection, if any, onto the Clipboard in CF_TEXT format."
},
{
"code": null,
"e": 2778,
"s": 2771,
"text": "Create"
},
{
"code": null,
"e": 2841,
"s": 2778,
"text": "Creates the combo box and attaches it to the CComboBox object."
},
{
"code": null,
"e": 2845,
"s": 2841,
"text": "Cut"
},
{
"code": null,
"e": 2977,
"s": 2845,
"text": "Deletes (cuts) the current selection, if any, in the edit control and copies the deleted text onto the Clipboard in CF_TEXT format."
},
{
"code": null,
"e": 2988,
"s": 2977,
"text": "DeleteItem"
},
{
"code": null,
"e": 3071,
"s": 2988,
"text": "Called by the framework when a list item is deleted from an owner-drawn combo box."
},
{
"code": null,
"e": 3084,
"s": 3071,
"text": "DeleteString"
},
{
"code": null,
"e": 3135,
"s": 3084,
"text": "Deletes a string from the list box of a combo box."
},
{
"code": null,
"e": 3139,
"s": 3135,
"text": "Dir"
},
{
"code": null,
"e": 3197,
"s": 3139,
"text": "Adds a list of file names to the list box of a combo box."
},
{
"code": null,
"e": 3206,
"s": 3197,
"text": "DrawItem"
},
{
"code": null,
"e": 3288,
"s": 3206,
"text": "Called by the framework when a visual aspect of an owner-drawn combo box changes."
},
{
"code": null,
"e": 3299,
"s": 3288,
"text": "FindString"
},
{
"code": null,
"e": 3389,
"s": 3299,
"text": "Finds the first string that contains the specified prefix in the list box of a combo box."
},
{
"code": null,
"e": 3405,
"s": 3389,
"text": "FindStringExact"
},
{
"code": null,
"e": 3489,
"s": 3405,
"text": "Finds the first list-box string (in a combo box) that matches the specified string."
},
{
"code": null,
"e": 3505,
"s": 3489,
"text": "GetComboBoxInfo"
},
{
"code": null,
"e": 3555,
"s": 3505,
"text": "Retrieves information about the CComboBox object."
},
{
"code": null,
"e": 3564,
"s": 3555,
"text": "GetCount"
},
{
"code": null,
"e": 3626,
"s": 3564,
"text": "Retrieves the number of items in the list box of a combo box."
},
{
"code": null,
"e": 3639,
"s": 3626,
"text": "GetCueBanner"
},
{
"code": null,
"e": 3700,
"s": 3639,
"text": "Gets the cue text that is displayed for a combo box control."
},
{
"code": null,
"e": 3710,
"s": 3700,
"text": "GetCurSel"
},
{
"code": null,
"e": 3802,
"s": 3710,
"text": "Retrieves the index of the currently selected item, if any, in the list box of a combo box."
},
{
"code": null,
"e": 3824,
"s": 3802,
"text": "GetDroppedControlRect"
},
{
"code": null,
"e": 3922,
"s": 3824,
"text": "Retrieves the screen coordinates of the visible (dropped down) list box of a drop-down combo box."
},
{
"code": null,
"e": 3938,
"s": 3922,
"text": "GetDroppedState"
},
{
"code": null,
"e": 4022,
"s": 3938,
"text": "Determines whether the list box of a drop-down combo box is visible (dropped down)."
},
{
"code": null,
"e": 4038,
"s": 4022,
"text": "GetDroppedWidth"
},
{
"code": null,
"e": 4125,
"s": 4038,
"text": "Retrieves the minimum allowed width for the drop-down list-box portion of a combo box."
},
{
"code": null,
"e": 4136,
"s": 4125,
"text": "GetEditSel"
},
{
"code": null,
"e": 4246,
"s": 4136,
"text": "Gets the starting and ending character positions of the current selection in the edit control of a combo box."
},
{
"code": null,
"e": 4260,
"s": 4246,
"text": "GetExtendedUI"
},
{
"code": null,
"e": 4353,
"s": 4260,
"text": "Determines whether a combo box has the default user interface or the extended user interface"
},
{
"code": null,
"e": 4373,
"s": 4353,
"text": "GetHorizontalExtent"
},
{
"code": null,
"e": 4474,
"s": 4373,
"text": "Returns the width in pixels that the list-box portion of the combo box can be scrolled horizontally."
},
{
"code": null,
"e": 4486,
"s": 4474,
"text": "GetItemData"
},
{
"code": null,
"e": 4579,
"s": 4486,
"text": "Retrieves the applicationsupplied 32-bit value associated with the specified combo-box item."
},
{
"code": null,
"e": 4594,
"s": 4579,
"text": "GetItemDataPtr"
},
{
"code": null,
"e": 4697,
"s": 4594,
"text": "Retrieves the applicationsupplied 32-bit pointer that is associated with the specified combo-box item."
},
{
"code": null,
"e": 4711,
"s": 4697,
"text": "GetItemHeight"
},
{
"code": null,
"e": 4762,
"s": 4711,
"text": "Retrieves the height of list items in a combo box."
},
{
"code": null,
"e": 4772,
"s": 4762,
"text": "GetLBText"
},
{
"code": null,
"e": 4820,
"s": 4772,
"text": "Gets a string from the list box of a combo box."
},
{
"code": null,
"e": 4833,
"s": 4820,
"text": "GetLBTextLen"
},
{
"code": null,
"e": 4893,
"s": 4833,
"text": "Gets the length of a string in the list box of a combo box."
},
{
"code": null,
"e": 4903,
"s": 4893,
"text": "GetLocale"
},
{
"code": null,
"e": 4952,
"s": 4903,
"text": "Retrieves the locale identifier for a combo box."
},
{
"code": null,
"e": 4966,
"s": 4952,
"text": "GetMinVisible"
},
{
"code": null,
"e": 5055,
"s": 4966,
"text": "Gets the minimum number of visible items in the drop-down list of the current combo box."
},
{
"code": null,
"e": 5067,
"s": 5055,
"text": "GetTopIndex"
},
{
"code": null,
"e": 5153,
"s": 5067,
"text": "Returns the index of the first visible item in the list-box portion of the combo box."
},
{
"code": null,
"e": 5165,
"s": 5153,
"text": "InitStorage"
},
{
"code": null,
"e": 5258,
"s": 5165,
"text": "Preallocates blocks of memory for items and strings in the listbox portion of the combo box."
},
{
"code": null,
"e": 5271,
"s": 5258,
"text": "InsertString"
},
{
"code": null,
"e": 5322,
"s": 5271,
"text": "Inserts a string into the list box of a combo box."
},
{
"code": null,
"e": 5332,
"s": 5322,
"text": "LimitText"
},
{
"code": null,
"e": 5424,
"s": 5332,
"text": "Limits the length of the text that the user can enter into the edit control of a combo box."
},
{
"code": null,
"e": 5436,
"s": 5424,
"text": "MeasureItem"
},
{
"code": null,
"e": 5534,
"s": 5436,
"text": "Called by the framework to determine combo box dimensions when an ownerdrawn combo box is created"
},
{
"code": null,
"e": 5540,
"s": 5534,
"text": "Paste"
},
{
"code": null,
"e": 5702,
"s": 5540,
"text": "Inserts the data from the Clipboard into the edit control at the current cursor position. Data is inserted only if the Clipboard contains data in CF_TEXT format."
},
{
"code": null,
"e": 5715,
"s": 5702,
"text": "ResetContent"
},
{
"code": null,
"e": 5784,
"s": 5715,
"text": "Removes all items from the list box and edit control of a combo box."
},
{
"code": null,
"e": 5797,
"s": 5784,
"text": "SelectString"
},
{
"code": null,
"e": 5957,
"s": 5797,
"text": "Searches for a string in the list box of a combo box and, if the string is found, selects the string in the list box and copies the string to the edit control."
},
{
"code": null,
"e": 5970,
"s": 5957,
"text": "SetCueBanner"
},
{
"code": null,
"e": 6031,
"s": 5970,
"text": "Sets the cue text that is displayed for a combo box control."
},
{
"code": null,
"e": 6041,
"s": 6031,
"text": "SetCurSel"
},
{
"code": null,
"e": 6090,
"s": 6041,
"text": "Selects a string in the list box of a combo box."
},
{
"code": null,
"e": 6106,
"s": 6090,
"text": "SetDroppedWidth"
},
{
"code": null,
"e": 6188,
"s": 6106,
"text": "Sets the minimum allowed width for the drop-down list-box portion of a combo box."
},
{
"code": null,
"e": 6199,
"s": 6188,
"text": "SetEditSel"
},
{
"code": null,
"e": 6254,
"s": 6199,
"text": "Selects characters in the edit control of a combo box."
},
{
"code": null,
"e": 6268,
"s": 6254,
"text": "SetExtendedUI"
},
{
"code": null,
"e": 6410,
"s": 6268,
"text": "Selects either the default user interface or the extended user interface for a combo box that has the CBS_DROPDOWN or CBS_DROPDOWNLIST style."
},
{
"code": null,
"e": 6430,
"s": 6410,
"text": "SetHorizontalExtent"
},
{
"code": null,
"e": 6528,
"s": 6430,
"text": "Sets the width in pixels that the list-box portion of the combo box can be scrolled horizontally."
},
{
"code": null,
"e": 6540,
"s": 6528,
"text": "SetItemData"
},
{
"code": null,
"e": 6613,
"s": 6540,
"text": "Sets the 32-bit value associated with the specified item in a combo box."
},
{
"code": null,
"e": 6628,
"s": 6613,
"text": "SetItemDataPtr"
},
{
"code": null,
"e": 6703,
"s": 6628,
"text": "Sets the 32-bit pointer associated with the specified item in a combo box."
},
{
"code": null,
"e": 6717,
"s": 6703,
"text": "SetItemHeight"
},
{
"code": null,
"e": 6837,
"s": 6717,
"text": "Sets the height of list items in a combo box or the height of the edit-control (or static-text) portion of a combo box."
},
{
"code": null,
"e": 6847,
"s": 6837,
"text": "SetLocale"
},
{
"code": null,
"e": 6891,
"s": 6847,
"text": "Sets the locale identifier for a combo box."
},
{
"code": null,
"e": 6910,
"s": 6891,
"text": "SetMinVisibleItems"
},
{
"code": null,
"e": 6999,
"s": 6910,
"text": "Sets the minimum number of visible items in the drop-down list of the current combo box."
},
{
"code": null,
"e": 7011,
"s": 6999,
"text": "SetTopIndex"
},
{
"code": null,
"e": 7112,
"s": 7011,
"text": "Tells the list-box portion of the combo box to display the item with the specified index at the top."
},
{
"code": null,
"e": 7125,
"s": 7112,
"text": "ShowDropDown"
},
{
"code": null,
"e": 7221,
"s": 7125,
"text": "Shows or hides the list box of a combo box that has the CBS_DROPDOWN or CBS_DROPDOWNLIST style."
},
{
"code": null,
"e": 7281,
"s": 7221,
"text": "Here is the list of messages mapping for Combobox control −"
},
{
"code": null,
"e": 7373,
"s": 7281,
"text": "Let us look into an example of Radio button by creating a new MFC dialog based application."
},
{
"code": null,
"e": 7446,
"s": 7373,
"text": "Step 1 − Drag a Combo box and remove the Caption of Static Text control."
},
{
"code": null,
"e": 7564,
"s": 7446,
"text": "Step 2 − Add a control variable m_comboBoxCtrl for combobox and value variable m_strTextCtrl for Static Text control."
},
{
"code": null,
"e": 7626,
"s": 7564,
"text": "Step 3 − Add event handler for selection change of combo box."
},
{
"code": null,
"e": 7699,
"s": 7626,
"text": "Step 4 − Add the following code in OnInitDialog() to load the combo box."
},
{
"code": null,
"e": 7797,
"s": 7699,
"text": "for (int i = 0; i<10; i++) {\n str.Format(_T(\"Item %d\"), i);\n m_comboBoxCtrl.AddString(str);\n}"
},
{
"code": null,
"e": 7851,
"s": 7797,
"text": "Step 5 − Here is the implementation of event handler."
},
{
"code": null,
"e": 8058,
"s": 7851,
"text": "void CMFCComboBoxDlg::OnCbnSelchangeCombo1() {\n \n // TODO: Add your control notification handler code here\n m_comboBoxCtrl.GetLBText(m_comboBoxCtrl.GetCurSel(), m_strTextCtrl);\n UpdateData(FALSE);\n}"
},
{
"code": null,
"e": 8148,
"s": 8058,
"text": "Step 6 − When the above code is compiled and executed, you will see the following output."
},
{
"code": null,
"e": 8229,
"s": 8148,
"text": "Step 7 − When you select any item then it will be displayed on the Text Control."
},
{
"code": null,
"e": 8236,
"s": 8229,
"text": " Print"
},
{
"code": null,
"e": 8247,
"s": 8236,
"text": " Add Notes"
}
] |
How to perform scrolling action on page in Selenium? | We can perform the following actions with respect to scrolling in Selenium −
The scrolling down to a specific pixel.
JavascriptExecutor j = (JavascriptExecutor) driver;
// scroll down by 1500 pixel with coordinates 0 and 1500 in x, y axes
j.executeScript("window.scrollBy(0,1500)");
The scrolling down to the bottom of the page.
JavascriptExecutor j = (JavascriptExecutor) driver;
// scroll down the bottom of page
js.executeScript("window.scrollTo(0, document.body.scrollHeight)");
For vertical scroll down till the element is visible.
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;
import org.openqa.selenium.JavascriptExecutor;
public class ScrollDownVisible {
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);
JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement terms = driver.findElement(By.linkText("Terms of use”));
// scroll down the web element for viewing
js.executeScript("arguments[0].scrollIntoView();",terms);
driver.close();
}
}
For horizontal scroll on page.
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;
import org.openqa.selenium.JavascriptExecutor;
public class HScrollDown {
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);
JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement meets = driver.findElement(By.linkText("NetMeeting”));
// scroll down the web element for viewing
js.executeScript("arguments[0].scrollIntoView();", meets);
driver.close();
}
} | [
{
"code": null,
"e": 1139,
"s": 1062,
"text": "We can perform the following actions with respect to scrolling in Selenium −"
},
{
"code": null,
"e": 1179,
"s": 1139,
"text": "The scrolling down to a specific pixel."
},
{
"code": null,
"e": 1345,
"s": 1179,
"text": "JavascriptExecutor j = (JavascriptExecutor) driver;\n// scroll down by 1500 pixel with coordinates 0 and 1500 in x, y axes\nj.executeScript(\"window.scrollBy(0,1500)\");"
},
{
"code": null,
"e": 1391,
"s": 1345,
"text": "The scrolling down to the bottom of the page."
},
{
"code": null,
"e": 1545,
"s": 1391,
"text": "JavascriptExecutor j = (JavascriptExecutor) driver;\n// scroll down the bottom of page\njs.executeScript(\"window.scrollTo(0, document.body.scrollHeight)\");"
},
{
"code": null,
"e": 1599,
"s": 1545,
"text": "For vertical scroll down till the element is visible."
},
{
"code": null,
"e": 2535,
"s": 1599,
"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;\nimport org.openqa.selenium.JavascriptExecutor;\npublic class ScrollDownVisible {\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 JavascriptExecutor js = (JavascriptExecutor) driver;\n WebElement terms = driver.findElement(By.linkText(\"Terms of use”));\n // scroll down the web element for viewing\n js.executeScript(\"arguments[0].scrollIntoView();\",terms);\n driver.close();\n }\n}"
},
{
"code": null,
"e": 2566,
"s": 2535,
"text": "For horizontal scroll on page."
},
{
"code": null,
"e": 3495,
"s": 2566,
"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;\nimport org.openqa.selenium.JavascriptExecutor;\npublic class HScrollDown {\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 JavascriptExecutor js = (JavascriptExecutor) driver;\n WebElement meets = driver.findElement(By.linkText(\"NetMeeting”));\n // scroll down the web element for viewing\n js.executeScript(\"arguments[0].scrollIntoView();\", meets);\n driver.close();\n }\n}"
}
] |
Alternate range slicing in list (Python) | Slicing is a very common technique for analyzing data from a given list in Python. But for our analysis sometimes we need to create slices of a list for a specific range of values. For example we need to print 4 elements by skipping every 4 elements from the list. In this article we will see this concept of range slicing in Python.
We create a for loop to go through the entire length of the list but choose only the elements that satisfy the divisibility test. In the divisibility test we check for the value of the remainder for the kth element in the list. If the remainder is greater than or equal to the range value, we accept the element otherwise we do not.
Live Demo
range_slicing = [6,9,11,15,20,24,29,36,39,43,47,52,56,70,73,79]
print("The given list: ",range_slicing)
# Range Value
s = 4
# Using range and len
result = [range_slicing[k] for k in range(len(range_slicing))
if k % (s * 2) >= s]
print("\nThe list after range slicing: ",result)
Running the above code gives us the following result:
The given list: [6, 9, 11, 15, 20, 24, 29, 36, 39, 43, 47, 52, 56, 70, 73, 79]
The list after range slicing: [20, 24, 29, 36, 56, 70, 73, 79]
We apply the similar logic as in previous approach but instead of using range() and len() we simply apply enumerate(). Please note the last element in the list appears in the result because it satisfies the divisibility condition.
Live Demo
range_slicing = [6,9,11,15,20,24,29,36,39,43,47,52,56,70,73,79]
print("The given list: ",range_slicing)
# Range value
s2= 5
# Using Enumerate
result_2 = [val for m, val in enumerate(range_slicing)
if m % (s2 * 2) >= s2]
print("\nThe list after range slicing: ",result_2)
Running the above code gives us the following result:
The given list: [6, 9, 11, 15, 20, 24, 29, 36, 39, 43, 47, 52, 56, 70, 73, 79]
The list after range slicing: [24, 29, 36, 39, 43, 79] | [
{
"code": null,
"e": 1396,
"s": 1062,
"text": "Slicing is a very common technique for analyzing data from a given list in Python. But for our analysis sometimes we need to create slices of a list for a specific range of values. For example we need to print 4 elements by skipping every 4 elements from the list. In this article we will see this concept of range slicing in Python."
},
{
"code": null,
"e": 1729,
"s": 1396,
"text": "We create a for loop to go through the entire length of the list but choose only the elements that satisfy the divisibility test. In the divisibility test we check for the value of the remainder for the kth element in the list. If the remainder is greater than or equal to the range value, we accept the element otherwise we do not."
},
{
"code": null,
"e": 1740,
"s": 1729,
"text": " Live Demo"
},
{
"code": null,
"e": 2020,
"s": 1740,
"text": "range_slicing = [6,9,11,15,20,24,29,36,39,43,47,52,56,70,73,79]\nprint(\"The given list: \",range_slicing)\n\n# Range Value\ns = 4\n# Using range and len\nresult = [range_slicing[k] for k in range(len(range_slicing))\nif k % (s * 2) >= s]\n\nprint(\"\\nThe list after range slicing: \",result)"
},
{
"code": null,
"e": 2074,
"s": 2020,
"text": "Running the above code gives us the following result:"
},
{
"code": null,
"e": 2216,
"s": 2074,
"text": "The given list: [6, 9, 11, 15, 20, 24, 29, 36, 39, 43, 47, 52, 56, 70, 73, 79]\nThe list after range slicing: [20, 24, 29, 36, 56, 70, 73, 79]"
},
{
"code": null,
"e": 2447,
"s": 2216,
"text": "We apply the similar logic as in previous approach but instead of using range() and len() we simply apply enumerate(). Please note the last element in the list appears in the result because it satisfies the divisibility condition."
},
{
"code": null,
"e": 2458,
"s": 2447,
"text": " Live Demo"
},
{
"code": null,
"e": 2731,
"s": 2458,
"text": "range_slicing = [6,9,11,15,20,24,29,36,39,43,47,52,56,70,73,79]\nprint(\"The given list: \",range_slicing)\n# Range value\ns2= 5\n\n# Using Enumerate\nresult_2 = [val for m, val in enumerate(range_slicing)\nif m % (s2 * 2) >= s2]\n\nprint(\"\\nThe list after range slicing: \",result_2)"
},
{
"code": null,
"e": 2785,
"s": 2731,
"text": "Running the above code gives us the following result:"
},
{
"code": null,
"e": 2919,
"s": 2785,
"text": "The given list: [6, 9, 11, 15, 20, 24, 29, 36, 39, 43, 47, 52, 56, 70, 73, 79]\nThe list after range slicing: [24, 29, 36, 39, 43, 79]"
}
] |
codecs.encode() in Python - GeeksforGeeks | 26 Mar, 2020
With the help of codecs.encode() method, we can encode the string into the binary form .
Syntax : codecs.encode(string)
Return : Return the encoded string.
Example #1 :In this example we can see that by using codecs.encode() method, we are able to get the encoded string which can be in binary form by using this method.
# import codecsimport codecs s = 'GeeksForGeeks'# Using codecs.encode() methodgfg = codecs.encode(s) print(gfg)
Output :
b’GeeksForGeeks’
Example #2 :
# import codecsimport codecs s = 'I love python.'# Using codecs.encode() methodgfg = codecs.encode(s) print(gfg)
Output :
b’I love python.’
Python codecs-module
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python program to check whether a number is Prime or not
Python | Convert a list to dictionary | [
{
"code": null,
"e": 23811,
"s": 23783,
"text": "\n26 Mar, 2020"
},
{
"code": null,
"e": 23900,
"s": 23811,
"text": "With the help of codecs.encode() method, we can encode the string into the binary form ."
},
{
"code": null,
"e": 23931,
"s": 23900,
"text": "Syntax : codecs.encode(string)"
},
{
"code": null,
"e": 23967,
"s": 23931,
"text": "Return : Return the encoded string."
},
{
"code": null,
"e": 24132,
"s": 23967,
"text": "Example #1 :In this example we can see that by using codecs.encode() method, we are able to get the encoded string which can be in binary form by using this method."
},
{
"code": "# import codecsimport codecs s = 'GeeksForGeeks'# Using codecs.encode() methodgfg = codecs.encode(s) print(gfg)",
"e": 24246,
"s": 24132,
"text": null
},
{
"code": null,
"e": 24255,
"s": 24246,
"text": "Output :"
},
{
"code": null,
"e": 24272,
"s": 24255,
"text": "b’GeeksForGeeks’"
},
{
"code": null,
"e": 24285,
"s": 24272,
"text": "Example #2 :"
},
{
"code": "# import codecsimport codecs s = 'I love python.'# Using codecs.encode() methodgfg = codecs.encode(s) print(gfg)",
"e": 24400,
"s": 24285,
"text": null
},
{
"code": null,
"e": 24409,
"s": 24400,
"text": "Output :"
},
{
"code": null,
"e": 24427,
"s": 24409,
"text": "b’I love python.’"
},
{
"code": null,
"e": 24448,
"s": 24427,
"text": "Python codecs-module"
},
{
"code": null,
"e": 24455,
"s": 24448,
"text": "Python"
},
{
"code": null,
"e": 24471,
"s": 24455,
"text": "Python Programs"
},
{
"code": null,
"e": 24569,
"s": 24471,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 24578,
"s": 24569,
"text": "Comments"
},
{
"code": null,
"e": 24591,
"s": 24578,
"text": "Old Comments"
},
{
"code": null,
"e": 24626,
"s": 24591,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 24648,
"s": 24626,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 24680,
"s": 24648,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 24722,
"s": 24680,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 24748,
"s": 24722,
"text": "Python String | replace()"
},
{
"code": null,
"e": 24770,
"s": 24748,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 24809,
"s": 24770,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 24855,
"s": 24809,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 24912,
"s": 24855,
"text": "Python program to check whether a number is Prime or not"
}
] |
Angular ng Bootstrap Dropdown 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 Dropdown in angular ng bootstrap. Dropdown is used to make a group of objects that will come out by clicking on it.
Installation syntax:
ng add @ng-bootstrap/ng-bootstrap
Approach:
First, install the angular ng bootstrap using the above-mentioned command.
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 dropdown component.
Serve the app using ng serve.
Example 1: In this example, we are using basic ngbDropdown.
app.component.html
<div class="col"> <br/> <div ngbDropdown> <button class="btn btn-warning" id="gfg" ngbDropdownToggle>Click Here!</button> <div ngbDropdownMenu="gfg"> <button ngbDropdownItem>GeeksforGeeks</button> <button ngbDropdownItem>Angular10</button> <button ngbDropdownItem>ng bootstrap</button> </div> </div></div>
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 { }
Output:
Example 2: In this example, we are using ngbDropdown with placement top-right.
app.component.html
<div class="col"> <br/><br/><br/><br/> <div ngbDropdown placement="top-right"> <button class="btn btn-warning" id="gfg" ngbDropdownToggle>Click Here!</button> <div ngbDropdownMenu="gfg"> <button ngbDropdownItem>GeeksforGeeks</button> <button ngbDropdownItem>Angular10</button> <button ngbDropdownItem>ng bootstrap</button> </div> </div></div>
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
.col{ margin: 50px;}
Output:
Reference: https://ng-bootstrap.github.io/#/components/dropdown/examples
Angular-ng-bootstrap
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Angular Libraries For Web Developers
How to make a Bootstrap Modal Popup in Angular 9/8 ?
Angular PrimeNG Dropdown Component
Angular 10 (blur) Event
How to create module with Routing in Angular 9 ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills | [
{
"code": null,
"e": 25109,
"s": 25081,
"text": "\n06 Jul, 2021"
},
{
"code": null,
"e": 25293,
"s": 25109,
"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": 25448,
"s": 25293,
"text": "In this article we will see how to use Dropdown in angular ng bootstrap. Dropdown is used to make a group of objects that will come out by clicking on it."
},
{
"code": null,
"e": 25469,
"s": 25448,
"text": "Installation syntax:"
},
{
"code": null,
"e": 25503,
"s": 25469,
"text": "ng add @ng-bootstrap/ng-bootstrap"
},
{
"code": null,
"e": 25513,
"s": 25503,
"text": "Approach:"
},
{
"code": null,
"e": 25588,
"s": 25513,
"text": "First, install the angular ng bootstrap using the above-mentioned command."
},
{
"code": null,
"e": 25710,
"s": 25588,
"text": "Import ng bootstrap module in module.tsimport { NgbModule } from '@ng-bootstrap/ng-bootstrap';\n\nimports: [\n NgbModule\n]\n"
},
{
"code": null,
"e": 25793,
"s": 25710,
"text": "import { NgbModule } from '@ng-bootstrap/ng-bootstrap';\n\nimports: [\n NgbModule\n]\n"
},
{
"code": null,
"e": 25843,
"s": 25793,
"text": "In app.component.html, make a dropdown component."
},
{
"code": null,
"e": 25873,
"s": 25843,
"text": "Serve the app using ng serve."
},
{
"code": null,
"e": 25935,
"s": 25875,
"text": "Example 1: In this example, we are using basic ngbDropdown."
},
{
"code": null,
"e": 25954,
"s": 25935,
"text": "app.component.html"
},
{
"code": "<div class=\"col\"> <br/> <div ngbDropdown> <button class=\"btn btn-warning\" id=\"gfg\" ngbDropdownToggle>Click Here!</button> <div ngbDropdownMenu=\"gfg\"> <button ngbDropdownItem>GeeksforGeeks</button> <button ngbDropdownItem>Angular10</button> <button ngbDropdownItem>ng bootstrap</button> </div> </div></div>",
"e": 26299,
"s": 25954,
"text": null
},
{
"code": null,
"e": 26313,
"s": 26299,
"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": 26919,
"s": 26313,
"text": null
},
{
"code": null,
"e": 26927,
"s": 26919,
"text": "Output:"
},
{
"code": null,
"e": 27006,
"s": 26927,
"text": "Example 2: In this example, we are using ngbDropdown with placement top-right."
},
{
"code": null,
"e": 27025,
"s": 27006,
"text": "app.component.html"
},
{
"code": "<div class=\"col\"> <br/><br/><br/><br/> <div ngbDropdown placement=\"top-right\"> <button class=\"btn btn-warning\" id=\"gfg\" ngbDropdownToggle>Click Here!</button> <div ngbDropdownMenu=\"gfg\"> <button ngbDropdownItem>GeeksforGeeks</button> <button ngbDropdownItem>Angular10</button> <button ngbDropdownItem>ng bootstrap</button> </div> </div></div>",
"e": 27410,
"s": 27025,
"text": null
},
{
"code": null,
"e": 27424,
"s": 27410,
"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": 28030,
"s": 27424,
"text": null
},
{
"code": null,
"e": 28048,
"s": 28030,
"text": "app.component.css"
},
{
"code": ".col{ margin: 50px;}",
"e": 28072,
"s": 28048,
"text": null
},
{
"code": null,
"e": 28080,
"s": 28072,
"text": "Output:"
},
{
"code": null,
"e": 28153,
"s": 28080,
"text": "Reference: https://ng-bootstrap.github.io/#/components/dropdown/examples"
},
{
"code": null,
"e": 28174,
"s": 28153,
"text": "Angular-ng-bootstrap"
},
{
"code": null,
"e": 28184,
"s": 28174,
"text": "AngularJS"
},
{
"code": null,
"e": 28201,
"s": 28184,
"text": "Web Technologies"
},
{
"code": null,
"e": 28299,
"s": 28201,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28343,
"s": 28299,
"text": "Top 10 Angular Libraries For Web Developers"
},
{
"code": null,
"e": 28396,
"s": 28343,
"text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?"
},
{
"code": null,
"e": 28431,
"s": 28396,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 28455,
"s": 28431,
"text": "Angular 10 (blur) Event"
},
{
"code": null,
"e": 28504,
"s": 28455,
"text": "How to create module with Routing in Angular 9 ?"
},
{
"code": null,
"e": 28546,
"s": 28504,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 28579,
"s": 28546,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28622,
"s": 28579,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28672,
"s": 28622,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
How to Best Work with JSON in Python | by Julia Kho | Towards Data Science | In this article, you will learn how to read, parse, and write JSON files in Python. I will talk about how to best handle simple JSON files as well as nested JSON files. In addition, I will discuss how to access specific values in the data.
JSON (Java Script Object Notation) is a popular file format for storing and transmitting data in web applications. It is highly likely that you’ll encounter JSON files if you work with data, so you definitely want to learn how to read and write to JSON.
Here is an example of what the structure of a JSON file might look like.
The JSON structure looks very similar to Python dictionaries. Notice that the JSON is in the format of “key”: <value> pairs, where key is a string and value can be a string, number, boolean, array, object, or null. To help you visualize that, I’ve highlighted all keys in blue and all values in orange in the image below. Notice that each key/value is also separated by a comma. Go ahead and examine the image below to familiarize yourself with the format. We will discuss the nested structure of the ‘members’ key later on in this article.
Python conveniently has built in functions to help read JSON files. Below are several examples of how to parse JSON files into a Python object.
Before we get started, if you would like to follow along with the examples:
Go to this link.Right click on the page and select Save As.Save the file as a JSON file named superheroes.
Go to this link.
Right click on the page and select Save As.
Save the file as a JSON file named superheroes.
Start by importing the json library. We use the function open to read the JSON file and then the method json.load() to parse the JSON string into a Python dictionary called superHeroSquad. That’s it! You now have a Python dictionary from your JSON file. Pretty simple.
import json with open('superheroes.json') as f: superHeroSquad = json.load(f)type(superHeroSquad)# Output: dictsuperHeroSquad.keys()# Output: dict_keys(['squadName', 'homeTown', 'formed', 'secretBase', 'active', 'members'])
One thing of note is that the json library has both load() and loads() . Both do the same thing, but loads() is to create a Python object from a JSON string whereas load() is to create a Python object from a JSON file. You can think of the extra ‘s’ in loads() as “load for strings”.
Use the method read_json() if you would like to transform the JSON file to a Pandas Dataframe.
import pandas as pddf = pd.read_json(‘superheroes.json’)
Note that you are not limited to reading JSON files from your computer. You can pass the URL path to the function as well. This will save you the step of having to download the JSON file.
df1 = pd.read_json(‘https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json')
You will likely encounter JSON files that are nested. That usually makes it difficult to work with in Pandas. Nested JSON is similar to the idea of nested dictionaries in python, that is, a dictionary within a dictionary.
Let’s examine the superhero data structure again. Notice that within the ‘members’ key, there are multiple sets of key/value pairs related to the ‘members’ key. The indentation is a helpful indicator illustrating the nested structure.
Recall from earlier when we loaded our JSON file into a Pandas dataframe, our ‘members’ column looked like this. Each row contains a dictionary.
The column ‘members’ would be much more convenient to work with in Pandas if each of the keys were actually individual columns. I’ll discuss two methods in which we can parse out the data so that each key is broken out into a column.
Method 1
We can use the apply method on the ‘members’ column like this.
df[‘members’].apply(pd.Series)
The four keys within ‘members’ are now broken out to separate columns as shown below. This is much easier for performing data manipulation and transformation.
To combine the new columns with the original dataframe, we can use pd.concat .
df = pd.concat([df[‘members’].apply(pd.Series), df.drop(‘members’, axis = 1)], axis = 1)
Method 2
Pandas also has the built-in function json_normalize() that will allow you to flatten nested JSONs. This is a cleaner method to parse the nested JSON.
pd.json_normalize(superHeroSquad, record_path = [‘members’], meta = [‘squadName’, ‘homeTown’, ‘formed’, ‘secretBase’, ‘active’])
We pass in our superHeroSquad dictionary.
record_path contains the column that we want parsed out.
meta is a list of columns we want to keep for the dataframe.
One last note: you can also add in the parameter meta_prefix if you would like to add in a particular naming convention to the parsed data.
pd.json_normalize(superHeroSquad, record_path = ['members'], meta = ['squadName', 'homeTown', 'formed', 'secretBase', 'active'], meta_prefix = 'members_')
We can access data anywhere in our JSON file by chaining together the key names and/or indices. For example, let’s say we want to access the secret identity of our second superhero, Madame Uppercut. Note the location of that particular value is highlighted in purple below.
In order to access that value, we can use the following code.
superHeroSquad[‘members’][1][‘secretIdentity’]
Starting from the top of the hierarchy and working our way down, the first key that we need is ‘members’ as that is the parent node that our value resides.
Inside the ‘members’ key, we are looking for Madame Uppercut, which is the second superhero in the list. Remember that the index for the first items always start at 0, so we want to use 1 to access the second superhero.
Lastly, we are interested in the key ‘secretIdentity’.
Combining all of that together gives us this line of code below which returns the value “Jane Wilson”.
superHeroSquad[‘members’][1][‘secretIdentity’]
You might have noticed that I have highlighted two values in blue in the JSON snippet above. Go ahead and try accessing those values as individual exercises. Feel free to share your code in the comments below.
Let’s make a quick edit to the missing secret identity of our last superhero, Eternal Flame, from “Unknown” to “Will Smith” and then export our superHeroSquad dictionary back to the JSON file. We use the method json.dump() to write to the file.
#update secret identity of Eternal FlamesuperHeroSquad[‘members’][2][‘secretIdentity’] = 'Will Smith'with open('superheroes.json', 'w') as file: json.dump(superHeroSquad, file)
If you open your superheroes.json file, it should now have Will Smith as the secret identity of Eternal Flame. Similar to load() and loads() mentioned previously, the json library also has dump() and dumps() . One to store as a JSON file and one to store as a JSON string respectively.
Alternatively, if you are working with the Pandas Dataframe and would like to export to JSON, you can use the to_json() method.
df.to_json(‘superheroes.json’)
You may notice that the JSON file does not look very nice in your output file. It shows up as a single string like below.
To make it look prettier, you can use the indent parameter in your json.dump method.
with open('superheroes.json', 'w') as file: json.dump(superHeroSquad, file, indent = 4)
The output will look like the image below, which is much more readable.
If required, you may also pass in a sort_key parameter, set to True, in order to sort your keys. Notice that all keys including the nested ones are all sorted.
with open('superheroes.json', 'w') as file: json.dump(superHeroSquad, file, indent = 4, sort_keys = True)
JSON data structure is in the format of “key”: <value> pairs, where key is a string and value can be a string, number, boolean, array, object, or null.
Python has built in functions that easily imports JSON files as a Python dictionary or a Pandas dataframe.
Use pd.read_json() to load simple JSONs and pd.json_normalize() to load nested JSONs.
You can easily access values in your JSON file by chaining together the key names and/or indices.
Python objects can be exported back to JSON with pretty printing and sorting.
Thank you for reading. Let me know in the comments if you have other tips for working with JSON in Python. | [
{
"code": null,
"e": 412,
"s": 172,
"text": "In this article, you will learn how to read, parse, and write JSON files in Python. I will talk about how to best handle simple JSON files as well as nested JSON files. In addition, I will discuss how to access specific values in the data."
},
{
"code": null,
"e": 666,
"s": 412,
"text": "JSON (Java Script Object Notation) is a popular file format for storing and transmitting data in web applications. It is highly likely that you’ll encounter JSON files if you work with data, so you definitely want to learn how to read and write to JSON."
},
{
"code": null,
"e": 739,
"s": 666,
"text": "Here is an example of what the structure of a JSON file might look like."
},
{
"code": null,
"e": 1280,
"s": 739,
"text": "The JSON structure looks very similar to Python dictionaries. Notice that the JSON is in the format of “key”: <value> pairs, where key is a string and value can be a string, number, boolean, array, object, or null. To help you visualize that, I’ve highlighted all keys in blue and all values in orange in the image below. Notice that each key/value is also separated by a comma. Go ahead and examine the image below to familiarize yourself with the format. We will discuss the nested structure of the ‘members’ key later on in this article."
},
{
"code": null,
"e": 1424,
"s": 1280,
"text": "Python conveniently has built in functions to help read JSON files. Below are several examples of how to parse JSON files into a Python object."
},
{
"code": null,
"e": 1500,
"s": 1424,
"text": "Before we get started, if you would like to follow along with the examples:"
},
{
"code": null,
"e": 1607,
"s": 1500,
"text": "Go to this link.Right click on the page and select Save As.Save the file as a JSON file named superheroes."
},
{
"code": null,
"e": 1624,
"s": 1607,
"text": "Go to this link."
},
{
"code": null,
"e": 1668,
"s": 1624,
"text": "Right click on the page and select Save As."
},
{
"code": null,
"e": 1716,
"s": 1668,
"text": "Save the file as a JSON file named superheroes."
},
{
"code": null,
"e": 1985,
"s": 1716,
"text": "Start by importing the json library. We use the function open to read the JSON file and then the method json.load() to parse the JSON string into a Python dictionary called superHeroSquad. That’s it! You now have a Python dictionary from your JSON file. Pretty simple."
},
{
"code": null,
"e": 2212,
"s": 1985,
"text": "import json with open('superheroes.json') as f: superHeroSquad = json.load(f)type(superHeroSquad)# Output: dictsuperHeroSquad.keys()# Output: dict_keys(['squadName', 'homeTown', 'formed', 'secretBase', 'active', 'members'])"
},
{
"code": null,
"e": 2496,
"s": 2212,
"text": "One thing of note is that the json library has both load() and loads() . Both do the same thing, but loads() is to create a Python object from a JSON string whereas load() is to create a Python object from a JSON file. You can think of the extra ‘s’ in loads() as “load for strings”."
},
{
"code": null,
"e": 2591,
"s": 2496,
"text": "Use the method read_json() if you would like to transform the JSON file to a Pandas Dataframe."
},
{
"code": null,
"e": 2648,
"s": 2591,
"text": "import pandas as pddf = pd.read_json(‘superheroes.json’)"
},
{
"code": null,
"e": 2836,
"s": 2648,
"text": "Note that you are not limited to reading JSON files from your computer. You can pass the URL path to the function as well. This will save you the step of having to download the JSON file."
},
{
"code": null,
"e": 2932,
"s": 2836,
"text": "df1 = pd.read_json(‘https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json')"
},
{
"code": null,
"e": 3154,
"s": 2932,
"text": "You will likely encounter JSON files that are nested. That usually makes it difficult to work with in Pandas. Nested JSON is similar to the idea of nested dictionaries in python, that is, a dictionary within a dictionary."
},
{
"code": null,
"e": 3389,
"s": 3154,
"text": "Let’s examine the superhero data structure again. Notice that within the ‘members’ key, there are multiple sets of key/value pairs related to the ‘members’ key. The indentation is a helpful indicator illustrating the nested structure."
},
{
"code": null,
"e": 3534,
"s": 3389,
"text": "Recall from earlier when we loaded our JSON file into a Pandas dataframe, our ‘members’ column looked like this. Each row contains a dictionary."
},
{
"code": null,
"e": 3768,
"s": 3534,
"text": "The column ‘members’ would be much more convenient to work with in Pandas if each of the keys were actually individual columns. I’ll discuss two methods in which we can parse out the data so that each key is broken out into a column."
},
{
"code": null,
"e": 3777,
"s": 3768,
"text": "Method 1"
},
{
"code": null,
"e": 3840,
"s": 3777,
"text": "We can use the apply method on the ‘members’ column like this."
},
{
"code": null,
"e": 3871,
"s": 3840,
"text": "df[‘members’].apply(pd.Series)"
},
{
"code": null,
"e": 4030,
"s": 3871,
"text": "The four keys within ‘members’ are now broken out to separate columns as shown below. This is much easier for performing data manipulation and transformation."
},
{
"code": null,
"e": 4109,
"s": 4030,
"text": "To combine the new columns with the original dataframe, we can use pd.concat ."
},
{
"code": null,
"e": 4198,
"s": 4109,
"text": "df = pd.concat([df[‘members’].apply(pd.Series), df.drop(‘members’, axis = 1)], axis = 1)"
},
{
"code": null,
"e": 4207,
"s": 4198,
"text": "Method 2"
},
{
"code": null,
"e": 4358,
"s": 4207,
"text": "Pandas also has the built-in function json_normalize() that will allow you to flatten nested JSONs. This is a cleaner method to parse the nested JSON."
},
{
"code": null,
"e": 4487,
"s": 4358,
"text": "pd.json_normalize(superHeroSquad, record_path = [‘members’], meta = [‘squadName’, ‘homeTown’, ‘formed’, ‘secretBase’, ‘active’])"
},
{
"code": null,
"e": 4529,
"s": 4487,
"text": "We pass in our superHeroSquad dictionary."
},
{
"code": null,
"e": 4586,
"s": 4529,
"text": "record_path contains the column that we want parsed out."
},
{
"code": null,
"e": 4647,
"s": 4586,
"text": "meta is a list of columns we want to keep for the dataframe."
},
{
"code": null,
"e": 4787,
"s": 4647,
"text": "One last note: you can also add in the parameter meta_prefix if you would like to add in a particular naming convention to the parsed data."
},
{
"code": null,
"e": 4942,
"s": 4787,
"text": "pd.json_normalize(superHeroSquad, record_path = ['members'], meta = ['squadName', 'homeTown', 'formed', 'secretBase', 'active'], meta_prefix = 'members_')"
},
{
"code": null,
"e": 5216,
"s": 4942,
"text": "We can access data anywhere in our JSON file by chaining together the key names and/or indices. For example, let’s say we want to access the secret identity of our second superhero, Madame Uppercut. Note the location of that particular value is highlighted in purple below."
},
{
"code": null,
"e": 5278,
"s": 5216,
"text": "In order to access that value, we can use the following code."
},
{
"code": null,
"e": 5325,
"s": 5278,
"text": "superHeroSquad[‘members’][1][‘secretIdentity’]"
},
{
"code": null,
"e": 5481,
"s": 5325,
"text": "Starting from the top of the hierarchy and working our way down, the first key that we need is ‘members’ as that is the parent node that our value resides."
},
{
"code": null,
"e": 5701,
"s": 5481,
"text": "Inside the ‘members’ key, we are looking for Madame Uppercut, which is the second superhero in the list. Remember that the index for the first items always start at 0, so we want to use 1 to access the second superhero."
},
{
"code": null,
"e": 5756,
"s": 5701,
"text": "Lastly, we are interested in the key ‘secretIdentity’."
},
{
"code": null,
"e": 5859,
"s": 5756,
"text": "Combining all of that together gives us this line of code below which returns the value “Jane Wilson”."
},
{
"code": null,
"e": 5906,
"s": 5859,
"text": "superHeroSquad[‘members’][1][‘secretIdentity’]"
},
{
"code": null,
"e": 6116,
"s": 5906,
"text": "You might have noticed that I have highlighted two values in blue in the JSON snippet above. Go ahead and try accessing those values as individual exercises. Feel free to share your code in the comments below."
},
{
"code": null,
"e": 6361,
"s": 6116,
"text": "Let’s make a quick edit to the missing secret identity of our last superhero, Eternal Flame, from “Unknown” to “Will Smith” and then export our superHeroSquad dictionary back to the JSON file. We use the method json.dump() to write to the file."
},
{
"code": null,
"e": 6541,
"s": 6361,
"text": "#update secret identity of Eternal FlamesuperHeroSquad[‘members’][2][‘secretIdentity’] = 'Will Smith'with open('superheroes.json', 'w') as file: json.dump(superHeroSquad, file)"
},
{
"code": null,
"e": 6827,
"s": 6541,
"text": "If you open your superheroes.json file, it should now have Will Smith as the secret identity of Eternal Flame. Similar to load() and loads() mentioned previously, the json library also has dump() and dumps() . One to store as a JSON file and one to store as a JSON string respectively."
},
{
"code": null,
"e": 6955,
"s": 6827,
"text": "Alternatively, if you are working with the Pandas Dataframe and would like to export to JSON, you can use the to_json() method."
},
{
"code": null,
"e": 6986,
"s": 6955,
"text": "df.to_json(‘superheroes.json’)"
},
{
"code": null,
"e": 7108,
"s": 6986,
"text": "You may notice that the JSON file does not look very nice in your output file. It shows up as a single string like below."
},
{
"code": null,
"e": 7193,
"s": 7108,
"text": "To make it look prettier, you can use the indent parameter in your json.dump method."
},
{
"code": null,
"e": 7284,
"s": 7193,
"text": "with open('superheroes.json', 'w') as file: json.dump(superHeroSquad, file, indent = 4)"
},
{
"code": null,
"e": 7356,
"s": 7284,
"text": "The output will look like the image below, which is much more readable."
},
{
"code": null,
"e": 7516,
"s": 7356,
"text": "If required, you may also pass in a sort_key parameter, set to True, in order to sort your keys. Notice that all keys including the nested ones are all sorted."
},
{
"code": null,
"e": 7625,
"s": 7516,
"text": "with open('superheroes.json', 'w') as file: json.dump(superHeroSquad, file, indent = 4, sort_keys = True)"
},
{
"code": null,
"e": 7777,
"s": 7625,
"text": "JSON data structure is in the format of “key”: <value> pairs, where key is a string and value can be a string, number, boolean, array, object, or null."
},
{
"code": null,
"e": 7884,
"s": 7777,
"text": "Python has built in functions that easily imports JSON files as a Python dictionary or a Pandas dataframe."
},
{
"code": null,
"e": 7970,
"s": 7884,
"text": "Use pd.read_json() to load simple JSONs and pd.json_normalize() to load nested JSONs."
},
{
"code": null,
"e": 8068,
"s": 7970,
"text": "You can easily access values in your JSON file by chaining together the key names and/or indices."
},
{
"code": null,
"e": 8146,
"s": 8068,
"text": "Python objects can be exported back to JSON with pretty printing and sorting."
}
] |
Groovy - floor() | The method floor gives the largest integer that is less than or equal to the argument.
double floor(double d)
double floor(float f)
Parameters − A double or float primitive data type.
Return Value − This method Returns the largest integer that is less than or equal to the argument. Returned as a double.
Following is an example of the usage of this method −
class Example {
static void main(String[] args) {
double a = -100.675;
float b = -90;
System.out.println(Math.floor(a));
System.out.println(Math.floor(b));
}
}
When we run the above program, we will get the following result −
-101.0
-90.0
52 Lectures
8 hours
Krishna Sakinala
49 Lectures
2.5 hours
Packt Publishing
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2325,
"s": 2238,
"text": "The method floor gives the largest integer that is less than or equal to the argument."
},
{
"code": null,
"e": 2372,
"s": 2325,
"text": "double floor(double d) \ndouble floor(float f)\n"
},
{
"code": null,
"e": 2424,
"s": 2372,
"text": "Parameters − A double or float primitive data type."
},
{
"code": null,
"e": 2545,
"s": 2424,
"text": "Return Value − This method Returns the largest integer that is less than or equal to the argument. Returned as a double."
},
{
"code": null,
"e": 2599,
"s": 2545,
"text": "Following is an example of the usage of this method −"
},
{
"code": null,
"e": 2799,
"s": 2599,
"text": "class Example { \n static void main(String[] args) { \n double a = -100.675; \n float b = -90; \n\t\t\n System.out.println(Math.floor(a)); \n System.out.println(Math.floor(b)); \n } \n}"
},
{
"code": null,
"e": 2865,
"s": 2799,
"text": "When we run the above program, we will get the following result −"
},
{
"code": null,
"e": 2881,
"s": 2865,
"text": "-101.0 \n-90.0 \n"
},
{
"code": null,
"e": 2914,
"s": 2881,
"text": "\n 52 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 2932,
"s": 2914,
"text": " Krishna Sakinala"
},
{
"code": null,
"e": 2967,
"s": 2932,
"text": "\n 49 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 2985,
"s": 2967,
"text": " Packt Publishing"
},
{
"code": null,
"e": 2992,
"s": 2985,
"text": " Print"
},
{
"code": null,
"e": 3003,
"s": 2992,
"text": " Add Notes"
}
] |
Swing Examples - Show Alert message Dialog | Following example showcase how to show a simple message alert with Ok button in swing based application.
We are using the following APIs.
JOptionPane − To create a standard dialog box.
JOptionPane − To create a standard dialog box.
JOptionPane.showMessageDialog() − To show the simple alert message.
JOptionPane.showMessageDialog() − To show the simple alert message.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class SwingTester {
public static void main(String[] args) {
createWindow();
}
private static void createWindow() {
JFrame frame = new JFrame("Swing Tester");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createUI(frame);
frame.setSize(560, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static void createUI(final JFrame frame){
JPanel panel = new JPanel();
LayoutManager layout = new FlowLayout();
panel.setLayout(layout);
JButton button = new JButton("Click Me!");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "Welcome to Swing!");
}
});
panel.add(button);
frame.getContentPane().add(panel, BorderLayout.CENTER);
}
}
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2144,
"s": 2039,
"text": "Following example showcase how to show a simple message alert with Ok button in swing based application."
},
{
"code": null,
"e": 2177,
"s": 2144,
"text": "We are using the following APIs."
},
{
"code": null,
"e": 2224,
"s": 2177,
"text": "JOptionPane − To create a standard dialog box."
},
{
"code": null,
"e": 2271,
"s": 2224,
"text": "JOptionPane − To create a standard dialog box."
},
{
"code": null,
"e": 2339,
"s": 2271,
"text": "JOptionPane.showMessageDialog() − To show the simple alert message."
},
{
"code": null,
"e": 2407,
"s": 2339,
"text": "JOptionPane.showMessageDialog() − To show the simple alert message."
},
{
"code": null,
"e": 3623,
"s": 2407,
"text": "import java.awt.BorderLayout;\nimport java.awt.FlowLayout;\nimport java.awt.LayoutManager;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\n\nimport javax.swing.JButton;\nimport javax.swing.JFrame;\nimport javax.swing.JOptionPane;\nimport javax.swing.JPanel;\n\npublic class SwingTester {\n public static void main(String[] args) {\n createWindow();\n }\n\n private static void createWindow() { \n JFrame frame = new JFrame(\"Swing Tester\");\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\n createUI(frame);\n frame.setSize(560, 200); \n frame.setLocationRelativeTo(null); \n frame.setVisible(true);\n }\n\n private static void createUI(final JFrame frame){ \n JPanel panel = new JPanel();\n LayoutManager layout = new FlowLayout(); \n panel.setLayout(layout); \n JButton button = new JButton(\"Click Me!\");\n button.addActionListener(new ActionListener() {\n @Override\n public void actionPerformed(ActionEvent e) {\n JOptionPane.showMessageDialog(frame, \"Welcome to Swing!\");\n }\n });\n\n panel.add(button);\n frame.getContentPane().add(panel, BorderLayout.CENTER); \n } \n}"
},
{
"code": null,
"e": 3630,
"s": 3623,
"text": " Print"
},
{
"code": null,
"e": 3641,
"s": 3630,
"text": " Add Notes"
}
] |
How to check whether a value is numeric or not using jQuery ? - GeeksforGeeks | 11 Sep, 2019
Given an input element and the task is to check whether the entered value is numeric or not using jQuery. The jQuery $.isNumeric() method is used to check whether the entered number is numeric or not.
$.isNumeric() method: It is used to check whether the given argument is a numeric value or not. If it is numeric then it returns true Otherwise returns false.
Syntax:
$.isNumeric( argument )
Example 1: This example uses jQuery .isNumeric() method to check entered element is numeric or not.
<!DOCTYPE html><html> <head> <title> How to check whether a value is numeric or not in jQuery? </title> <script src="https://code.jquery.com/jquery-1.12.4.min.js"> </script></head> <body style="text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <h3> How to check whether a value is numeric or not in jQuery? </h3> <hr> <form> <p> Enter any value: <input style="text-align:center;" type="text"> </p> <button type="button">Click to Check</button> </form> <hr> <script type="text/javascript"> $(document).ready(function() { $("button").click(function() { var inputVal = $("input").val(); alert($.isNumeric(inputVal)); }); }); </script></body> </html>
Output:
Before entering the value:
Entering the value:
After click on the button:
Example 2: This example uses jQuery .isNumeric() method to check entered element is numeric or not.
<!DOCTYPE html><html> <head> <title> How to check whether a value is numeric or not in jQuery? </title> <script src="https://code.jquery.com/jquery-1.12.4.min.js"> </script></head> <body style="text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <h3> How to check whether a value is numeric or not in jQuery? </h3> <hr> <form> <p> Enter any value: <input style="text-align:center;" type="text"> </p> <button type="button">Click to Check</button> </form> <hr> <h4></h4> <script type="text/javascript"> $(document).ready(function() { $("button").click(function() { var inputVal = $("input").val(); var gfg = $.isNumeric(inputVal); if (gfg) { $("h4").text("The Value Entered is Numeric"); } else { $("h4").text("The Value Entered is Not Numeric"); } }); }); </script></body> </html>
Output:
Before Entering the value:
After entering the value and click on button:
jQuery-Misc
JQuery
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Form validation using jQuery
Scroll to the top of the page using JavaScript/jQuery
jQuery | children() with Examples
How to get the ID of the clicked button using JavaScript / jQuery ?
How to redirect to a particular section of a page using HTML or jQuery?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Convert a string to an integer in JavaScript | [
{
"code": null,
"e": 25103,
"s": 25075,
"text": "\n11 Sep, 2019"
},
{
"code": null,
"e": 25304,
"s": 25103,
"text": "Given an input element and the task is to check whether the entered value is numeric or not using jQuery. The jQuery $.isNumeric() method is used to check whether the entered number is numeric or not."
},
{
"code": null,
"e": 25463,
"s": 25304,
"text": "$.isNumeric() method: It is used to check whether the given argument is a numeric value or not. If it is numeric then it returns true Otherwise returns false."
},
{
"code": null,
"e": 25471,
"s": 25463,
"text": "Syntax:"
},
{
"code": null,
"e": 25495,
"s": 25471,
"text": "$.isNumeric( argument )"
},
{
"code": null,
"e": 25595,
"s": 25495,
"text": "Example 1: This example uses jQuery .isNumeric() method to check entered element is numeric or not."
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to check whether a value is numeric or not in jQuery? </title> <script src=\"https://code.jquery.com/jquery-1.12.4.min.js\"> </script></head> <body style=\"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <h3> How to check whether a value is numeric or not in jQuery? </h3> <hr> <form> <p> Enter any value: <input style=\"text-align:center;\" type=\"text\"> </p> <button type=\"button\">Click to Check</button> </form> <hr> <script type=\"text/javascript\"> $(document).ready(function() { $(\"button\").click(function() { var inputVal = $(\"input\").val(); alert($.isNumeric(inputVal)); }); }); </script></body> </html> ",
"e": 26511,
"s": 25595,
"text": null
},
{
"code": null,
"e": 26519,
"s": 26511,
"text": "Output:"
},
{
"code": null,
"e": 26546,
"s": 26519,
"text": "Before entering the value:"
},
{
"code": null,
"e": 26566,
"s": 26546,
"text": "Entering the value:"
},
{
"code": null,
"e": 26593,
"s": 26566,
"text": "After click on the button:"
},
{
"code": null,
"e": 26693,
"s": 26593,
"text": "Example 2: This example uses jQuery .isNumeric() method to check entered element is numeric or not."
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to check whether a value is numeric or not in jQuery? </title> <script src=\"https://code.jquery.com/jquery-1.12.4.min.js\"> </script></head> <body style=\"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <h3> How to check whether a value is numeric or not in jQuery? </h3> <hr> <form> <p> Enter any value: <input style=\"text-align:center;\" type=\"text\"> </p> <button type=\"button\">Click to Check</button> </form> <hr> <h4></h4> <script type=\"text/javascript\"> $(document).ready(function() { $(\"button\").click(function() { var inputVal = $(\"input\").val(); var gfg = $.isNumeric(inputVal); if (gfg) { $(\"h4\").text(\"The Value Entered is Numeric\"); } else { $(\"h4\").text(\"The Value Entered is Not Numeric\"); } }); }); </script></body> </html> ",
"e": 27852,
"s": 26693,
"text": null
},
{
"code": null,
"e": 27860,
"s": 27852,
"text": "Output:"
},
{
"code": null,
"e": 27887,
"s": 27860,
"text": "Before Entering the value:"
},
{
"code": null,
"e": 27933,
"s": 27887,
"text": "After entering the value and click on button:"
},
{
"code": null,
"e": 27945,
"s": 27933,
"text": "jQuery-Misc"
},
{
"code": null,
"e": 27952,
"s": 27945,
"text": "JQuery"
},
{
"code": null,
"e": 27969,
"s": 27952,
"text": "Web Technologies"
},
{
"code": null,
"e": 27996,
"s": 27969,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 28094,
"s": 27996,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28123,
"s": 28094,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 28177,
"s": 28123,
"text": "Scroll to the top of the page using JavaScript/jQuery"
},
{
"code": null,
"e": 28211,
"s": 28177,
"text": "jQuery | children() with Examples"
},
{
"code": null,
"e": 28279,
"s": 28211,
"text": "How to get the ID of the clicked button using JavaScript / jQuery ?"
},
{
"code": null,
"e": 28351,
"s": 28279,
"text": "How to redirect to a particular section of a page using HTML or jQuery?"
},
{
"code": null,
"e": 28393,
"s": 28351,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 28426,
"s": 28393,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28469,
"s": 28426,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28531,
"s": 28469,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
Data Cleaning with Python and Pandas: Detecting Missing Values | by John Sullivan | Towards Data Science | Data cleaning can be a tedious task.
It’s the start of a new project and you’re excited to apply some machine learning models.
You take a look at the data and quickly realize it’s an absolute mess.
According to IBM Data Analytics you can expect to spend up to 80% of your time cleaning data.
In this post we’ll walk through a number of different data cleaning tasks using Python’s Pandas library. Specifically, we’ll focus on probably the biggest data cleaning task, missing values.
After reading this post you’ll be able to more quickly clean data. We all want to spend less time cleaning data, and more time exploring and modeling.
Before we dive into code, it’s important to understand the sources of missing data. Here’s some typical reasons why data is missing:
User forgot to fill in a field.
Data was lost while transferring manually from a legacy database.
There was a programming error.
Users chose not to fill out a field tied to their beliefs about how the results would be used or interpreted.
As you can see, some of these sources are just simple random mistakes. Other times, there can be a deeper reason why data is missing.
It’s important to understand these different types of missing data from a statistics point of view. The type of missing data will influence how you deal with filling in the missing values.
Today we’ll learn how to detect missing values, and do some basic imputation. For a detailed statistical approach for dealing with missing data, check out these awesome slides from data scientist Matt Brems.
Keep in mind, imputing with a median or mean value is usually a bad idea, so be sure to check out Matt’s slides for the correct approach.
Before you start cleaning a data set, it’s a good idea to just get a general feel for the data. After that, you can put together a plan to clean the data.
I like to start by asking the following questions:
What are the features?
What are the expected types (int, float, string, boolean)?
Is there obvious missing data (values that Pandas can detect)?
Is there other types of missing data that’s not so obvious (can’t easily detect with Pandas)?
To show you what I mean, let’s start working through the example.
The data we’re going to work with is a very small real estate dataset. Head on over to our github page to grab a copy of the csv file so that you can code along.
Here’s a quick look at the data:
This is a much smaller dataset than what you’ll typically work with. Even though it’s a small dataset, it highlights a lot of real-world situations that you will encounter.
A good way to get a quick feel for the data is to take a look at the first few rows. Here’s how you would do that in Pandas:
# Importing librariesimport pandas as pdimport numpy as np# Read csv file into a pandas dataframedf = pd.read_csv("property data.csv")# Take a look at the first few rowsprint df.head()Out: ST_NUM ST_NAME OWN_OCCUPIED NUM_BEDROOMS0 104.0 PUTNAM Y 3.01 197.0 LEXINGTON N 3.02 NaN LEXINGTON N 3.03 201.0 BERKELEY NaN 1.04 203.0 BERKELEY Y 3.0
I know that I said we’ll be working with Pandas, but you can see that I also imported Numpy. We’ll use this a little bit later on to rename some missing values, so we might as well import it now.
After importing the libraries we read the csv file into a Pandas dataframe. You can think of the dataframe as a spreadsheet.
With the .head()method, we can easily see the first few rows.
Now I can answer my original question, what are my features? It’s pretty easy to infer the following features from the column names:
ST_NUM: Street number
ST_NAME: Street name
OWN_OCCUPIED: Is the residence owner occupied
NUM_BEDROOMS: Number of bedrooms
We can also answer, what are the expected types?
ST_NUM: float or int... some sort of numeric type
ST_NAME: string
OWN_OCCUPIED: string... Y (“Yes”) or N (“No”)
NUM_BEDROOMS: float or int, a numeric type
To answer the next two questions, we’ll need to start getting more in-depth width Pandas. Let’s start looking at examples of how to detect missing values
So what do I mean by “standard missing values”? These are missing values that Pandas can detect.
Going back to our original dataset, let’s take a look at the “Street Number” column.
In the third row there’s an empty cell. In the seventh row there’s an “NA” value.
Clearly these are both missing values. Let’s see how Pandas deals with these.
# Looking at the ST_NUM columnprint df['ST_NUM']print df['ST_NUM'].isnull()Out:0 104.01 197.02 NaN3 201.04 203.05 207.06 NaN7 213.08 215.0Out:0 False1 False2 True3 False4 False5 False6 True7 False8 False
Taking a look at the column, we can see that Pandas filled in the blank space with “NA”. Using the isnull() method, we can confirm that both the missing value and “NA” were recognized as missing values. Both boolean responses are True.
This is a simple example, but highlights an important point. Pandas will recognize both empty cells and “NA” types as missing values. In the next section, we’ll take a look at some types that Pandas won’t recognize.
Sometimes it might be the case where there’s missing values that have different formats.
Let’s take a look at the “Number of Bedrooms” column to see what I mean.
In this column, there’s four missing values.
n/a
NA
—
na
From the previous section, we know that Pandas will recognize “NA” as a missing value, but what about the others? Let’s take a look.
# Looking at the NUM_BEDROOMS columnprint df['NUM_BEDROOMS']print df['NUM_BEDROOMS'].isnull()Out:0 31 32 n/a3 14 35 NaN6 27 --8 naOut:0 False1 False2 False3 False4 False5 True6 False7 False8 False
Just like before, Pandas recognized the “NA” as a missing value. Unfortunately, the other types weren’t recognized.
If there’s multiple users manually entering data, then this is a common problem. Maybe i like to use “n/a” but you like to use “na”.
An easy way to detect these various formats is to put them in a list. Then when we import the data, Pandas will recognize them right away. Here’s an example of how we would do that.
# Making a list of missing value typesmissing_values = ["n/a", "na", "--"]df = pd.read_csv("property data.csv", na_values = missing_values)
Now let’s take another look at this column and see what happens.
# Looking at the NUM_BEDROOMS columnprint df['NUM_BEDROOMS']print df['NUM_BEDROOMS'].isnull()Out:0 3.01 3.02 NaN3 1.04 3.05 NaN6 2.07 NaN8 NaNOut:0 False1 False2 True3 False4 False5 True6 False7 True8 True
This time, all of the different formats were recognized as missing values.
You might not be able to catch all of these right away. As you work through the data and see other types of missing values, you can add them to the list.
It’s important to recognize these non-standard types of missing values for purposes of summarizing and transforming missing values. If you try and count the number of missing values before converting these non-standard types, you could end up missing a lot of missing values.
In the next section we’ll take a look at a more complicated, but very common, type of missing value.
So far we’ve seen standard missing values, and non-standard missing values. What if we have an unexpected type?
For example, if our feature is expected to be a string, but there’s a numeric type, then technically this is also a missing value.
Let’s take a look at the “Owner Occupied” column to see what I’m talking about.
From our previous examples, we know that Pandas will detect the empty cell in row seven as a missing value. Let’s confirm with some code.
# Looking at the OWN_OCCUPIED columnprint df['OWN_OCCUPIED']print df['OWN_OCCUPIED'].isnull()# Looking at the ST_NUM columnOut:0 Y1 N2 N3 124 Y5 Y6 NaN7 Y8 YOut:0 False1 False2 False3 False4 False5 False6 True7 False8 False
In the fourth row, there’s the number 12. The response for Owner Occupied should clearly be a string (Y or N), so this numeric type should be a missing value.
This example is a little more complicated so we’ll need to think through a strategy for detecting these types of missing values. There’s a number of different approaches, but here’s the way that I’m going to work through this one.
Loop through the OWN_OCCUPIED columnTry and turn the entry into an integerIf the entry can be changed into an integer, enter a missing valueIf the number can’t be an integer, we know it’s a string, so keep going
Loop through the OWN_OCCUPIED column
Try and turn the entry into an integer
If the entry can be changed into an integer, enter a missing value
If the number can’t be an integer, we know it’s a string, so keep going
Let’s take a look at the code and then we’ll go through it in detail.
# Detecting numbers cnt=0for row in df['OWN_OCCUPIED']: try: int(row) df.loc[cnt, 'OWN_OCCUPIED']=np.nan except ValueError: pass cnt+=1
In the code we’re looping through each entry in the “Owner Occupied” column. To try and change the entry to an integer, we’re using int(row).
If the value can be changed to an integer, we change the entry to a missing value using Numpy’s np.nan.
On the other hand, if it can’t be changed to an integer, we pass and keep going.
You’ll notice that I used try and except ValueError. This is called exception handling, and we use this to handle errors.
If we were to try and change an entry into an integer and it couldn’t be changed, then a ValueError would be returned, and the code would stop. To deal with this, we use exception handling to recognize these errors, and keep going.
Another important bit of the code is the .loc method. This is the preferred Pandas method for modifying entries in place. For more info on this you can check out the Pandas documentation.
Now that we’ve worked through the different ways of detecting missing values, we’ll take a look at summarizing, and replacing them.
After we’ve cleaned the missing values, we will probably want to summarize them. For instance, we might want to look at the total number of missing values for each feature.
# Total missing values for each featureprint df.isnull().sum()Out:ST_NUM 2ST_NAME 0OWN_OCCUPIED 2NUM_BEDROOMS 4
Other times we might want to do a quick check to see if we have any missing values at all.
# Any missing values?print df.isnull().values.any()Out:True
We might also want to get a total count of missing values.
# Total number of missing valuesprint df.isnull().sum().sum()Out:8
Now that we’ve summarized the number of missing values, let’s take a look at doing some simple replacements.
Often times you’ll have to figure out how you want to handle missing values.
Sometimes you’ll simply want to delete those rows, other times you’ll replace them.
As I mentioned earlier, this shouldn’t be taken lightly. We’ll go over some basic imputations, but for a detailed statistical approach for dealing with missing data, check out these awesome slides from data scientist Matt Brems.
That being said, maybe you just want to fill in missing values with a single value.
# Replace missing values with a numberdf['ST_NUM'].fillna(125, inplace=True)
More likely, you might want to do a location based imputation. Here’s how you would do that.
# Location based replacementdf.loc[2,'ST_NUM'] = 125
A very common way to replace missing values is using a median.
# Replace using median median = df['NUM_BEDROOMS'].median()df['NUM_BEDROOMS'].fillna(median, inplace=True)
We’ve gone over a few simple ways to replace missing values, but be sure to check out Matt’s slides for the proper techniques.
Dealing with messy data is inevitable. Data cleaning is just part of the process on a data science project.
In this article we went over some ways to detect, summarize, and replace missing values.
For even more resources about data cleaning, check out these data science books.
Armed with these techniques, you’ll spend less time data cleaning, and more time exploring and modeling. | [
{
"code": null,
"e": 208,
"s": 171,
"text": "Data cleaning can be a tedious task."
},
{
"code": null,
"e": 298,
"s": 208,
"text": "It’s the start of a new project and you’re excited to apply some machine learning models."
},
{
"code": null,
"e": 369,
"s": 298,
"text": "You take a look at the data and quickly realize it’s an absolute mess."
},
{
"code": null,
"e": 463,
"s": 369,
"text": "According to IBM Data Analytics you can expect to spend up to 80% of your time cleaning data."
},
{
"code": null,
"e": 654,
"s": 463,
"text": "In this post we’ll walk through a number of different data cleaning tasks using Python’s Pandas library. Specifically, we’ll focus on probably the biggest data cleaning task, missing values."
},
{
"code": null,
"e": 805,
"s": 654,
"text": "After reading this post you’ll be able to more quickly clean data. We all want to spend less time cleaning data, and more time exploring and modeling."
},
{
"code": null,
"e": 938,
"s": 805,
"text": "Before we dive into code, it’s important to understand the sources of missing data. Here’s some typical reasons why data is missing:"
},
{
"code": null,
"e": 970,
"s": 938,
"text": "User forgot to fill in a field."
},
{
"code": null,
"e": 1036,
"s": 970,
"text": "Data was lost while transferring manually from a legacy database."
},
{
"code": null,
"e": 1067,
"s": 1036,
"text": "There was a programming error."
},
{
"code": null,
"e": 1177,
"s": 1067,
"text": "Users chose not to fill out a field tied to their beliefs about how the results would be used or interpreted."
},
{
"code": null,
"e": 1311,
"s": 1177,
"text": "As you can see, some of these sources are just simple random mistakes. Other times, there can be a deeper reason why data is missing."
},
{
"code": null,
"e": 1500,
"s": 1311,
"text": "It’s important to understand these different types of missing data from a statistics point of view. The type of missing data will influence how you deal with filling in the missing values."
},
{
"code": null,
"e": 1708,
"s": 1500,
"text": "Today we’ll learn how to detect missing values, and do some basic imputation. For a detailed statistical approach for dealing with missing data, check out these awesome slides from data scientist Matt Brems."
},
{
"code": null,
"e": 1846,
"s": 1708,
"text": "Keep in mind, imputing with a median or mean value is usually a bad idea, so be sure to check out Matt’s slides for the correct approach."
},
{
"code": null,
"e": 2001,
"s": 1846,
"text": "Before you start cleaning a data set, it’s a good idea to just get a general feel for the data. After that, you can put together a plan to clean the data."
},
{
"code": null,
"e": 2052,
"s": 2001,
"text": "I like to start by asking the following questions:"
},
{
"code": null,
"e": 2075,
"s": 2052,
"text": "What are the features?"
},
{
"code": null,
"e": 2134,
"s": 2075,
"text": "What are the expected types (int, float, string, boolean)?"
},
{
"code": null,
"e": 2197,
"s": 2134,
"text": "Is there obvious missing data (values that Pandas can detect)?"
},
{
"code": null,
"e": 2291,
"s": 2197,
"text": "Is there other types of missing data that’s not so obvious (can’t easily detect with Pandas)?"
},
{
"code": null,
"e": 2357,
"s": 2291,
"text": "To show you what I mean, let’s start working through the example."
},
{
"code": null,
"e": 2519,
"s": 2357,
"text": "The data we’re going to work with is a very small real estate dataset. Head on over to our github page to grab a copy of the csv file so that you can code along."
},
{
"code": null,
"e": 2552,
"s": 2519,
"text": "Here’s a quick look at the data:"
},
{
"code": null,
"e": 2725,
"s": 2552,
"text": "This is a much smaller dataset than what you’ll typically work with. Even though it’s a small dataset, it highlights a lot of real-world situations that you will encounter."
},
{
"code": null,
"e": 2850,
"s": 2725,
"text": "A good way to get a quick feel for the data is to take a look at the first few rows. Here’s how you would do that in Pandas:"
},
{
"code": null,
"e": 3321,
"s": 2850,
"text": "# Importing librariesimport pandas as pdimport numpy as np# Read csv file into a pandas dataframedf = pd.read_csv(\"property data.csv\")# Take a look at the first few rowsprint df.head()Out: ST_NUM ST_NAME OWN_OCCUPIED NUM_BEDROOMS0 104.0 PUTNAM Y 3.01 197.0 LEXINGTON N 3.02 NaN LEXINGTON N 3.03 201.0 BERKELEY NaN 1.04 203.0 BERKELEY Y 3.0"
},
{
"code": null,
"e": 3517,
"s": 3321,
"text": "I know that I said we’ll be working with Pandas, but you can see that I also imported Numpy. We’ll use this a little bit later on to rename some missing values, so we might as well import it now."
},
{
"code": null,
"e": 3642,
"s": 3517,
"text": "After importing the libraries we read the csv file into a Pandas dataframe. You can think of the dataframe as a spreadsheet."
},
{
"code": null,
"e": 3704,
"s": 3642,
"text": "With the .head()method, we can easily see the first few rows."
},
{
"code": null,
"e": 3837,
"s": 3704,
"text": "Now I can answer my original question, what are my features? It’s pretty easy to infer the following features from the column names:"
},
{
"code": null,
"e": 3859,
"s": 3837,
"text": "ST_NUM: Street number"
},
{
"code": null,
"e": 3880,
"s": 3859,
"text": "ST_NAME: Street name"
},
{
"code": null,
"e": 3926,
"s": 3880,
"text": "OWN_OCCUPIED: Is the residence owner occupied"
},
{
"code": null,
"e": 3959,
"s": 3926,
"text": "NUM_BEDROOMS: Number of bedrooms"
},
{
"code": null,
"e": 4008,
"s": 3959,
"text": "We can also answer, what are the expected types?"
},
{
"code": null,
"e": 4058,
"s": 4008,
"text": "ST_NUM: float or int... some sort of numeric type"
},
{
"code": null,
"e": 4074,
"s": 4058,
"text": "ST_NAME: string"
},
{
"code": null,
"e": 4120,
"s": 4074,
"text": "OWN_OCCUPIED: string... Y (“Yes”) or N (“No”)"
},
{
"code": null,
"e": 4163,
"s": 4120,
"text": "NUM_BEDROOMS: float or int, a numeric type"
},
{
"code": null,
"e": 4317,
"s": 4163,
"text": "To answer the next two questions, we’ll need to start getting more in-depth width Pandas. Let’s start looking at examples of how to detect missing values"
},
{
"code": null,
"e": 4414,
"s": 4317,
"text": "So what do I mean by “standard missing values”? These are missing values that Pandas can detect."
},
{
"code": null,
"e": 4499,
"s": 4414,
"text": "Going back to our original dataset, let’s take a look at the “Street Number” column."
},
{
"code": null,
"e": 4581,
"s": 4499,
"text": "In the third row there’s an empty cell. In the seventh row there’s an “NA” value."
},
{
"code": null,
"e": 4659,
"s": 4581,
"text": "Clearly these are both missing values. Let’s see how Pandas deals with these."
},
{
"code": null,
"e": 4923,
"s": 4659,
"text": "# Looking at the ST_NUM columnprint df['ST_NUM']print df['ST_NUM'].isnull()Out:0 104.01 197.02 NaN3 201.04 203.05 207.06 NaN7 213.08 215.0Out:0 False1 False2 True3 False4 False5 False6 True7 False8 False"
},
{
"code": null,
"e": 5159,
"s": 4923,
"text": "Taking a look at the column, we can see that Pandas filled in the blank space with “NA”. Using the isnull() method, we can confirm that both the missing value and “NA” were recognized as missing values. Both boolean responses are True."
},
{
"code": null,
"e": 5375,
"s": 5159,
"text": "This is a simple example, but highlights an important point. Pandas will recognize both empty cells and “NA” types as missing values. In the next section, we’ll take a look at some types that Pandas won’t recognize."
},
{
"code": null,
"e": 5464,
"s": 5375,
"text": "Sometimes it might be the case where there’s missing values that have different formats."
},
{
"code": null,
"e": 5537,
"s": 5464,
"text": "Let’s take a look at the “Number of Bedrooms” column to see what I mean."
},
{
"code": null,
"e": 5582,
"s": 5537,
"text": "In this column, there’s four missing values."
},
{
"code": null,
"e": 5586,
"s": 5582,
"text": "n/a"
},
{
"code": null,
"e": 5589,
"s": 5586,
"text": "NA"
},
{
"code": null,
"e": 5591,
"s": 5589,
"text": "—"
},
{
"code": null,
"e": 5594,
"s": 5591,
"text": "na"
},
{
"code": null,
"e": 5727,
"s": 5594,
"text": "From the previous section, we know that Pandas will recognize “NA” as a missing value, but what about the others? Let’s take a look."
},
{
"code": null,
"e": 5991,
"s": 5727,
"text": "# Looking at the NUM_BEDROOMS columnprint df['NUM_BEDROOMS']print df['NUM_BEDROOMS'].isnull()Out:0 31 32 n/a3 14 35 NaN6 27 --8 naOut:0 False1 False2 False3 False4 False5 True6 False7 False8 False"
},
{
"code": null,
"e": 6107,
"s": 5991,
"text": "Just like before, Pandas recognized the “NA” as a missing value. Unfortunately, the other types weren’t recognized."
},
{
"code": null,
"e": 6240,
"s": 6107,
"text": "If there’s multiple users manually entering data, then this is a common problem. Maybe i like to use “n/a” but you like to use “na”."
},
{
"code": null,
"e": 6422,
"s": 6240,
"text": "An easy way to detect these various formats is to put them in a list. Then when we import the data, Pandas will recognize them right away. Here’s an example of how we would do that."
},
{
"code": null,
"e": 6562,
"s": 6422,
"text": "# Making a list of missing value typesmissing_values = [\"n/a\", \"na\", \"--\"]df = pd.read_csv(\"property data.csv\", na_values = missing_values)"
},
{
"code": null,
"e": 6627,
"s": 6562,
"text": "Now let’s take another look at this column and see what happens."
},
{
"code": null,
"e": 6891,
"s": 6627,
"text": "# Looking at the NUM_BEDROOMS columnprint df['NUM_BEDROOMS']print df['NUM_BEDROOMS'].isnull()Out:0 3.01 3.02 NaN3 1.04 3.05 NaN6 2.07 NaN8 NaNOut:0 False1 False2 True3 False4 False5 True6 False7 True8 True"
},
{
"code": null,
"e": 6966,
"s": 6891,
"text": "This time, all of the different formats were recognized as missing values."
},
{
"code": null,
"e": 7120,
"s": 6966,
"text": "You might not be able to catch all of these right away. As you work through the data and see other types of missing values, you can add them to the list."
},
{
"code": null,
"e": 7396,
"s": 7120,
"text": "It’s important to recognize these non-standard types of missing values for purposes of summarizing and transforming missing values. If you try and count the number of missing values before converting these non-standard types, you could end up missing a lot of missing values."
},
{
"code": null,
"e": 7497,
"s": 7396,
"text": "In the next section we’ll take a look at a more complicated, but very common, type of missing value."
},
{
"code": null,
"e": 7609,
"s": 7497,
"text": "So far we’ve seen standard missing values, and non-standard missing values. What if we have an unexpected type?"
},
{
"code": null,
"e": 7740,
"s": 7609,
"text": "For example, if our feature is expected to be a string, but there’s a numeric type, then technically this is also a missing value."
},
{
"code": null,
"e": 7820,
"s": 7740,
"text": "Let’s take a look at the “Owner Occupied” column to see what I’m talking about."
},
{
"code": null,
"e": 7958,
"s": 7820,
"text": "From our previous examples, we know that Pandas will detect the empty cell in row seven as a missing value. Let’s confirm with some code."
},
{
"code": null,
"e": 8252,
"s": 7958,
"text": "# Looking at the OWN_OCCUPIED columnprint df['OWN_OCCUPIED']print df['OWN_OCCUPIED'].isnull()# Looking at the ST_NUM columnOut:0 Y1 N2 N3 124 Y5 Y6 NaN7 Y8 YOut:0 False1 False2 False3 False4 False5 False6 True7 False8 False"
},
{
"code": null,
"e": 8411,
"s": 8252,
"text": "In the fourth row, there’s the number 12. The response for Owner Occupied should clearly be a string (Y or N), so this numeric type should be a missing value."
},
{
"code": null,
"e": 8642,
"s": 8411,
"text": "This example is a little more complicated so we’ll need to think through a strategy for detecting these types of missing values. There’s a number of different approaches, but here’s the way that I’m going to work through this one."
},
{
"code": null,
"e": 8854,
"s": 8642,
"text": "Loop through the OWN_OCCUPIED columnTry and turn the entry into an integerIf the entry can be changed into an integer, enter a missing valueIf the number can’t be an integer, we know it’s a string, so keep going"
},
{
"code": null,
"e": 8891,
"s": 8854,
"text": "Loop through the OWN_OCCUPIED column"
},
{
"code": null,
"e": 8930,
"s": 8891,
"text": "Try and turn the entry into an integer"
},
{
"code": null,
"e": 8997,
"s": 8930,
"text": "If the entry can be changed into an integer, enter a missing value"
},
{
"code": null,
"e": 9069,
"s": 8997,
"text": "If the number can’t be an integer, we know it’s a string, so keep going"
},
{
"code": null,
"e": 9139,
"s": 9069,
"text": "Let’s take a look at the code and then we’ll go through it in detail."
},
{
"code": null,
"e": 9305,
"s": 9139,
"text": "# Detecting numbers cnt=0for row in df['OWN_OCCUPIED']: try: int(row) df.loc[cnt, 'OWN_OCCUPIED']=np.nan except ValueError: pass cnt+=1"
},
{
"code": null,
"e": 9447,
"s": 9305,
"text": "In the code we’re looping through each entry in the “Owner Occupied” column. To try and change the entry to an integer, we’re using int(row)."
},
{
"code": null,
"e": 9551,
"s": 9447,
"text": "If the value can be changed to an integer, we change the entry to a missing value using Numpy’s np.nan."
},
{
"code": null,
"e": 9632,
"s": 9551,
"text": "On the other hand, if it can’t be changed to an integer, we pass and keep going."
},
{
"code": null,
"e": 9754,
"s": 9632,
"text": "You’ll notice that I used try and except ValueError. This is called exception handling, and we use this to handle errors."
},
{
"code": null,
"e": 9986,
"s": 9754,
"text": "If we were to try and change an entry into an integer and it couldn’t be changed, then a ValueError would be returned, and the code would stop. To deal with this, we use exception handling to recognize these errors, and keep going."
},
{
"code": null,
"e": 10174,
"s": 9986,
"text": "Another important bit of the code is the .loc method. This is the preferred Pandas method for modifying entries in place. For more info on this you can check out the Pandas documentation."
},
{
"code": null,
"e": 10306,
"s": 10174,
"text": "Now that we’ve worked through the different ways of detecting missing values, we’ll take a look at summarizing, and replacing them."
},
{
"code": null,
"e": 10479,
"s": 10306,
"text": "After we’ve cleaned the missing values, we will probably want to summarize them. For instance, we might want to look at the total number of missing values for each feature."
},
{
"code": null,
"e": 10614,
"s": 10479,
"text": "# Total missing values for each featureprint df.isnull().sum()Out:ST_NUM 2ST_NAME 0OWN_OCCUPIED 2NUM_BEDROOMS 4"
},
{
"code": null,
"e": 10705,
"s": 10614,
"text": "Other times we might want to do a quick check to see if we have any missing values at all."
},
{
"code": null,
"e": 10765,
"s": 10705,
"text": "# Any missing values?print df.isnull().values.any()Out:True"
},
{
"code": null,
"e": 10824,
"s": 10765,
"text": "We might also want to get a total count of missing values."
},
{
"code": null,
"e": 10891,
"s": 10824,
"text": "# Total number of missing valuesprint df.isnull().sum().sum()Out:8"
},
{
"code": null,
"e": 11000,
"s": 10891,
"text": "Now that we’ve summarized the number of missing values, let’s take a look at doing some simple replacements."
},
{
"code": null,
"e": 11077,
"s": 11000,
"text": "Often times you’ll have to figure out how you want to handle missing values."
},
{
"code": null,
"e": 11161,
"s": 11077,
"text": "Sometimes you’ll simply want to delete those rows, other times you’ll replace them."
},
{
"code": null,
"e": 11390,
"s": 11161,
"text": "As I mentioned earlier, this shouldn’t be taken lightly. We’ll go over some basic imputations, but for a detailed statistical approach for dealing with missing data, check out these awesome slides from data scientist Matt Brems."
},
{
"code": null,
"e": 11474,
"s": 11390,
"text": "That being said, maybe you just want to fill in missing values with a single value."
},
{
"code": null,
"e": 11551,
"s": 11474,
"text": "# Replace missing values with a numberdf['ST_NUM'].fillna(125, inplace=True)"
},
{
"code": null,
"e": 11644,
"s": 11551,
"text": "More likely, you might want to do a location based imputation. Here’s how you would do that."
},
{
"code": null,
"e": 11697,
"s": 11644,
"text": "# Location based replacementdf.loc[2,'ST_NUM'] = 125"
},
{
"code": null,
"e": 11760,
"s": 11697,
"text": "A very common way to replace missing values is using a median."
},
{
"code": null,
"e": 11867,
"s": 11760,
"text": "# Replace using median median = df['NUM_BEDROOMS'].median()df['NUM_BEDROOMS'].fillna(median, inplace=True)"
},
{
"code": null,
"e": 11994,
"s": 11867,
"text": "We’ve gone over a few simple ways to replace missing values, but be sure to check out Matt’s slides for the proper techniques."
},
{
"code": null,
"e": 12102,
"s": 11994,
"text": "Dealing with messy data is inevitable. Data cleaning is just part of the process on a data science project."
},
{
"code": null,
"e": 12191,
"s": 12102,
"text": "In this article we went over some ways to detect, summarize, and replace missing values."
},
{
"code": null,
"e": 12272,
"s": 12191,
"text": "For even more resources about data cleaning, check out these data science books."
}
] |
Clear/Set a specific bit of a number in Arduino | When you delve into advanced firmware, you deal with a lot of registers, whose specific bits need to be set or cleared depending on your use case. Arduino has inbuild functions to do that.
bitSet(x, index)
and,
bitClear(x, index)
Where x is the number whose bit has to be set/ cleared and index is the position of the bit (0 for least significant or right-most bit). This function makes changes in the number x in place, and also returns the updated value of x.
Note that setting a bit means setting its value to 1, and clearing it means setting its value to 0.
The following example illustrates the use of these functions −
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
Serial.println();
int x = 6;
Serial.println(x);
bitSet(x,0);
Serial.println(x);
bitClear(x,2);
Serial.println(x);
bitClear(x,3);
Serial.println(x);
}
void loop() {
// put your main code here, to run repeatedly:
}
The Serial Monitor output is shown below −
As you can see, we start off with the number 6 (0b0110).
We then set its 0th bit, yielding (0b0111), which corresponds to 7.
Then, we clear its 2nd bit, yielding (0b0011), which corresponds to 3.
We then clear its 3rd bit, which was already 0. Thus, we again get (0b0011), which corresponds to 3.
The Serial Monitor output shows these numbers in the exact sequence we just described. | [
{
"code": null,
"e": 1251,
"s": 1062,
"text": "When you delve into advanced firmware, you deal with a lot of registers, whose specific bits need to be set or cleared depending on your use case. Arduino has inbuild functions to do that."
},
{
"code": null,
"e": 1268,
"s": 1251,
"text": "bitSet(x, index)"
},
{
"code": null,
"e": 1273,
"s": 1268,
"text": "and,"
},
{
"code": null,
"e": 1292,
"s": 1273,
"text": "bitClear(x, index)"
},
{
"code": null,
"e": 1524,
"s": 1292,
"text": "Where x is the number whose bit has to be set/ cleared and index is the position of the bit (0 for least significant or right-most bit). This function makes changes in the number x in place, and also returns the updated value of x."
},
{
"code": null,
"e": 1624,
"s": 1524,
"text": "Note that setting a bit means setting its value to 1, and clearing it means setting its value to 0."
},
{
"code": null,
"e": 1687,
"s": 1624,
"text": "The following example illustrates the use of these functions −"
},
{
"code": null,
"e": 2015,
"s": 1687,
"text": "void setup() {\n // put your setup code here, to run once:\n Serial.begin(9600);\n Serial.println();\n int x = 6;\n\n Serial.println(x);\n bitSet(x,0);\n Serial.println(x);\n bitClear(x,2);\n Serial.println(x);\n bitClear(x,3);\n Serial.println(x);\n}\n\nvoid loop() {\n // put your main code here, to run repeatedly:\n}"
},
{
"code": null,
"e": 2058,
"s": 2015,
"text": "The Serial Monitor output is shown below −"
},
{
"code": null,
"e": 2115,
"s": 2058,
"text": "As you can see, we start off with the number 6 (0b0110)."
},
{
"code": null,
"e": 2183,
"s": 2115,
"text": "We then set its 0th bit, yielding (0b0111), which corresponds to 7."
},
{
"code": null,
"e": 2254,
"s": 2183,
"text": "Then, we clear its 2nd bit, yielding (0b0011), which corresponds to 3."
},
{
"code": null,
"e": 2355,
"s": 2254,
"text": "We then clear its 3rd bit, which was already 0. Thus, we again get (0b0011), which corresponds to 3."
},
{
"code": null,
"e": 2442,
"s": 2355,
"text": "The Serial Monitor output shows these numbers in the exact sequence we just described."
}
] |
Elixir - Structs | Structs are extensions built on top of maps that provide compile-time checks and default values.
To define a struct, the defstruct construct is used −
defmodule User do
defstruct name: "John", age: 27
end
The keyword list used with defstruct defines what fields the struct will have along with their default values. Structs take the name of the module they are defined in. In the example given above, we defined a struct named User. We can now create User structs by using a syntax similar to the one used to create maps −
new_john = %User{})
ayush = %User{name: "Ayush", age: 20}
megan = %User{name: "Megan"})
The above code will generate three different structs with values −
%User{age: 27, name: "John"}
%User{age: 20, name: "Ayush"}
%User{age: 27, name: "Megan"}
Structs provide compile-time guarantees that only the fields (and all of them) defined through defstruct will be allowed to exist in a struct. So you cannot define your own fields once you have created the struct in the module.
When we discussed maps, we showed how we can access and update the fields of a map. The same techniques (and the same syntax) apply to structs as well. For example, if we want to update the user we created in the earlier example, then −
defmodule User do
defstruct name: "John", age: 27
end
john = %User{}
#john right now is: %User{age: 27, name: "John"}
#To access name and age of John,
IO.puts(john.name)
IO.puts(john.age)
When the above program is run, it produces the following result −
John
27
To update a value in a struct, we will again use the same procedure that we used in the map chapter,
meg = %{john | name: "Meg"}
Structs can also be used in pattern matching, both for matching on the value of specific keys as well as for ensuring that the matching value is a struct of the same type as the matched value.
35 Lectures
3 hours
Pranjal Srivastava
54 Lectures
6 hours
Pranjal Srivastava, Harshit Srivastava
80 Lectures
9.5 hours
Pranjal Srivastava
43 Lectures
4 hours
Mohammad Nauman
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2279,
"s": 2182,
"text": "Structs are extensions built on top of maps that provide compile-time checks and default values."
},
{
"code": null,
"e": 2333,
"s": 2279,
"text": "To define a struct, the defstruct construct is used −"
},
{
"code": null,
"e": 2390,
"s": 2333,
"text": "defmodule User do\n defstruct name: \"John\", age: 27\nend"
},
{
"code": null,
"e": 2708,
"s": 2390,
"text": "The keyword list used with defstruct defines what fields the struct will have along with their default values. Structs take the name of the module they are defined in. In the example given above, we defined a struct named User. We can now create User structs by using a syntax similar to the one used to create maps −"
},
{
"code": null,
"e": 2796,
"s": 2708,
"text": "new_john = %User{})\nayush = %User{name: \"Ayush\", age: 20}\nmegan = %User{name: \"Megan\"})"
},
{
"code": null,
"e": 2863,
"s": 2796,
"text": "The above code will generate three different structs with values −"
},
{
"code": null,
"e": 2953,
"s": 2863,
"text": "%User{age: 27, name: \"John\"}\n%User{age: 20, name: \"Ayush\"}\n%User{age: 27, name: \"Megan\"}\n"
},
{
"code": null,
"e": 3181,
"s": 2953,
"text": "Structs provide compile-time guarantees that only the fields (and all of them) defined through defstruct will be allowed to exist in a struct. So you cannot define your own fields once you have created the struct in the module."
},
{
"code": null,
"e": 3418,
"s": 3181,
"text": "When we discussed maps, we showed how we can access and update the fields of a map. The same techniques (and the same syntax) apply to structs as well. For example, if we want to update the user we created in the earlier example, then −"
},
{
"code": null,
"e": 3611,
"s": 3418,
"text": "defmodule User do\n defstruct name: \"John\", age: 27\nend\njohn = %User{}\n#john right now is: %User{age: 27, name: \"John\"}\n\n#To access name and age of John, \nIO.puts(john.name)\nIO.puts(john.age)"
},
{
"code": null,
"e": 3677,
"s": 3611,
"text": "When the above program is run, it produces the following result −"
},
{
"code": null,
"e": 3686,
"s": 3677,
"text": "John\n27\n"
},
{
"code": null,
"e": 3787,
"s": 3686,
"text": "To update a value in a struct, we will again use the same procedure that we used in the map chapter,"
},
{
"code": null,
"e": 3815,
"s": 3787,
"text": "meg = %{john | name: \"Meg\"}"
},
{
"code": null,
"e": 4008,
"s": 3815,
"text": "Structs can also be used in pattern matching, both for matching on the value of specific keys as well as for ensuring that the matching value is a struct of the same type as the matched value."
},
{
"code": null,
"e": 4041,
"s": 4008,
"text": "\n 35 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 4061,
"s": 4041,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 4094,
"s": 4061,
"text": "\n 54 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4134,
"s": 4094,
"text": " Pranjal Srivastava, Harshit Srivastava"
},
{
"code": null,
"e": 4169,
"s": 4134,
"text": "\n 80 Lectures \n 9.5 hours \n"
},
{
"code": null,
"e": 4189,
"s": 4169,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 4222,
"s": 4189,
"text": "\n 43 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4239,
"s": 4222,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 4246,
"s": 4239,
"text": " Print"
},
{
"code": null,
"e": 4257,
"s": 4246,
"text": " Add Notes"
}
] |
Python | Convert byteString key:value pair of dictionary to String - GeeksforGeeks | 11 Feb, 2019
Given a dictionary having key:value pairs as byteString, the task is to convert the key:value pair to string.
Examples:
Input: {b'EmplId': b'12345', b'Name': b'Paras', b'Company': b'Cyware' }
Output: {'EmplId': '12345', 'Name': 'Paras', 'Company': 'Cyware'}
Input: {b'Key1': b'Geeks', b'Key2': b'For', b'Key3': b'Geek' }
Output: {'Key1':'Geeks', 'Key2':'For', 'Key3':'Geek' }
Method #1: By dictionary comprehension
# Python Code to convert ByteString key:value # pair of dictionary to String. # Initialising dictionary x = {b'EmplId': b'12345', b'Name': b'Paras', b'Company': b'Cyware'} # Convertingx = { y.decode('ascii'): x.get(y).decode('ascii') for y in x.keys() } # printing converted dictionaryprint(x)
{'Name': 'Paras', 'EmplId': '12345', 'Company': 'Cyware'}
Method #2: By iterating key and values
# Python Code to convert ByteString key:value # pair of dictionary to String. # Initialising dictionary x = {b'EmplId': b'12345', b'Name': b'Paras', b'Company': b'Cyware'} # Initialising empty dictionary y = {} # Convertingfor key, value in x.items(): y[key.decode("utf-8")] = value.decode("utf-8") # printing converted dictionaryprint(y)
{'Company': 'Cyware', 'Name': 'Paras', 'EmplId': '12345'}
Python dictionary-programs
python-dict
Python
Python Programs
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Python program to convert a list to string
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary | [
{
"code": null,
"e": 24554,
"s": 24526,
"text": "\n11 Feb, 2019"
},
{
"code": null,
"e": 24664,
"s": 24554,
"text": "Given a dictionary having key:value pairs as byteString, the task is to convert the key:value pair to string."
},
{
"code": null,
"e": 24674,
"s": 24664,
"text": "Examples:"
},
{
"code": null,
"e": 24932,
"s": 24674,
"text": "Input: {b'EmplId': b'12345', b'Name': b'Paras', b'Company': b'Cyware' }\nOutput: {'EmplId': '12345', 'Name': 'Paras', 'Company': 'Cyware'}\n\nInput: {b'Key1': b'Geeks', b'Key2': b'For', b'Key3': b'Geek' }\nOutput: {'Key1':'Geeks', 'Key2':'For', 'Key3':'Geek' }\n"
},
{
"code": null,
"e": 24972,
"s": 24932,
"text": " Method #1: By dictionary comprehension"
},
{
"code": "# Python Code to convert ByteString key:value # pair of dictionary to String. # Initialising dictionary x = {b'EmplId': b'12345', b'Name': b'Paras', b'Company': b'Cyware'} # Convertingx = { y.decode('ascii'): x.get(y).decode('ascii') for y in x.keys() } # printing converted dictionaryprint(x)",
"e": 25269,
"s": 24972,
"text": null
},
{
"code": null,
"e": 25328,
"s": 25269,
"text": "{'Name': 'Paras', 'EmplId': '12345', 'Company': 'Cyware'}\n"
},
{
"code": null,
"e": 25368,
"s": 25328,
"text": " Method #2: By iterating key and values"
},
{
"code": "# Python Code to convert ByteString key:value # pair of dictionary to String. # Initialising dictionary x = {b'EmplId': b'12345', b'Name': b'Paras', b'Company': b'Cyware'} # Initialising empty dictionary y = {} # Convertingfor key, value in x.items(): y[key.decode(\"utf-8\")] = value.decode(\"utf-8\") # printing converted dictionaryprint(y)",
"e": 25714,
"s": 25368,
"text": null
},
{
"code": null,
"e": 25773,
"s": 25714,
"text": "{'Company': 'Cyware', 'Name': 'Paras', 'EmplId': '12345'}\n"
},
{
"code": null,
"e": 25800,
"s": 25773,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 25812,
"s": 25800,
"text": "python-dict"
},
{
"code": null,
"e": 25819,
"s": 25812,
"text": "Python"
},
{
"code": null,
"e": 25835,
"s": 25819,
"text": "Python Programs"
},
{
"code": null,
"e": 25847,
"s": 25835,
"text": "python-dict"
},
{
"code": null,
"e": 25945,
"s": 25847,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25954,
"s": 25945,
"text": "Comments"
},
{
"code": null,
"e": 25967,
"s": 25954,
"text": "Old Comments"
},
{
"code": null,
"e": 25985,
"s": 25967,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26020,
"s": 25985,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26042,
"s": 26020,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26074,
"s": 26042,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26104,
"s": 26074,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26147,
"s": 26104,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 26169,
"s": 26147,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26215,
"s": 26169,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 26254,
"s": 26215,
"text": "Python | Get dictionary keys as a list"
}
] |
How to update ui from Intent Service in android? | Before getting into example, we should know what Intent service is in android. Intent Service is going to do back ground operation asynchronously. When user call startService() from activity , it doesn’t create instance for each request. It going to stop service after done some action in service class or else we need to stop service using stopSelf().
This example demonstrate about How to update ui from Intent Service.
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"?>
<android.support.constraint.ConstraintLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:app = "http://schemas.android.com/apk/res-auto"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity">
<TextView
android:id = "@+id/text"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text = "Start Service"
android:textSize = "25sp"
app:layout_constraintBottom_toBottomOf = "parent"
app:layout_constraintLeft_toLeftOf = "parent"
app:layout_constraintRight_toRightOf = "parent"
app:layout_constraintTop_toTopOf = "parent" />
</android.support.constraint.ConstraintLayout>
In the above code, we have taken text view, when user gets the data from intent service it will update.
Step 3 − Add the following code to src/MainActivity.java
package com.example.andy.myapplication;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView text;
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String s1 = intent.getStringExtra("DATAPASSED");
text.setText(s1);
}
};
@Override
protected void onStart() {
super.onStart();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.example.andy.myapplication");
registerReceiver(broadcastReceiver, intentFilter);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = findViewById(R.id.text);
text.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startService(new Intent(MainActivity.this, service.class));
}
});
}
@Override
protected void onStop() {
super.onStop();
unregisterReceiver(broadcastReceiver);
}
}
In the above code, we have create a service class and dynamic broad cast receiver as shown below –
@Override
protected void onStart() {
super.onStart();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.example.andy.myapplication");
registerReceiver(broadcastReceiver, intentFilter);
}
..................................................
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String s1 = intent.getStringExtra("DATAPASSED");
text.setText(s1);
}
};
......................................................................................
@Override
protected void onStop() {
super.onStop();
unregisterReceiver(broadcastReceiver);
}
Create a class called service.class file and add the following code –
package com.example.andy.myapplication;
import android.app.IntentService;
import android.content.Intent;
import android.os.IBinder;
public class service extends IntentService {
public service() {
super(service.class.getSimpleName());
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
protected void onHandleIntent(Intent intent) {
Intent intent1 = new Intent();
intent1.setAction("com.example.andy.myapplication");
intent1.putExtra("DATAPASSED", "Tutorialspoint.com");
sendBroadcast(intent1);
}
}
Step 4 − Add the following code to manifest.xml
<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android = "http://schemas.android.com/apk/res/android"
package = "com.example.andy.myapplication">
<uses-permission android:name = "android.permission.WAKE_LOCK"/>
<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>
<service android:name = ".service"/>
</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 –
In the above result, it shown default screen of application. When user click on “start Service” it will start service and update the textview as shown below-
Click here to download the project code | [
{
"code": null,
"e": 1415,
"s": 1062,
"text": "Before getting into example, we should know what Intent service is in android. Intent Service is going to do back ground operation asynchronously. When user call startService() from activity , it doesn’t create instance for each request. It going to stop service after done some action in service class or else we need to stop service using stopSelf()."
},
{
"code": null,
"e": 1484,
"s": 1415,
"text": "This example demonstrate about How to update ui from Intent Service."
},
{
"code": null,
"e": 1613,
"s": 1484,
"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": 1678,
"s": 1613,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2519,
"s": 1678,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<android.support.constraint.ConstraintLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:app = \"http://schemas.android.com/apk/res-auto\"\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/text\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\"\n android:text = \"Start Service\"\n android:textSize = \"25sp\"\n app:layout_constraintBottom_toBottomOf = \"parent\"\n app:layout_constraintLeft_toLeftOf = \"parent\"\n app:layout_constraintRight_toRightOf = \"parent\"\n app:layout_constraintTop_toTopOf = \"parent\" />\n</android.support.constraint.ConstraintLayout>"
},
{
"code": null,
"e": 2623,
"s": 2519,
"text": "In the above code, we have taken text view, when user gets the data from intent service it will update."
},
{
"code": null,
"e": 2680,
"s": 2623,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 4087,
"s": 2680,
"text": "package com.example.andy.myapplication;\n\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.IntentFilter;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.TextView;\n\npublic class MainActivity extends AppCompatActivity {\n TextView text;\n BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {\n @Override\n public void onReceive(Context context, Intent intent) {\n String s1 = intent.getStringExtra(\"DATAPASSED\");\n text.setText(s1);\n }\n };\n\n @Override\n protected void onStart() {\n super.onStart();\n IntentFilter intentFilter = new IntentFilter();\n intentFilter.addAction(\"com.example.andy.myapplication\");\n registerReceiver(broadcastReceiver, intentFilter);\n }\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n text = findViewById(R.id.text);\n text.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n startService(new Intent(MainActivity.this, service.class));\n }\n });\n }\n @Override\n protected void onStop() {\n super.onStop();\n unregisterReceiver(broadcastReceiver);\n }\n}"
},
{
"code": null,
"e": 4186,
"s": 4087,
"text": "In the above code, we have create a service class and dynamic broad cast receiver as shown below –"
},
{
"code": null,
"e": 4873,
"s": 4186,
"text": "@Override\nprotected void onStart() {\n super.onStart();\n IntentFilter intentFilter = new IntentFilter();\n intentFilter.addAction(\"com.example.andy.myapplication\");\n registerReceiver(broadcastReceiver, intentFilter);\n}\n\n..................................................\nBroadcastReceiver broadcastReceiver = new BroadcastReceiver() {\n @Override\n public void onReceive(Context context, Intent intent) {\n String s1 = intent.getStringExtra(\"DATAPASSED\");\n text.setText(s1);\n }\n};\n\n......................................................................................\n@Override\nprotected void onStop() {\n super.onStop();\n unregisterReceiver(broadcastReceiver);\n}"
},
{
"code": null,
"e": 4943,
"s": 4873,
"text": "Create a class called service.class file and add the following code –"
},
{
"code": null,
"e": 5526,
"s": 4943,
"text": "package com.example.andy.myapplication;\nimport android.app.IntentService;\nimport android.content.Intent;\nimport android.os.IBinder;\npublic class service extends IntentService {\n public service() {\n super(service.class.getSimpleName());\n }\n @Override\n public IBinder onBind(Intent intent) {\n return null;\n }\n @Override\n protected void onHandleIntent(Intent intent) {\n Intent intent1 = new Intent();\n intent1.setAction(\"com.example.andy.myapplication\");\n intent1.putExtra(\"DATAPASSED\", \"Tutorialspoint.com\");\n sendBroadcast(intent1);\n }\n}"
},
{
"code": null,
"e": 5574,
"s": 5526,
"text": "Step 4 − Add the following code to manifest.xml"
},
{
"code": null,
"e": 6400,
"s": 5574,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<manifest xmlns:android = \"http://schemas.android.com/apk/res/android\"\n package = \"com.example.andy.myapplication\">\n <uses-permission android:name = \"android.permission.WAKE_LOCK\"/>\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 <service android:name = \".service\"/>\n </application>\n</manifest>"
},
{
"code": null,
"e": 6747,
"s": 6400,
"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": 6905,
"s": 6747,
"text": "In the above result, it shown default screen of application. When user click on “start Service” it will start service and update the textview as shown below-"
},
{
"code": null,
"e": 6945,
"s": 6905,
"text": "Click here to download the project code"
}
] |
How can I remove the decimal part of JavaScript number? | To remove the decimal part from a number, use the JavaScript Math.trunc() method. The method returns the integer part of a number by removing the decimal part.
Live Demo
<!DOCTYPE html>
<html>
<body>
<p>Value:</p>
<script>
var myFloat = 4.5;
var myTrunc = Math.trunc( myFloat );
document.write(myTrunc+ " ");
</script>
</body>
</html>
Value:
4 | [
{
"code": null,
"e": 1222,
"s": 1062,
"text": "To remove the decimal part from a number, use the JavaScript Math.trunc() method. The method returns the integer part of a number by removing the decimal part."
},
{
"code": null,
"e": 1232,
"s": 1222,
"text": "Live Demo"
},
{
"code": null,
"e": 1448,
"s": 1232,
"text": "<!DOCTYPE html>\n<html>\n <body>\n <p>Value:</p>\n <script>\n var myFloat = 4.5;\n var myTrunc = Math.trunc( myFloat );\n document.write(myTrunc+ \" \");\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 1457,
"s": 1448,
"text": "Value:\n4"
}
] |
Maven - IntelliJ IDEA IDE Integration | IntelliJ IDEA has in-built support for Maven. We are using IntelliJ IDEA Community Edition 11.1 in this example.
Some of the features of IntelliJ IDEA are listed below −
You can run Maven goals from IntelliJ IDEA.
You can run Maven goals from IntelliJ IDEA.
You can view the output of Maven commands inside the IntelliJ IDEA using its own console.
You can view the output of Maven commands inside the IntelliJ IDEA using its own console.
You can update maven dependencies within IDE.
You can update maven dependencies within IDE.
You can Launch Maven builds from within IntelliJ IDEA.
You can Launch Maven builds from within IntelliJ IDEA.
IntelliJ IDEA does the dependency management automatically based on Maven's pom.xml.
IntelliJ IDEA does the dependency management automatically based on Maven's pom.xml.
IntelliJ IDEA resolves Maven dependencies from its workspace without installing to local Maven repository (requires dependency project be in same workspace).
IntelliJ IDEA resolves Maven dependencies from its workspace without installing to local Maven repository (requires dependency project be in same workspace).
IntelliJ IDEA automatically downloads the required dependencies and sources from the remote Maven repositories.
IntelliJ IDEA automatically downloads the required dependencies and sources from the remote Maven repositories.
IntelliJ IDEA provides wizards for creating new Maven projects, pom.xml.
IntelliJ IDEA provides wizards for creating new Maven projects, pom.xml.
Following example will help you to leverage benefits of integrating IntelliJ IDEA and Maven.
We will import Maven project using New Project Wizard.
Open IntelliJ IDEA.
Open IntelliJ IDEA.
Select File Menu > New Project Option.
Select File Menu > New Project Option.
Select import project from existing model.
Select import project from existing model.
Select Maven option
Select Project location, where a project was created using Maven. We have created a Java Project consumerBanking. Go to ‘Creating Java Project' chapter, to see how to create a project using Maven.
Select Project location, where a project was created using Maven. We have created a Java Project consumerBanking. Go to ‘Creating Java Project' chapter, to see how to create a project using Maven.
Select Maven project to import.
Enter name of the project and click finish.
Now, you can see the maven project in IntelliJ IDEA. Have a look at consumerBanking project external libraries. You can see that IntelliJ IDEA has added Maven dependencies to its build path under Maven section.
Now, you can see the maven project in IntelliJ IDEA. Have a look at consumerBanking project external libraries. You can see that IntelliJ IDEA has added Maven dependencies to its build path under Maven section.
Now, it is time to build this project using capability of IntelliJ IDEA.
Select consumerBanking project.
Select consumerBanking project.
Select Buid menu > Rebuild Project Option
Select Buid menu > Rebuild Project Option
You can see the output in IntelliJ IDEA Console
4:01:56 PM Compilation completed successfully
Select consumerBanking project.
Select consumerBanking project.
Right click on App.java to open context menu.
Right click on App.java to open context menu.
select Run App.main()
select Run App.main()
You will see the result in IntelliJ IDEA Console.
"C:\Program Files\Java\jdk1.6.0_21\bin\java"
-Didea.launcher.port=7533
"-Didea.launcher.bin.path=
C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 11.1.2\bin"
-Dfile.encoding=UTF-8
-classpath "C:\Program Files\Java\jdk1.6.0_21\jre\lib\charsets.jar;
C:\Program Files\Java\jdk1.6.0_21\jre\lib\deploy.jar;
C:\Program Files\Java\jdk1.6.0_21\jre\lib\javaws.jar;
C:\Program Files\Java\jdk1.6.0_21\jre\lib\jce.jar;
C:\Program Files\Java\jdk1.6.0_21\jre\lib\jsse.jar;
C:\Program Files\Java\jdk1.6.0_21\jre\lib\management-agent.jar;
C:\Program Files\Java\jdk1.6.0_21\jre\lib\plugin.jar;
C:\Program Files\Java\jdk1.6.0_21\jre\lib\resources.jar;
C:\Program Files\Java\jdk1.6.0_21\jre\lib\rt.jar;
C:\Program Files\Java\jdk1.6.0_21\jre\lib\ext\dnsns.jar;
C:\Program Files\Java\jdk1.6.0_21\jre\lib\ext\localedata.jar;
C:\Program Files\Java\jdk1.6.0_21\jre\lib\ext\sunjce_provider.jar;
C:\Program Files\Java\jdk1.6.0_21\jre\lib\ext\sunmscapi.jar;
C:\Program Files\Java\jdk1.6.0_21\jre\lib\ext\sunpkcs11.jar
C:\MVN\consumerBanking\target\classes;
C:\Program Files\JetBrains\
IntelliJ IDEA Community Edition 11.1.2\lib\idea_rt.jar"
com.intellij.rt.execution.application.AppMain com.companyname.bank.App
Hello World!
Process finished with exit code 0
34 Lectures
4 hours
Karthikeya T
14 Lectures
1.5 hours
Quaatso Learning
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2173,
"s": 2060,
"text": "IntelliJ IDEA has in-built support for Maven. We are using IntelliJ IDEA Community Edition 11.1 in this example."
},
{
"code": null,
"e": 2230,
"s": 2173,
"text": "Some of the features of IntelliJ IDEA are listed below −"
},
{
"code": null,
"e": 2274,
"s": 2230,
"text": "You can run Maven goals from IntelliJ IDEA."
},
{
"code": null,
"e": 2318,
"s": 2274,
"text": "You can run Maven goals from IntelliJ IDEA."
},
{
"code": null,
"e": 2408,
"s": 2318,
"text": "You can view the output of Maven commands inside the IntelliJ IDEA using its own console."
},
{
"code": null,
"e": 2498,
"s": 2408,
"text": "You can view the output of Maven commands inside the IntelliJ IDEA using its own console."
},
{
"code": null,
"e": 2544,
"s": 2498,
"text": "You can update maven dependencies within IDE."
},
{
"code": null,
"e": 2590,
"s": 2544,
"text": "You can update maven dependencies within IDE."
},
{
"code": null,
"e": 2645,
"s": 2590,
"text": "You can Launch Maven builds from within IntelliJ IDEA."
},
{
"code": null,
"e": 2700,
"s": 2645,
"text": "You can Launch Maven builds from within IntelliJ IDEA."
},
{
"code": null,
"e": 2785,
"s": 2700,
"text": "IntelliJ IDEA does the dependency management automatically based on Maven's pom.xml."
},
{
"code": null,
"e": 2870,
"s": 2785,
"text": "IntelliJ IDEA does the dependency management automatically based on Maven's pom.xml."
},
{
"code": null,
"e": 3028,
"s": 2870,
"text": "IntelliJ IDEA resolves Maven dependencies from its workspace without installing to local Maven repository (requires dependency project be in same workspace)."
},
{
"code": null,
"e": 3186,
"s": 3028,
"text": "IntelliJ IDEA resolves Maven dependencies from its workspace without installing to local Maven repository (requires dependency project be in same workspace)."
},
{
"code": null,
"e": 3298,
"s": 3186,
"text": "IntelliJ IDEA automatically downloads the required dependencies and sources from the remote Maven repositories."
},
{
"code": null,
"e": 3410,
"s": 3298,
"text": "IntelliJ IDEA automatically downloads the required dependencies and sources from the remote Maven repositories."
},
{
"code": null,
"e": 3483,
"s": 3410,
"text": "IntelliJ IDEA provides wizards for creating new Maven projects, pom.xml."
},
{
"code": null,
"e": 3556,
"s": 3483,
"text": "IntelliJ IDEA provides wizards for creating new Maven projects, pom.xml."
},
{
"code": null,
"e": 3649,
"s": 3556,
"text": "Following example will help you to leverage benefits of integrating IntelliJ IDEA and Maven."
},
{
"code": null,
"e": 3704,
"s": 3649,
"text": "We will import Maven project using New Project Wizard."
},
{
"code": null,
"e": 3724,
"s": 3704,
"text": "Open IntelliJ IDEA."
},
{
"code": null,
"e": 3744,
"s": 3724,
"text": "Open IntelliJ IDEA."
},
{
"code": null,
"e": 3783,
"s": 3744,
"text": "Select File Menu > New Project Option."
},
{
"code": null,
"e": 3822,
"s": 3783,
"text": "Select File Menu > New Project Option."
},
{
"code": null,
"e": 3865,
"s": 3822,
"text": "Select import project from existing model."
},
{
"code": null,
"e": 3908,
"s": 3865,
"text": "Select import project from existing model."
},
{
"code": null,
"e": 3928,
"s": 3908,
"text": "Select Maven option"
},
{
"code": null,
"e": 4125,
"s": 3928,
"text": "Select Project location, where a project was created using Maven. We have created a Java Project consumerBanking. Go to ‘Creating Java Project' chapter, to see how to create a project using Maven."
},
{
"code": null,
"e": 4322,
"s": 4125,
"text": "Select Project location, where a project was created using Maven. We have created a Java Project consumerBanking. Go to ‘Creating Java Project' chapter, to see how to create a project using Maven."
},
{
"code": null,
"e": 4354,
"s": 4322,
"text": "Select Maven project to import."
},
{
"code": null,
"e": 4398,
"s": 4354,
"text": "Enter name of the project and click finish."
},
{
"code": null,
"e": 4609,
"s": 4398,
"text": "Now, you can see the maven project in IntelliJ IDEA. Have a look at consumerBanking project external libraries. You can see that IntelliJ IDEA has added Maven dependencies to its build path under Maven section."
},
{
"code": null,
"e": 4820,
"s": 4609,
"text": "Now, you can see the maven project in IntelliJ IDEA. Have a look at consumerBanking project external libraries. You can see that IntelliJ IDEA has added Maven dependencies to its build path under Maven section."
},
{
"code": null,
"e": 4893,
"s": 4820,
"text": "Now, it is time to build this project using capability of IntelliJ IDEA."
},
{
"code": null,
"e": 4925,
"s": 4893,
"text": "Select consumerBanking project."
},
{
"code": null,
"e": 4957,
"s": 4925,
"text": "Select consumerBanking project."
},
{
"code": null,
"e": 4999,
"s": 4957,
"text": "Select Buid menu > Rebuild Project Option"
},
{
"code": null,
"e": 5041,
"s": 4999,
"text": "Select Buid menu > Rebuild Project Option"
},
{
"code": null,
"e": 5089,
"s": 5041,
"text": "You can see the output in IntelliJ IDEA Console"
},
{
"code": null,
"e": 5136,
"s": 5089,
"text": "4:01:56 PM Compilation completed successfully\n"
},
{
"code": null,
"e": 5168,
"s": 5136,
"text": "Select consumerBanking project."
},
{
"code": null,
"e": 5200,
"s": 5168,
"text": "Select consumerBanking project."
},
{
"code": null,
"e": 5246,
"s": 5200,
"text": "Right click on App.java to open context menu."
},
{
"code": null,
"e": 5292,
"s": 5246,
"text": "Right click on App.java to open context menu."
},
{
"code": null,
"e": 5314,
"s": 5292,
"text": "select Run App.main()"
},
{
"code": null,
"e": 5336,
"s": 5314,
"text": "select Run App.main()"
},
{
"code": null,
"e": 5386,
"s": 5336,
"text": "You will see the result in IntelliJ IDEA Console."
},
{
"code": null,
"e": 6636,
"s": 5386,
"text": "\"C:\\Program Files\\Java\\jdk1.6.0_21\\bin\\java\"\n-Didea.launcher.port=7533 \n\"-Didea.launcher.bin.path=\nC:\\Program Files\\JetBrains\\IntelliJ IDEA Community Edition 11.1.2\\bin\"\n-Dfile.encoding=UTF-8 \n-classpath \"C:\\Program Files\\Java\\jdk1.6.0_21\\jre\\lib\\charsets.jar;\n\nC:\\Program Files\\Java\\jdk1.6.0_21\\jre\\lib\\deploy.jar;\nC:\\Program Files\\Java\\jdk1.6.0_21\\jre\\lib\\javaws.jar;\nC:\\Program Files\\Java\\jdk1.6.0_21\\jre\\lib\\jce.jar;\nC:\\Program Files\\Java\\jdk1.6.0_21\\jre\\lib\\jsse.jar;\nC:\\Program Files\\Java\\jdk1.6.0_21\\jre\\lib\\management-agent.jar;\nC:\\Program Files\\Java\\jdk1.6.0_21\\jre\\lib\\plugin.jar;\nC:\\Program Files\\Java\\jdk1.6.0_21\\jre\\lib\\resources.jar;\nC:\\Program Files\\Java\\jdk1.6.0_21\\jre\\lib\\rt.jar;\nC:\\Program Files\\Java\\jdk1.6.0_21\\jre\\lib\\ext\\dnsns.jar;\nC:\\Program Files\\Java\\jdk1.6.0_21\\jre\\lib\\ext\\localedata.jar;\nC:\\Program Files\\Java\\jdk1.6.0_21\\jre\\lib\\ext\\sunjce_provider.jar;\nC:\\Program Files\\Java\\jdk1.6.0_21\\jre\\lib\\ext\\sunmscapi.jar;\nC:\\Program Files\\Java\\jdk1.6.0_21\\jre\\lib\\ext\\sunpkcs11.jar\n\nC:\\MVN\\consumerBanking\\target\\classes;\nC:\\Program Files\\JetBrains\\\nIntelliJ IDEA Community Edition 11.1.2\\lib\\idea_rt.jar\" \ncom.intellij.rt.execution.application.AppMain com.companyname.bank.App\nHello World!\n\nProcess finished with exit code 0\n"
},
{
"code": null,
"e": 6669,
"s": 6636,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6683,
"s": 6669,
"text": " Karthikeya T"
},
{
"code": null,
"e": 6718,
"s": 6683,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6736,
"s": 6718,
"text": " Quaatso Learning"
},
{
"code": null,
"e": 6743,
"s": 6736,
"text": " Print"
},
{
"code": null,
"e": 6754,
"s": 6743,
"text": " Add Notes"
}
] |
Spark SQL - Parquet Files | Parquet is a columnar format, supported by many data processing systems. The advantages of having a columnar storage are as follows −
Columnar storage limits IO operations.
Columnar storage limits IO operations.
Columnar storage can fetch specific columns that you need to access.
Columnar storage can fetch specific columns that you need to access.
Columnar storage consumes less space.
Columnar storage consumes less space.
Columnar storage gives better-summarized data and follows type-specific encoding.
Columnar storage gives better-summarized data and follows type-specific encoding.
Spark SQL provides support for both reading and writing parquet files that automatically capture the schema of the original data. Like JSON datasets, parquet files follow the same procedure.
Let’s take another look at the same example of employee record data named employee.parquet placed in the same directory where spark-shell is running.
Given data − Do not bother about converting the input data of employee records into parquet format. We use the following commands that convert the RDD data into Parquet file. Place the employee.json document, which we have used as the input file in our previous examples.
$ spark-shell
Scala> val sqlContext = new org.apache.spark.sql.SQLContext(sc)
Scala> val employee = sqlContext.read.json(“emplaoyee”)
Scala> employee.write.parquet(“employee.parquet”)
It is not possible to show you the parquet file. It is a directory structure, which you can find in the current directory. If you want to see the directory and file structure, use the following command.
$ cd employee.parquet/
$ ls
_common_metadata
Part-r-00001.gz.parquet
_metadata
_SUCCESS
The following commands are used for reading, registering into table, and applying some queries on it.
Start the Spark shell using following example
$ spark-shell
Generate SQLContext using the following command. Here, sc means SparkContext object.
scala> val sqlContext = new org.apache.spark.sql.SQLContext(sc)
Create an RDD DataFrame by reading a data from the parquet file named employee.parquet using the following statement.
scala> val parqfile = sqlContext.read.parquet(“employee.parquet”)
Use the following command for storing the DataFrame data into a table named employee. After this command, we can apply all types of SQL statements into it.
scala> Parqfile.registerTempTable(“employee”)
The employee table is ready. Let us now pass some SQL queries on the table using the method SQLContext.sql().
Use the following command for selecting all records from the employee table. Here, we use the variable allrecords for capturing all records data. To display those records, call show() method on it.
scala> val allrecords = sqlContext.sql("SELeCT * FROM employee")
To see the result data of allrecords DataFrame, use the following command.
scala> allrecords.show()
+------+--------+----+
| id | name |age |
+------+--------+----+
| 1201 | satish | 25 |
| 1202 | krishna| 28 |
| 1203 | amith | 39 |
| 1204 | javed | 23 |
| 1205 | prudvi | 23 |
+------+--------+----+
46 Lectures
3.5 hours
Arnab Chakraborty
31 Lectures
1 hours
Frahaan Hussain
12 Lectures
1 hours
Pranjal Srivastava
23 Lectures
1.5 hours
Mukund Kumar Mishra
52 Lectures
1.5 hours
Bigdata Engineer
23 Lectures
1 hours
Bigdata Engineer
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1854,
"s": 1720,
"text": "Parquet is a columnar format, supported by many data processing systems. The advantages of having a columnar storage are as follows −"
},
{
"code": null,
"e": 1893,
"s": 1854,
"text": "Columnar storage limits IO operations."
},
{
"code": null,
"e": 1932,
"s": 1893,
"text": "Columnar storage limits IO operations."
},
{
"code": null,
"e": 2001,
"s": 1932,
"text": "Columnar storage can fetch specific columns that you need to access."
},
{
"code": null,
"e": 2070,
"s": 2001,
"text": "Columnar storage can fetch specific columns that you need to access."
},
{
"code": null,
"e": 2108,
"s": 2070,
"text": "Columnar storage consumes less space."
},
{
"code": null,
"e": 2146,
"s": 2108,
"text": "Columnar storage consumes less space."
},
{
"code": null,
"e": 2228,
"s": 2146,
"text": "Columnar storage gives better-summarized data and follows type-specific encoding."
},
{
"code": null,
"e": 2310,
"s": 2228,
"text": "Columnar storage gives better-summarized data and follows type-specific encoding."
},
{
"code": null,
"e": 2501,
"s": 2310,
"text": "Spark SQL provides support for both reading and writing parquet files that automatically capture the schema of the original data. Like JSON datasets, parquet files follow the same procedure."
},
{
"code": null,
"e": 2651,
"s": 2501,
"text": "Let’s take another look at the same example of employee record data named employee.parquet placed in the same directory where spark-shell is running."
},
{
"code": null,
"e": 2923,
"s": 2651,
"text": "Given data − Do not bother about converting the input data of employee records into parquet format. We use the following commands that convert the RDD data into Parquet file. Place the employee.json document, which we have used as the input file in our previous examples."
},
{
"code": null,
"e": 3108,
"s": 2923,
"text": "$ spark-shell\nScala> val sqlContext = new org.apache.spark.sql.SQLContext(sc)\nScala> val employee = sqlContext.read.json(“emplaoyee”)\nScala> employee.write.parquet(“employee.parquet”)\n"
},
{
"code": null,
"e": 3311,
"s": 3108,
"text": "It is not possible to show you the parquet file. It is a directory structure, which you can find in the current directory. If you want to see the directory and file structure, use the following command."
},
{
"code": null,
"e": 3401,
"s": 3311,
"text": "$ cd employee.parquet/\n\n$ ls\n_common_metadata\nPart-r-00001.gz.parquet\n_metadata\n_SUCCESS\n"
},
{
"code": null,
"e": 3503,
"s": 3401,
"text": "The following commands are used for reading, registering into table, and applying some queries on it."
},
{
"code": null,
"e": 3549,
"s": 3503,
"text": "Start the Spark shell using following example"
},
{
"code": null,
"e": 3564,
"s": 3549,
"text": "$ spark-shell\n"
},
{
"code": null,
"e": 3649,
"s": 3564,
"text": "Generate SQLContext using the following command. Here, sc means SparkContext object."
},
{
"code": null,
"e": 3714,
"s": 3649,
"text": "scala> val sqlContext = new org.apache.spark.sql.SQLContext(sc)\n"
},
{
"code": null,
"e": 3832,
"s": 3714,
"text": "Create an RDD DataFrame by reading a data from the parquet file named employee.parquet using the following statement."
},
{
"code": null,
"e": 3899,
"s": 3832,
"text": "scala> val parqfile = sqlContext.read.parquet(“employee.parquet”)\n"
},
{
"code": null,
"e": 4055,
"s": 3899,
"text": "Use the following command for storing the DataFrame data into a table named employee. After this command, we can apply all types of SQL statements into it."
},
{
"code": null,
"e": 4102,
"s": 4055,
"text": "scala> Parqfile.registerTempTable(“employee”)\n"
},
{
"code": null,
"e": 4212,
"s": 4102,
"text": "The employee table is ready. Let us now pass some SQL queries on the table using the method SQLContext.sql()."
},
{
"code": null,
"e": 4410,
"s": 4212,
"text": "Use the following command for selecting all records from the employee table. Here, we use the variable allrecords for capturing all records data. To display those records, call show() method on it."
},
{
"code": null,
"e": 4476,
"s": 4410,
"text": "scala> val allrecords = sqlContext.sql(\"SELeCT * FROM employee\")\n"
},
{
"code": null,
"e": 4551,
"s": 4476,
"text": "To see the result data of allrecords DataFrame, use the following command."
},
{
"code": null,
"e": 4577,
"s": 4551,
"text": "scala> allrecords.show()\n"
},
{
"code": null,
"e": 4785,
"s": 4577,
"text": "+------+--------+----+\n| id | name |age |\n+------+--------+----+\n| 1201 | satish | 25 |\n| 1202 | krishna| 28 |\n| 1203 | amith | 39 |\n| 1204 | javed | 23 |\n| 1205 | prudvi | 23 |\n+------+--------+----+\n"
},
{
"code": null,
"e": 4820,
"s": 4785,
"text": "\n 46 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4839,
"s": 4820,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4872,
"s": 4839,
"text": "\n 31 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4889,
"s": 4872,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4922,
"s": 4889,
"text": "\n 12 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4942,
"s": 4922,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 4977,
"s": 4942,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4998,
"s": 4977,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 5033,
"s": 4998,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5051,
"s": 5033,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 5084,
"s": 5051,
"text": "\n 23 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5102,
"s": 5084,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 5109,
"s": 5102,
"text": " Print"
},
{
"code": null,
"e": 5120,
"s": 5109,
"text": " Add Notes"
}
] |
Deploy Sci-kit Learn models in .NET Core Applications | by George Novack | Towards Data Science | One frequent pain point for organizations trying to deliver ML models to Production is the discrepancy between the tools and technologies used by Data Scientists and those used by Application Developers. Data Scientists will most likely work in Python, using Machine Learning frameworks like Sci-kit Learn, Tensorflow, or PyTorch to build and train their models, while Application Developers will often use programming languages like Java, C#, or JavaScript to build enterprise applications, leveraging popular Web Application frameworks like Spring or ASP.NET Core.
There are many ways to bridge this gap. A couple of the most common approaches are:
Have the Data Scientist send the model’s trained parameters to the Application Developer, who then must rewrite the model using the language of the web application where the model will be used.Develop a separate suite of web applications to host the deployed models using a Python web framework like Flask or Django.
Have the Data Scientist send the model’s trained parameters to the Application Developer, who then must rewrite the model using the language of the web application where the model will be used.
Develop a separate suite of web applications to host the deployed models using a Python web framework like Flask or Django.
Neither of these is ideal. With the first approach, the manual rewrite step leads to slower cycle times, duplication of logic, and an increase in the probability of human error. The second approach, while more appealing than the first, is still not great, as it hinders the ability to share development patterns, libraries, and core logic (such as security, logging, or common integration logic) across all applications.
In this article, we’ll look at a better way to bridge the technology gap between Data Scientists and App Developers using the ONNX Model format and the ONNX Runtime. Specifically, we’ll show how you can build and train a model using Sci-kit Learn, then use that same model to perform real-time inference in a .NET Core Web API.
Open Neural Network Exchange, or ONNX, is an open ML model format, similar to the Pickle format often used to save and load Sci-kit Learn models, or the SavedModel format for Tensorflow models. ONNX, however, is framework-agnostic, meaning you can produce ONNX format models from just about any popular Machine Learning framework.
In addition to the ONNX model format, we’ll also be using the ONNX Runtime, an open-source runtime that will allow us to run our ONNX model within our .NET Core Application. We’ll be using the C# APIs, but the ONNX Runtime also supports APIs for several other languages, including Python, Java, and Javascript.
You can read more about the ONNX project and the frameworks supported here: https://onnx.ai/
And you can learn more about how to use the ONNX Runtime with different languages and platforms here: https://microsoft.github.io/onnxruntime/
First, we’ll build and train a Sci-kit Learn model using the California Housing Dataset. Nothing special here, just a GradientBoostingRegressor trained to predict the price of a house given a few data points about the neighborhood, such as median income, the average number of bedrooms, and so on.
We’ll need to install the sklearn-onnx library which will allow us to convert the sklearn model into the ONNX format:
pip install skl2onnx
Then we’ll use the convert_sklearn() method to do the conversion:
The initial_types parameter defines the dimensions and data types of the model input. This model takes 8 inputs of type float. The None in the input dimension [None,8] indicates an unknown batch size.
Note: There are some limitations for converting Scikit-learn models to ONNX format. You can find details about these limitations and the sklearn-onnx library here: http://onnx.ai/sklearn-onnx/
Now for the ASP.NET Core application that will use our ONNX model and expose it as a REST API endpoint, enabling real-time inference as a service. We’ll create an empty ASP.NET Core Web API using the dotnet command-line tool:
dotnet new webapi
Next, we’ll install the Microsoft.ML.OnnxRuntime NuGet package which will allow us to load and score the ONNX model within the .NET Core application:
dotnet add package Microsoft.ML.OnnxRuntime
Before we can score the model, we need to start an InferenceSession and load the model object into memory. Add the following line to the ConfigureServices method in Startup.cs:
If you’re not familiar with ASP.NET Core or dependency injection, the above line is simply creating a singleton instance of typeInferenceSession and adding it to the application’s Service Container. This means that the Inference Session will be created only once when the application starts up, and that the same Session will be reused by subsequent calls to the inference API endpoint we’ll create shortly.
You can find more in-depth information about the Service Container, service lifetimes, and dependency injection in general here: Dependency Injection in ASP.NET Core
Notice that in the code above, we’re loading the .onnx model file in from the local filesystem. While this works fine for our example, in a production application you’d probably be better off downloading the model object from an external model repository/registry such as MLFlow in order to separate version control of the ML model from that of the application.
Now that the application knows how to load our ONNX model into memory, we can create an API Controller class, which, in ASP.NET Core applications, is simply a class that defines the API endpoints that will be exposed by our application.
Here’s the Controller class for the inference endpoint:
A few notes about the above class:
The [Route("/score")] attribute specifies that we can make requests to this controller’s endpoints via the route /score
Notice that the class’s constructor accepts an object of type InferenceSession as a parameter. When the application starts, it will create an instance of our controller class, passing in the singleton instance of InferenceSession that we defined earlier in Startup.cs.
The actual scoring of our model on the inputs happens when we call _session.Run()
The classes HousingData and Prediction are simple data classes used to represent the request and response bodies, respectively. We’ll define both below.
Here is the HousingData class that represents the JSON body of the incoming API request to our endpoint. In addition to the object’s properties, we’ve also defined an AsTensor() method that converts the HousingData object into an object of type Tensor<float> so that we can pass it into our ONNX model:
And here is the Prediction class that defines the structure of the response with which our API endpoint will reply:
And that’s it. We’re now ready to run our ASP.NET Core Web API and test out our inference endpoint. Use the dotnet run command at the root of the project to start the application. You should see a line like this in the output indicating which port the application is listening on:
Now listening on: http://[::]:80
Now that the app is up and running, you can use your favorite tool for making API requests (mine is Postman) to send it a request like so:
And there you have it! We’re now able to get predictions from our model in real-time via API requests. Try tweaking the input values and see how the predicted value changes.
Thanks for reading. In this article, we’ve seen how to use the ONNX model format and the ONNX Runtime to streamline the process of integrating ML models into production applications. While the examples shown were specific to Scikit-Learn and C#, the flexibility of ONNX and the ONNX Runtime allows us to mix and match various Machine Learning Frameworks and technology stacks (e.g. Scikit-learn & Javascript, Tensorflow & Java, and so on).
You can find a repository containing all of the example code for training and inference here: https://github.com/gnovack/sklearn-dotnet
http://onnx.ai/sklearn-onnx/tutorial.html
https://github.com/microsoft/onnxruntime/blob/master/docs/CSharp_API.md#getting-started
Feel free to leave any questions or comments below. Thanks! | [
{
"code": null,
"e": 613,
"s": 46,
"text": "One frequent pain point for organizations trying to deliver ML models to Production is the discrepancy between the tools and technologies used by Data Scientists and those used by Application Developers. Data Scientists will most likely work in Python, using Machine Learning frameworks like Sci-kit Learn, Tensorflow, or PyTorch to build and train their models, while Application Developers will often use programming languages like Java, C#, or JavaScript to build enterprise applications, leveraging popular Web Application frameworks like Spring or ASP.NET Core."
},
{
"code": null,
"e": 697,
"s": 613,
"text": "There are many ways to bridge this gap. A couple of the most common approaches are:"
},
{
"code": null,
"e": 1014,
"s": 697,
"text": "Have the Data Scientist send the model’s trained parameters to the Application Developer, who then must rewrite the model using the language of the web application where the model will be used.Develop a separate suite of web applications to host the deployed models using a Python web framework like Flask or Django."
},
{
"code": null,
"e": 1208,
"s": 1014,
"text": "Have the Data Scientist send the model’s trained parameters to the Application Developer, who then must rewrite the model using the language of the web application where the model will be used."
},
{
"code": null,
"e": 1332,
"s": 1208,
"text": "Develop a separate suite of web applications to host the deployed models using a Python web framework like Flask or Django."
},
{
"code": null,
"e": 1753,
"s": 1332,
"text": "Neither of these is ideal. With the first approach, the manual rewrite step leads to slower cycle times, duplication of logic, and an increase in the probability of human error. The second approach, while more appealing than the first, is still not great, as it hinders the ability to share development patterns, libraries, and core logic (such as security, logging, or common integration logic) across all applications."
},
{
"code": null,
"e": 2081,
"s": 1753,
"text": "In this article, we’ll look at a better way to bridge the technology gap between Data Scientists and App Developers using the ONNX Model format and the ONNX Runtime. Specifically, we’ll show how you can build and train a model using Sci-kit Learn, then use that same model to perform real-time inference in a .NET Core Web API."
},
{
"code": null,
"e": 2412,
"s": 2081,
"text": "Open Neural Network Exchange, or ONNX, is an open ML model format, similar to the Pickle format often used to save and load Sci-kit Learn models, or the SavedModel format for Tensorflow models. ONNX, however, is framework-agnostic, meaning you can produce ONNX format models from just about any popular Machine Learning framework."
},
{
"code": null,
"e": 2723,
"s": 2412,
"text": "In addition to the ONNX model format, we’ll also be using the ONNX Runtime, an open-source runtime that will allow us to run our ONNX model within our .NET Core Application. We’ll be using the C# APIs, but the ONNX Runtime also supports APIs for several other languages, including Python, Java, and Javascript."
},
{
"code": null,
"e": 2816,
"s": 2723,
"text": "You can read more about the ONNX project and the frameworks supported here: https://onnx.ai/"
},
{
"code": null,
"e": 2959,
"s": 2816,
"text": "And you can learn more about how to use the ONNX Runtime with different languages and platforms here: https://microsoft.github.io/onnxruntime/"
},
{
"code": null,
"e": 3257,
"s": 2959,
"text": "First, we’ll build and train a Sci-kit Learn model using the California Housing Dataset. Nothing special here, just a GradientBoostingRegressor trained to predict the price of a house given a few data points about the neighborhood, such as median income, the average number of bedrooms, and so on."
},
{
"code": null,
"e": 3375,
"s": 3257,
"text": "We’ll need to install the sklearn-onnx library which will allow us to convert the sklearn model into the ONNX format:"
},
{
"code": null,
"e": 3396,
"s": 3375,
"text": "pip install skl2onnx"
},
{
"code": null,
"e": 3462,
"s": 3396,
"text": "Then we’ll use the convert_sklearn() method to do the conversion:"
},
{
"code": null,
"e": 3663,
"s": 3462,
"text": "The initial_types parameter defines the dimensions and data types of the model input. This model takes 8 inputs of type float. The None in the input dimension [None,8] indicates an unknown batch size."
},
{
"code": null,
"e": 3856,
"s": 3663,
"text": "Note: There are some limitations for converting Scikit-learn models to ONNX format. You can find details about these limitations and the sklearn-onnx library here: http://onnx.ai/sklearn-onnx/"
},
{
"code": null,
"e": 4082,
"s": 3856,
"text": "Now for the ASP.NET Core application that will use our ONNX model and expose it as a REST API endpoint, enabling real-time inference as a service. We’ll create an empty ASP.NET Core Web API using the dotnet command-line tool:"
},
{
"code": null,
"e": 4100,
"s": 4082,
"text": "dotnet new webapi"
},
{
"code": null,
"e": 4250,
"s": 4100,
"text": "Next, we’ll install the Microsoft.ML.OnnxRuntime NuGet package which will allow us to load and score the ONNX model within the .NET Core application:"
},
{
"code": null,
"e": 4294,
"s": 4250,
"text": "dotnet add package Microsoft.ML.OnnxRuntime"
},
{
"code": null,
"e": 4471,
"s": 4294,
"text": "Before we can score the model, we need to start an InferenceSession and load the model object into memory. Add the following line to the ConfigureServices method in Startup.cs:"
},
{
"code": null,
"e": 4879,
"s": 4471,
"text": "If you’re not familiar with ASP.NET Core or dependency injection, the above line is simply creating a singleton instance of typeInferenceSession and adding it to the application’s Service Container. This means that the Inference Session will be created only once when the application starts up, and that the same Session will be reused by subsequent calls to the inference API endpoint we’ll create shortly."
},
{
"code": null,
"e": 5045,
"s": 4879,
"text": "You can find more in-depth information about the Service Container, service lifetimes, and dependency injection in general here: Dependency Injection in ASP.NET Core"
},
{
"code": null,
"e": 5407,
"s": 5045,
"text": "Notice that in the code above, we’re loading the .onnx model file in from the local filesystem. While this works fine for our example, in a production application you’d probably be better off downloading the model object from an external model repository/registry such as MLFlow in order to separate version control of the ML model from that of the application."
},
{
"code": null,
"e": 5644,
"s": 5407,
"text": "Now that the application knows how to load our ONNX model into memory, we can create an API Controller class, which, in ASP.NET Core applications, is simply a class that defines the API endpoints that will be exposed by our application."
},
{
"code": null,
"e": 5700,
"s": 5644,
"text": "Here’s the Controller class for the inference endpoint:"
},
{
"code": null,
"e": 5735,
"s": 5700,
"text": "A few notes about the above class:"
},
{
"code": null,
"e": 5855,
"s": 5735,
"text": "The [Route(\"/score\")] attribute specifies that we can make requests to this controller’s endpoints via the route /score"
},
{
"code": null,
"e": 6124,
"s": 5855,
"text": "Notice that the class’s constructor accepts an object of type InferenceSession as a parameter. When the application starts, it will create an instance of our controller class, passing in the singleton instance of InferenceSession that we defined earlier in Startup.cs."
},
{
"code": null,
"e": 6206,
"s": 6124,
"text": "The actual scoring of our model on the inputs happens when we call _session.Run()"
},
{
"code": null,
"e": 6359,
"s": 6206,
"text": "The classes HousingData and Prediction are simple data classes used to represent the request and response bodies, respectively. We’ll define both below."
},
{
"code": null,
"e": 6662,
"s": 6359,
"text": "Here is the HousingData class that represents the JSON body of the incoming API request to our endpoint. In addition to the object’s properties, we’ve also defined an AsTensor() method that converts the HousingData object into an object of type Tensor<float> so that we can pass it into our ONNX model:"
},
{
"code": null,
"e": 6778,
"s": 6662,
"text": "And here is the Prediction class that defines the structure of the response with which our API endpoint will reply:"
},
{
"code": null,
"e": 7059,
"s": 6778,
"text": "And that’s it. We’re now ready to run our ASP.NET Core Web API and test out our inference endpoint. Use the dotnet run command at the root of the project to start the application. You should see a line like this in the output indicating which port the application is listening on:"
},
{
"code": null,
"e": 7092,
"s": 7059,
"text": "Now listening on: http://[::]:80"
},
{
"code": null,
"e": 7231,
"s": 7092,
"text": "Now that the app is up and running, you can use your favorite tool for making API requests (mine is Postman) to send it a request like so:"
},
{
"code": null,
"e": 7405,
"s": 7231,
"text": "And there you have it! We’re now able to get predictions from our model in real-time via API requests. Try tweaking the input values and see how the predicted value changes."
},
{
"code": null,
"e": 7845,
"s": 7405,
"text": "Thanks for reading. In this article, we’ve seen how to use the ONNX model format and the ONNX Runtime to streamline the process of integrating ML models into production applications. While the examples shown were specific to Scikit-Learn and C#, the flexibility of ONNX and the ONNX Runtime allows us to mix and match various Machine Learning Frameworks and technology stacks (e.g. Scikit-learn & Javascript, Tensorflow & Java, and so on)."
},
{
"code": null,
"e": 7981,
"s": 7845,
"text": "You can find a repository containing all of the example code for training and inference here: https://github.com/gnovack/sklearn-dotnet"
},
{
"code": null,
"e": 8023,
"s": 7981,
"text": "http://onnx.ai/sklearn-onnx/tutorial.html"
},
{
"code": null,
"e": 8111,
"s": 8023,
"text": "https://github.com/microsoft/onnxruntime/blob/master/docs/CSharp_API.md#getting-started"
}
] |
Display all grants for user in MySQL | Use INFORMATION_SCHEMA.SCHEMA_PRIVILEGES to display all grants for a user −
select *from INFORMATION_SCHEMA.SCHEMA_PRIVILEGES;
Let us implement the above syntax to show all grants for a user −
mysql> select *from INFORMATION_SCHEMA.SCHEMA_PRIVILEGES;
This will produce the following output −
+-----------------------------+---------------+--------------------+-------------------------+--------------+
| GRANTEE | TABLE_CATALOG | TABLE_SCHEMA | PRIVILEGE_TYPE | IS_GRANTABLE |
+-----------------------------+---------------+--------------------+-------------------------+--------------+
| 'mysql.sys'@'localhost' | def | sys | TRIGGER | NO |
| 'Adam Smith'@'localhost' | def | test | SELECT | NO |
| 'Adam Smith'@'localhost' | def | test | INSERT | NO |
| 'Adam Smith'@'localhost' | def | test | UPDATE | NO |
| 'Adam Smith'@'localhost' | def | test | DELETE | NO |
| 'Adam Smith'@'localhost' | def | test | CREATE | NO |
| 'Adam Smith'@'localhost' | def | test | DROP | NO |
| 'Adam Smith'@'localhost' | def | test | REFERENCES | NO |
| 'Adam Smith'@'localhost' | def | test | INDEX | NO |
| 'Adam Smith'@'localhost' | def | test | ALTER | NO |
| 'Adam Smith'@'localhost' | def | test | CREATE TEMPORARY TABLES | NO |
| 'Adam Smith'@'localhost' | def | test | LOCK TABLES | NO |
| 'Adam Smith'@'localhost' | def | test | EXECUTE | NO |
| 'Adam Smith'@'localhost' | def | test | CREATE VIEW | NO |
| 'Adam Smith'@'localhost' | def | test | SHOW VIEW | NO |
| 'Adam Smith'@'localhost' | def | test | CREATE ROUTINE | NO |
| 'Adam Smith'@'localhost' | def | test | ALTER ROUTINE | NO |
| 'Adam Smith'@'localhost' | def | test | EVENT | NO |
| 'Adam Smith'@'localhost' | def | test | TRIGGER | NO |
| 'David'@'localhost' | def | test | SELECT | NO |
| 'David'@'localhost' | def | test | INSERT | NO |
| 'David'@'localhost' | def | test | UPDATE | NO |
| 'David'@'localhost' | def | test | DELETE | NO |
| 'David'@'localhost' | def | test | CREATE | NO |
| 'David'@'localhost' | def | test | REFERENCES | NO |
| 'David'@'localhost' | def | test | ALTER | NO |
| 'mysql.session'@'localhost' | def | performance_schema | SELECT | NO |
| 'Robert'@'%' | def | sample | SELECT | YES |
| 'Robert'@'%' | def | sample | INSERT | YES |
| 'Robert'@'%' | def | sample | UPDATE | YES |
| 'Robert'@'%' | def | sample | DELETE | YES |
| 'Robert'@'%' | def | sample | CREATE | YES |
| 'Robert'@'%' | def | sample | DROP | YES |
| 'Robert'@'%' | def | sample | REFERENCES | YES |
| 'Robert'@'%' | def | sample | INDEX | YES |
| 'Robert'@'%' | def | sample | ALTER | YES |
| 'Robert'@'%' | def | sample | CREATE TEMPORARY TABLES | YES |
| 'Robert'@'%' | def | sample | LOCK TABLES | YES |
| 'Robert'@'%' | def | sample | EXECUTE | YES |
| 'Robert'@'%' | def | sample | CREATE VIEW | YES |
| 'Robert'@'%' | def | sample | SHOW VIEW | YES |
| 'Robert'@'%' | def | sample | CREATE ROUTINE | YES |
| 'Robert'@'%' | def | sample | ALTER ROUTINE | YES |
| 'Robert'@'%' | def | sample | EVENT | YES |
| 'Robert'@'%' | def | sample | TRIGGER | YES |
| 'Robert'@'%' | def | web | EXECUTE | NO |
+-----------------------------+---------------+--------------------+-------------------------+--------------+
46 rows in set (0.00 sec) | [
{
"code": null,
"e": 1138,
"s": 1062,
"text": "Use INFORMATION_SCHEMA.SCHEMA_PRIVILEGES to display all grants for a user −"
},
{
"code": null,
"e": 1189,
"s": 1138,
"text": "select *from INFORMATION_SCHEMA.SCHEMA_PRIVILEGES;"
},
{
"code": null,
"e": 1255,
"s": 1189,
"text": "Let us implement the above syntax to show all grants for a user −"
},
{
"code": null,
"e": 1313,
"s": 1255,
"text": "mysql> select *from INFORMATION_SCHEMA.SCHEMA_PRIVILEGES;"
},
{
"code": null,
"e": 1354,
"s": 1313,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 6880,
"s": 1354,
"text": "+-----------------------------+---------------+--------------------+-------------------------+--------------+\n| GRANTEE | TABLE_CATALOG | TABLE_SCHEMA | PRIVILEGE_TYPE | IS_GRANTABLE |\n+-----------------------------+---------------+--------------------+-------------------------+--------------+\n| 'mysql.sys'@'localhost' | def | sys | TRIGGER | NO |\n| 'Adam Smith'@'localhost' | def | test | SELECT | NO |\n| 'Adam Smith'@'localhost' | def | test | INSERT | NO |\n| 'Adam Smith'@'localhost' | def | test | UPDATE | NO |\n| 'Adam Smith'@'localhost' | def | test | DELETE | NO |\n| 'Adam Smith'@'localhost' | def | test | CREATE | NO |\n| 'Adam Smith'@'localhost' | def | test | DROP | NO |\n| 'Adam Smith'@'localhost' | def | test | REFERENCES | NO |\n| 'Adam Smith'@'localhost' | def | test | INDEX | NO |\n| 'Adam Smith'@'localhost' | def | test | ALTER | NO |\n| 'Adam Smith'@'localhost' | def | test | CREATE TEMPORARY TABLES | NO |\n| 'Adam Smith'@'localhost' | def | test | LOCK TABLES | NO |\n| 'Adam Smith'@'localhost' | def | test | EXECUTE | NO |\n| 'Adam Smith'@'localhost' | def | test | CREATE VIEW | NO |\n| 'Adam Smith'@'localhost' | def | test | SHOW VIEW | NO |\n| 'Adam Smith'@'localhost' | def | test | CREATE ROUTINE | NO |\n| 'Adam Smith'@'localhost' | def | test | ALTER ROUTINE | NO |\n| 'Adam Smith'@'localhost' | def | test | EVENT | NO |\n| 'Adam Smith'@'localhost' | def | test | TRIGGER | NO |\n| 'David'@'localhost' | def | test | SELECT | NO |\n| 'David'@'localhost' | def | test | INSERT | NO |\n| 'David'@'localhost' | def | test | UPDATE | NO |\n| 'David'@'localhost' | def | test | DELETE | NO |\n| 'David'@'localhost' | def | test | CREATE | NO |\n| 'David'@'localhost' | def | test | REFERENCES | NO |\n| 'David'@'localhost' | def | test | ALTER | NO |\n| 'mysql.session'@'localhost' | def | performance_schema | SELECT | NO |\n| 'Robert'@'%' | def | sample | SELECT | YES |\n| 'Robert'@'%' | def | sample | INSERT | YES |\n| 'Robert'@'%' | def | sample | UPDATE | YES |\n| 'Robert'@'%' | def | sample | DELETE | YES |\n| 'Robert'@'%' | def | sample | CREATE | YES |\n| 'Robert'@'%' | def | sample | DROP | YES |\n| 'Robert'@'%' | def | sample | REFERENCES | YES |\n| 'Robert'@'%' | def | sample | INDEX | YES |\n| 'Robert'@'%' | def | sample | ALTER | YES |\n| 'Robert'@'%' | def | sample | CREATE TEMPORARY TABLES | YES |\n| 'Robert'@'%' | def | sample | LOCK TABLES | YES |\n| 'Robert'@'%' | def | sample | EXECUTE | YES |\n| 'Robert'@'%' | def | sample | CREATE VIEW | YES |\n| 'Robert'@'%' | def | sample | SHOW VIEW | YES |\n| 'Robert'@'%' | def | sample | CREATE ROUTINE | YES |\n| 'Robert'@'%' | def | sample | ALTER ROUTINE | YES |\n| 'Robert'@'%' | def | sample | EVENT | YES |\n| 'Robert'@'%' | def | sample | TRIGGER | YES |\n| 'Robert'@'%' | def | web | EXECUTE | NO |\n+-----------------------------+---------------+--------------------+-------------------------+--------------+\n46 rows in set (0.00 sec)"
}
] |
VB.Net - Program Structure | Before we study basic building blocks of the VB.Net programming language, let us look a bare minimum VB.Net program structure so that we can take it as a reference in upcoming chapters.
A VB.Net program basically consists of the following parts −
Namespace declaration
Namespace declaration
A class or module
A class or module
One or more procedures
One or more procedures
Variables
Variables
The Main procedure
The Main procedure
Statements & Expressions
Statements & Expressions
Comments
Comments
Let us look at a simple code that would print the words "Hello World" −
Imports System
Module Module1
'This program will display Hello World
Sub Main()
Console.WriteLine("Hello World")
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Hello, World!
Let us look various parts of the above program −
The first line of the program Imports System is used to include the System namespace in the program.
The first line of the program Imports System is used to include the System namespace in the program.
The next line has a Module declaration, the module Module1. VB.Net is completely object oriented, so every program must contain a module of a class that contains the data and procedures that your program uses.
The next line has a Module declaration, the module Module1. VB.Net is completely object oriented, so every program must contain a module of a class that contains the data and procedures that your program uses.
Classes or Modules generally would contain more than one procedure. Procedures contain the executable code, or in other words, they define the behavior of the class. A procedure could be any of the following −
Function
Sub
Operator
Get
Set
AddHandler
RemoveHandler
RaiseEvent
Classes or Modules generally would contain more than one procedure. Procedures contain the executable code, or in other words, they define the behavior of the class. A procedure could be any of the following −
Function
Function
Sub
Sub
Operator
Operator
Get
Get
Set
Set
AddHandler
AddHandler
RemoveHandler
RemoveHandler
RaiseEvent
RaiseEvent
The next line( 'This program) will be ignored by the compiler and it has been put to add additional comments in the program.
The next line( 'This program) will be ignored by the compiler and it has been put to add additional comments in the program.
The next line defines the Main procedure, which is the entry point for all VB.Net programs. The Main procedure states what the module or class will do when executed.
The next line defines the Main procedure, which is the entry point for all VB.Net programs. The Main procedure states what the module or class will do when executed.
The Main procedure specifies its behavior with the statement
Console.WriteLine("Hello World") WriteLine is a method of the Console class defined in the System namespace. This statement causes the message "Hello, World!" to be displayed on the screen.
The Main procedure specifies its behavior with the statement
Console.WriteLine("Hello World") WriteLine is a method of the Console class defined in the System namespace. This statement causes the message "Hello, World!" to be displayed on the screen.
The last line Console.ReadKey() is for the VS.NET Users. This will prevent the screen from running and closing quickly when the program is launched from Visual Studio .NET.
The last line Console.ReadKey() is for the VS.NET Users. This will prevent the screen from running and closing quickly when the program is launched from Visual Studio .NET.
If you are using Visual Studio.Net IDE, take the following steps −
Start Visual Studio.
Start Visual Studio.
On the menu bar, choose File → New → Project.
On the menu bar, choose File → New → Project.
Choose Visual Basic from templates
Choose Visual Basic from templates
Choose Console Application.
Choose Console Application.
Specify a name and location for your project using the Browse button, and then choose the OK button.
Specify a name and location for your project using the Browse button, and then choose the OK button.
The new project appears in Solution Explorer.
The new project appears in Solution Explorer.
Write code in the Code Editor.
Write code in the Code Editor.
Click the Run button or the F5 key to run the project. A Command Prompt window appears that contains the line Hello World.
Click the Run button or the F5 key to run the project. A Command Prompt window appears that contains the line Hello World.
You can compile a VB.Net program by using the command line instead of the Visual Studio IDE −
Open a text editor and add the above mentioned code.
Open a text editor and add the above mentioned code.
Save the file as helloworld.vb
Save the file as helloworld.vb
Open the command prompt tool and go to the directory where you saved the file.
Open the command prompt tool and go to the directory where you saved the file.
Type vbc helloworld.vb and press enter to compile your code.
Type vbc helloworld.vb and press enter to compile your code.
If there are no errors in your code the command prompt will take you to the next line and would generate helloworld.exe executable file.
If there are no errors in your code the command prompt will take you to the next line and would generate helloworld.exe executable file.
Next, type helloworld to execute your program.
Next, type helloworld to execute your program.
You will be able to see "Hello World" printed on the screen.
You will be able to see "Hello World" printed on the screen.
63 Lectures
4 hours
Frahaan Hussain
103 Lectures
12 hours
Arnold Higuit
60 Lectures
9.5 hours
Arnold Higuit
97 Lectures
9 hours
Arnold Higuit
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2486,
"s": 2300,
"text": "Before we study basic building blocks of the VB.Net programming language, let us look a bare minimum VB.Net program structure so that we can take it as a reference in upcoming chapters."
},
{
"code": null,
"e": 2547,
"s": 2486,
"text": "A VB.Net program basically consists of the following parts −"
},
{
"code": null,
"e": 2569,
"s": 2547,
"text": "Namespace declaration"
},
{
"code": null,
"e": 2591,
"s": 2569,
"text": "Namespace declaration"
},
{
"code": null,
"e": 2609,
"s": 2591,
"text": "A class or module"
},
{
"code": null,
"e": 2627,
"s": 2609,
"text": "A class or module"
},
{
"code": null,
"e": 2650,
"s": 2627,
"text": "One or more procedures"
},
{
"code": null,
"e": 2673,
"s": 2650,
"text": "One or more procedures"
},
{
"code": null,
"e": 2683,
"s": 2673,
"text": "Variables"
},
{
"code": null,
"e": 2693,
"s": 2683,
"text": "Variables"
},
{
"code": null,
"e": 2712,
"s": 2693,
"text": "The Main procedure"
},
{
"code": null,
"e": 2731,
"s": 2712,
"text": "The Main procedure"
},
{
"code": null,
"e": 2756,
"s": 2731,
"text": "Statements & Expressions"
},
{
"code": null,
"e": 2781,
"s": 2756,
"text": "Statements & Expressions"
},
{
"code": null,
"e": 2790,
"s": 2781,
"text": "Comments"
},
{
"code": null,
"e": 2799,
"s": 2790,
"text": "Comments"
},
{
"code": null,
"e": 2871,
"s": 2799,
"text": "Let us look at a simple code that would print the words \"Hello World\" −"
},
{
"code": null,
"e": 3043,
"s": 2871,
"text": "Imports System\nModule Module1\n 'This program will display Hello World \n Sub Main()\n Console.WriteLine(\"Hello World\")\n Console.ReadKey()\n End Sub\nEnd Module"
},
{
"code": null,
"e": 3124,
"s": 3043,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 3139,
"s": 3124,
"text": "Hello, World!\n"
},
{
"code": null,
"e": 3188,
"s": 3139,
"text": "Let us look various parts of the above program −"
},
{
"code": null,
"e": 3289,
"s": 3188,
"text": "The first line of the program Imports System is used to include the System namespace in the program."
},
{
"code": null,
"e": 3390,
"s": 3289,
"text": "The first line of the program Imports System is used to include the System namespace in the program."
},
{
"code": null,
"e": 3600,
"s": 3390,
"text": "The next line has a Module declaration, the module Module1. VB.Net is completely object oriented, so every program must contain a module of a class that contains the data and procedures that your program uses."
},
{
"code": null,
"e": 3810,
"s": 3600,
"text": "The next line has a Module declaration, the module Module1. VB.Net is completely object oriented, so every program must contain a module of a class that contains the data and procedures that your program uses."
},
{
"code": null,
"e": 4089,
"s": 3810,
"text": "Classes or Modules generally would contain more than one procedure. Procedures contain the executable code, or in other words, they define the behavior of the class. A procedure could be any of the following −\n\nFunction\nSub\nOperator\nGet\nSet\nAddHandler\nRemoveHandler\nRaiseEvent\n\n"
},
{
"code": null,
"e": 4299,
"s": 4089,
"text": "Classes or Modules generally would contain more than one procedure. Procedures contain the executable code, or in other words, they define the behavior of the class. A procedure could be any of the following −"
},
{
"code": null,
"e": 4308,
"s": 4299,
"text": "Function"
},
{
"code": null,
"e": 4317,
"s": 4308,
"text": "Function"
},
{
"code": null,
"e": 4321,
"s": 4317,
"text": "Sub"
},
{
"code": null,
"e": 4325,
"s": 4321,
"text": "Sub"
},
{
"code": null,
"e": 4334,
"s": 4325,
"text": "Operator"
},
{
"code": null,
"e": 4343,
"s": 4334,
"text": "Operator"
},
{
"code": null,
"e": 4347,
"s": 4343,
"text": "Get"
},
{
"code": null,
"e": 4351,
"s": 4347,
"text": "Get"
},
{
"code": null,
"e": 4355,
"s": 4351,
"text": "Set"
},
{
"code": null,
"e": 4359,
"s": 4355,
"text": "Set"
},
{
"code": null,
"e": 4370,
"s": 4359,
"text": "AddHandler"
},
{
"code": null,
"e": 4381,
"s": 4370,
"text": "AddHandler"
},
{
"code": null,
"e": 4395,
"s": 4381,
"text": "RemoveHandler"
},
{
"code": null,
"e": 4409,
"s": 4395,
"text": "RemoveHandler"
},
{
"code": null,
"e": 4420,
"s": 4409,
"text": "RaiseEvent"
},
{
"code": null,
"e": 4431,
"s": 4420,
"text": "RaiseEvent"
},
{
"code": null,
"e": 4556,
"s": 4431,
"text": "The next line( 'This program) will be ignored by the compiler and it has been put to add additional comments in the program."
},
{
"code": null,
"e": 4681,
"s": 4556,
"text": "The next line( 'This program) will be ignored by the compiler and it has been put to add additional comments in the program."
},
{
"code": null,
"e": 4847,
"s": 4681,
"text": "The next line defines the Main procedure, which is the entry point for all VB.Net programs. The Main procedure states what the module or class will do when executed."
},
{
"code": null,
"e": 5013,
"s": 4847,
"text": "The next line defines the Main procedure, which is the entry point for all VB.Net programs. The Main procedure states what the module or class will do when executed."
},
{
"code": null,
"e": 5264,
"s": 5013,
"text": "The Main procedure specifies its behavior with the statement\nConsole.WriteLine(\"Hello World\") WriteLine is a method of the Console class defined in the System namespace. This statement causes the message \"Hello, World!\" to be displayed on the screen."
},
{
"code": null,
"e": 5325,
"s": 5264,
"text": "The Main procedure specifies its behavior with the statement"
},
{
"code": null,
"e": 5515,
"s": 5325,
"text": "Console.WriteLine(\"Hello World\") WriteLine is a method of the Console class defined in the System namespace. This statement causes the message \"Hello, World!\" to be displayed on the screen."
},
{
"code": null,
"e": 5688,
"s": 5515,
"text": "The last line Console.ReadKey() is for the VS.NET Users. This will prevent the screen from running and closing quickly when the program is launched from Visual Studio .NET."
},
{
"code": null,
"e": 5861,
"s": 5688,
"text": "The last line Console.ReadKey() is for the VS.NET Users. This will prevent the screen from running and closing quickly when the program is launched from Visual Studio .NET."
},
{
"code": null,
"e": 5928,
"s": 5861,
"text": "If you are using Visual Studio.Net IDE, take the following steps −"
},
{
"code": null,
"e": 5949,
"s": 5928,
"text": "Start Visual Studio."
},
{
"code": null,
"e": 5970,
"s": 5949,
"text": "Start Visual Studio."
},
{
"code": null,
"e": 6016,
"s": 5970,
"text": "On the menu bar, choose File → New → Project."
},
{
"code": null,
"e": 6062,
"s": 6016,
"text": "On the menu bar, choose File → New → Project."
},
{
"code": null,
"e": 6097,
"s": 6062,
"text": "Choose Visual Basic from templates"
},
{
"code": null,
"e": 6132,
"s": 6097,
"text": "Choose Visual Basic from templates"
},
{
"code": null,
"e": 6160,
"s": 6132,
"text": "Choose Console Application."
},
{
"code": null,
"e": 6188,
"s": 6160,
"text": "Choose Console Application."
},
{
"code": null,
"e": 6289,
"s": 6188,
"text": "Specify a name and location for your project using the Browse button, and then choose the OK button."
},
{
"code": null,
"e": 6390,
"s": 6289,
"text": "Specify a name and location for your project using the Browse button, and then choose the OK button."
},
{
"code": null,
"e": 6436,
"s": 6390,
"text": "The new project appears in Solution Explorer."
},
{
"code": null,
"e": 6482,
"s": 6436,
"text": "The new project appears in Solution Explorer."
},
{
"code": null,
"e": 6513,
"s": 6482,
"text": "Write code in the Code Editor."
},
{
"code": null,
"e": 6544,
"s": 6513,
"text": "Write code in the Code Editor."
},
{
"code": null,
"e": 6667,
"s": 6544,
"text": "Click the Run button or the F5 key to run the project. A Command Prompt window appears that contains the line Hello World."
},
{
"code": null,
"e": 6790,
"s": 6667,
"text": "Click the Run button or the F5 key to run the project. A Command Prompt window appears that contains the line Hello World."
},
{
"code": null,
"e": 6884,
"s": 6790,
"text": "You can compile a VB.Net program by using the command line instead of the Visual Studio IDE −"
},
{
"code": null,
"e": 6937,
"s": 6884,
"text": "Open a text editor and add the above mentioned code."
},
{
"code": null,
"e": 6990,
"s": 6937,
"text": "Open a text editor and add the above mentioned code."
},
{
"code": null,
"e": 7021,
"s": 6990,
"text": "Save the file as helloworld.vb"
},
{
"code": null,
"e": 7052,
"s": 7021,
"text": "Save the file as helloworld.vb"
},
{
"code": null,
"e": 7131,
"s": 7052,
"text": "Open the command prompt tool and go to the directory where you saved the file."
},
{
"code": null,
"e": 7210,
"s": 7131,
"text": "Open the command prompt tool and go to the directory where you saved the file."
},
{
"code": null,
"e": 7271,
"s": 7210,
"text": "Type vbc helloworld.vb and press enter to compile your code."
},
{
"code": null,
"e": 7332,
"s": 7271,
"text": "Type vbc helloworld.vb and press enter to compile your code."
},
{
"code": null,
"e": 7469,
"s": 7332,
"text": "If there are no errors in your code the command prompt will take you to the next line and would generate helloworld.exe executable file."
},
{
"code": null,
"e": 7606,
"s": 7469,
"text": "If there are no errors in your code the command prompt will take you to the next line and would generate helloworld.exe executable file."
},
{
"code": null,
"e": 7653,
"s": 7606,
"text": "Next, type helloworld to execute your program."
},
{
"code": null,
"e": 7700,
"s": 7653,
"text": "Next, type helloworld to execute your program."
},
{
"code": null,
"e": 7761,
"s": 7700,
"text": "You will be able to see \"Hello World\" printed on the screen."
},
{
"code": null,
"e": 7822,
"s": 7761,
"text": "You will be able to see \"Hello World\" printed on the screen."
},
{
"code": null,
"e": 7855,
"s": 7822,
"text": "\n 63 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 7872,
"s": 7855,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 7907,
"s": 7872,
"text": "\n 103 Lectures \n 12 hours \n"
},
{
"code": null,
"e": 7922,
"s": 7907,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 7957,
"s": 7922,
"text": "\n 60 Lectures \n 9.5 hours \n"
},
{
"code": null,
"e": 7972,
"s": 7957,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 8005,
"s": 7972,
"text": "\n 97 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 8020,
"s": 8005,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 8027,
"s": 8020,
"text": " Print"
},
{
"code": null,
"e": 8038,
"s": 8027,
"text": " Add Notes"
}
] |
Form widget in Django | In this article, we will see how to use widgets in a Django form. Widgets can be quiet helpful to make the frontend better. Widgets are html elements that are rendered from Django form, textarea, input, password input, etc., all are widgets.
First let's create a Django project and an app. I created the project with the name "tutorial14" and app with the name "djangoFormWidget".
Add app in settings.py and include app's URL in project urls.py.
Make every basic files and folders like Templates, home.html, forms.py.
In app's urls.py −
from django.urls import path,include
from . import views
urlpatterns = [
path('',views.home,name="home")
]
It will create a basic URL for rendering view.
In views.py −
from django.shortcuts import render
from .forms import CommentForm
# Create your views here.
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def home(request):
if request.method=='POST':
form=CommentForm(request.POST)
if form.is_valid():
form.save()
commentform=CommentForm()
return render(request,'home.html',{"commentform":commentform})
Here, we imported our form and handled its POST and GET requests.
In POST, we save the data and in GET, we send the form to the frontend.
In models.py −
from django.db import models
# Create your models here.
class CommentModel(models.Model):
comment=models.CharField(max_length=500)
Here we created a model which we will use in our form. We need this model to use the form.
In home.html −
<!DOCTYPE html>
<html>
<head>
<title>TUT</title>
</head>
<body>
{% for fm in commentform %}
<form method="post">
{%csrf_token%}
{{fm.errors}}<br>
{{fm.label}}:{{fm}}<br>
{%endfor%}
<button type="submit">Submit</button>
</form>
</body>
</html>
It is a simple frontend where we render our form.
In forms.py −
from django import forms
from .models import CommentModel
class CommentForm(forms.Form):
comment=forms.CharField(widget=forms.Textarea(attrs={'class':'comment','title':'add comment'})) # this is the line which is used for widget, here I added TextArea widget you can see we also assigned class to widget using attrs attribute.
def save(self):
data=self.data
modelRef=CommentModel(comment=data['comment'])
modelRef.save()
It is where we make our form. We used the built-in Django form widget
to render a textarea in the form. | [
{
"code": null,
"e": 1304,
"s": 1062,
"text": "In this article, we will see how to use widgets in a Django form. Widgets can be quiet helpful to make the frontend better. Widgets are html elements that are rendered from Django form, textarea, input, password input, etc., all are widgets."
},
{
"code": null,
"e": 1443,
"s": 1304,
"text": "First let's create a Django project and an app. I created the project with the name \"tutorial14\" and app with the name \"djangoFormWidget\"."
},
{
"code": null,
"e": 1508,
"s": 1443,
"text": "Add app in settings.py and include app's URL in project urls.py."
},
{
"code": null,
"e": 1580,
"s": 1508,
"text": "Make every basic files and folders like Templates, home.html, forms.py."
},
{
"code": null,
"e": 1599,
"s": 1580,
"text": "In app's urls.py −"
},
{
"code": null,
"e": 1709,
"s": 1599,
"text": "from django.urls import path,include\nfrom . import views\nurlpatterns = [\n path('',views.home,name=\"home\")\n]"
},
{
"code": null,
"e": 1756,
"s": 1709,
"text": "It will create a basic URL for rendering view."
},
{
"code": null,
"e": 1770,
"s": 1756,
"text": "In views.py −"
},
{
"code": null,
"e": 2159,
"s": 1770,
"text": "from django.shortcuts import render\nfrom .forms import CommentForm\n\n# Create your views here.\nfrom django.views.decorators.csrf import csrf_exempt\n\n@csrf_exempt\ndef home(request):\n if request.method=='POST':\n form=CommentForm(request.POST)\n if form.is_valid():\n form.save()\n commentform=CommentForm()\n return render(request,'home.html',{\"commentform\":commentform})"
},
{
"code": null,
"e": 2225,
"s": 2159,
"text": "Here, we imported our form and handled its POST and GET requests."
},
{
"code": null,
"e": 2297,
"s": 2225,
"text": "In POST, we save the data and in GET, we send the form to the frontend."
},
{
"code": null,
"e": 2312,
"s": 2297,
"text": "In models.py −"
},
{
"code": null,
"e": 2447,
"s": 2312,
"text": "from django.db import models\n\n# Create your models here.\nclass CommentModel(models.Model):\n comment=models.CharField(max_length=500)"
},
{
"code": null,
"e": 2538,
"s": 2447,
"text": "Here we created a model which we will use in our form. We need this model to use the form."
},
{
"code": null,
"e": 2553,
"s": 2538,
"text": "In home.html −"
},
{
"code": null,
"e": 2881,
"s": 2553,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>TUT</title>\n </head>\n <body>\n {% for fm in commentform %}\n <form method=\"post\">\n {%csrf_token%}\n\n {{fm.errors}}<br>\n {{fm.label}}:{{fm}}<br>\n {%endfor%}\n <button type=\"submit\">Submit</button>\n </form>\n </body>\n</html>"
},
{
"code": null,
"e": 2931,
"s": 2881,
"text": "It is a simple frontend where we render our form."
},
{
"code": null,
"e": 2945,
"s": 2931,
"text": "In forms.py −"
},
{
"code": null,
"e": 3379,
"s": 2945,
"text": "from django import forms\nfrom .models import CommentModel\nclass CommentForm(forms.Form):\n comment=forms.CharField(widget=forms.Textarea(attrs={'class':'comment','title':'add comment'})) # this is the line which is used for widget, here I added TextArea widget you can see we also assigned class to widget using attrs attribute.\n\ndef save(self):\n data=self.data\n modelRef=CommentModel(comment=data['comment'])\n modelRef.save()"
},
{
"code": null,
"e": 3483,
"s": 3379,
"text": "It is where we make our form. We used the built-in Django form widget\nto render a textarea in the form."
}
] |
How to Generate Newman Reports on Jenkins using Postman? | We can generate Newman reports on Jenkins. The reports obtained from Jenkins are a pictorial and organized representation of test execution results. These reports can also be shared with all the stakeholders of the project.
Jenkins reports can be generated in several formats and can be controlled by adding different flags in the build commands. Also, it is necessary to specify the path where the reports shall be saved in build commands.
The steps to generate Newman reports on Jenkins are listed below −
As a prerequisite, Jenkins should be configured in the system. The details available in the link − https://www.tutorialspoint.com/jenkins/index.htm. Also, we should have a Collection with a minimum one request along with the Newman installed in the system.
Step 1 − Click on the arrow to the right of the Collection name. Next, click the Share button.
Step 2 − SHARE COLLECTION1 window opens up. Move to the Get public link tab and copy the link that has been marked in the below image.
Step 3 − Open Jenkins and move to the Jenkins Job below the Build section. Add the below command to generate CLI and JUNIT reports −
newman run "<link copied in Step2> " --reporters cli, junit
Step 4 − To specify the path where the Newman report is to be saved, we should add the command.
newman run "<link in Step2>" --reporters cli,junit --reporter-junit-export
"report/newmanreport.xml"
Here, report/newmanreport.xml is the path where the report shall be saved. If that directory does not exist, the report gets created by default within the Jenkins Workspace directory. | [
{
"code": null,
"e": 1286,
"s": 1062,
"text": "We can generate Newman reports on Jenkins. The reports obtained from Jenkins are a pictorial and organized representation of test execution results. These reports can also be shared with all the stakeholders of the project."
},
{
"code": null,
"e": 1503,
"s": 1286,
"text": "Jenkins reports can be generated in several formats and can be controlled by adding different flags in the build commands. Also, it is necessary to specify the path where the reports shall be saved in build commands."
},
{
"code": null,
"e": 1570,
"s": 1503,
"text": "The steps to generate Newman reports on Jenkins are listed below −"
},
{
"code": null,
"e": 1827,
"s": 1570,
"text": "As a prerequisite, Jenkins should be configured in the system. The details available in the link − https://www.tutorialspoint.com/jenkins/index.htm. Also, we should have a Collection with a minimum one request along with the Newman installed in the system."
},
{
"code": null,
"e": 1922,
"s": 1827,
"text": "Step 1 − Click on the arrow to the right of the Collection name. Next, click the Share button."
},
{
"code": null,
"e": 2057,
"s": 1922,
"text": "Step 2 − SHARE COLLECTION1 window opens up. Move to the Get public link tab and copy the link that has been marked in the below image."
},
{
"code": null,
"e": 2190,
"s": 2057,
"text": "Step 3 − Open Jenkins and move to the Jenkins Job below the Build section. Add the below command to generate CLI and JUNIT reports −"
},
{
"code": null,
"e": 2250,
"s": 2190,
"text": "newman run \"<link copied in Step2> \" --reporters cli, junit"
},
{
"code": null,
"e": 2346,
"s": 2250,
"text": "Step 4 − To specify the path where the Newman report is to be saved, we should add the command."
},
{
"code": null,
"e": 2447,
"s": 2346,
"text": "newman run \"<link in Step2>\" --reporters cli,junit --reporter-junit-export\n\"report/newmanreport.xml\""
},
{
"code": null,
"e": 2631,
"s": 2447,
"text": "Here, report/newmanreport.xml is the path where the report shall be saved. If that directory does not exist, the report gets created by default within the Jenkins Workspace directory."
}
] |
How to use case-insensitive switch-case in JavaScript? | To use case-insensitive switch-case in JavaScript, make the input all upper or all lowercase.
You can try to run the following code to learn how to use a case-insensitive switch:
<!DOCTYPE html>
<html>
<body>
<h3>JavaScript Strings</h3>
<p id="test"></p>
<script>
var str = "amit";
str = str.toUpperCase();
switch (str) {
case 'AMIT': document.write("The name is AMIT <br>");
break;
case 'JOHN': document.write("The name is JOHN <br>");
break;
default: document.write("Unknown name<br>")
}
document.write("Exiting switch block");
</script>
</body>
</html> | [
{
"code": null,
"e": 1156,
"s": 1062,
"text": "To use case-insensitive switch-case in JavaScript, make the input all upper or all lowercase."
},
{
"code": null,
"e": 1241,
"s": 1156,
"text": "You can try to run the following code to learn how to use a case-insensitive switch:"
},
{
"code": null,
"e": 1753,
"s": 1241,
"text": "<!DOCTYPE html>\n<html>\n <body>\n <h3>JavaScript Strings</h3>\n <p id=\"test\"></p>\n <script>\n var str = \"amit\";\n str = str.toUpperCase();\n switch (str) {\n case 'AMIT': document.write(\"The name is AMIT <br>\");\n break;\n case 'JOHN': document.write(\"The name is JOHN <br>\");\n break;\n default: document.write(\"Unknown name<br>\")\n }\n document.write(\"Exiting switch block\");\n </script>\n </body>\n</html>"
}
] |
Replacing array of object property name in JavaScript | Following is the code to replace array of object property name in JavaScript −
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result {
font-size: 18px;
font-weight: 500;
color: rebeccapurple;
}
</style>
</head>
<body>
<h1>Replacing array of object property name</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click the above button to change the property name of an object in array</h3>
<script>
let BtnEle = document.querySelector(".Btn");
let resEle = document.querySelector(".result");
var person = [
{ name: "Rohan Sharma", age: 16 },
{ name: "Vinit Mehta", age: 18 },
];
person = person.map((item) => {
return {
fullName: item.name,
age: item.age,
};
});
BtnEle.addEventListener("click", () => {
person.forEach((item) => {
resEle.innerHTML += "fullName = " + item.fullName + " : Age = " + item.age + "";
});
});
</script>
</body>
</html>
The above code will produce the following output −
On clicking the ‘CLICK HERE’ button − | [
{
"code": null,
"e": 1141,
"s": 1062,
"text": "Following is the code to replace array of object property name in JavaScript −"
},
{
"code": null,
"e": 1152,
"s": 1141,
"text": " Live Demo"
},
{
"code": null,
"e": 2263,
"s": 1152,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .result {\n font-size: 18px;\n font-weight: 500;\n color: rebeccapurple;\n }\n</style>\n</head>\n<body>\n<h1>Replacing array of object property name</h1>\n<div class=\"result\"></div>\n<button class=\"Btn\">CLICK HERE</button>\n<h3>Click the above button to change the property name of an object in array</h3>\n<script>\n let BtnEle = document.querySelector(\".Btn\");\n let resEle = document.querySelector(\".result\");\n var person = [\n { name: \"Rohan Sharma\", age: 16 },\n { name: \"Vinit Mehta\", age: 18 },\n ];\n person = person.map((item) => {\n return {\n fullName: item.name,\n age: item.age,\n };\n });\n BtnEle.addEventListener(\"click\", () => {\n person.forEach((item) => {\n resEle.innerHTML += \"fullName = \" + item.fullName + \" : Age = \" + item.age + \"\";\n });\n });\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2314,
"s": 2263,
"text": "The above code will produce the following output −"
},
{
"code": null,
"e": 2352,
"s": 2314,
"text": "On clicking the ‘CLICK HERE’ button −"
}
] |
Sum Of Digits | Practice | GeeksforGeeks | Given a number, N. Find the sum of all the digits of N
Example 1:
Input:
N = 12
Output:
3
Explanation:
Sum of 12's digits:
1 + 2 = 3
Example 2:
Input:
N = 23
Output
5
Explanation:
Sum of 23's digits:
2 + 3 = 5
Your Task:
You don't need to read input or print anything. Your task is to complete the function sumOfDigits() which takes an integer N as input parameters and returns an integer, total sum of digits of N.
Expected Time Complexity: O(log10N)
Expected Space Complexity: O(1)
Constraints:
1<=N<=105
0
mayank180919992 weeks ago
int sumOfDigits(int N){
//code here
int digit,sum=0;
while(N!=0){
digit=N%10;
sum+=digit;
N=N/10;
}
return sum;
}
0
sayanmazumder9991 month ago
JAVA
String s = String.valueOf(N); int sum = 0; for(int i = 0; i < s.length(); i++) sum += (s.charAt(i) - '0'); return sum;
-1
0niharika22 months ago
if(N==0) return 0; return sumOfDigits(N/10) + N%10;
+2
0niharika22 months ago
int sum=0; while(N){ sum+=N%10; N/=10; } return sum;
0
iamprashantgehlot242 months ago
int rem,sum=0; while(N){ rem=N%10; sum =sum+rem; N=N/10; } return sum;
0
rupanjalborphukan2 months ago
Most efficient code:
Time taken for this code: C++ : 0.0/1.1
Java : 0.1/1.2
Python : 0.0
int ans = 0;
while(N!=0){
int digits = N%10;
ans = ans+digits;
N = N/10;
}
return ans;
0
amoghyelasangi2 months ago
class Solution: def sumOfDigits (self, N): sum = 0 for digit in str(N): sum = sum+int(digit) return sum
0
aadityajoshi2910203 months ago
Very Easy Solution :
class Solution{
static int sumOfDigits(int N) {
// code here
int sum = 0;
while(N != 0){
int rem = N % 10;
N = N/10;
sum += rem;
}
return sum;
}
}
0
sarangrajendrabadgujar3 months ago
JAVA Solution
class Solution{ static int sumOfDigits(int N) { int i=0; int count=0; if(N<=99999){ i=N%10; N=(N-i)/10; count+=i; i=N%10; N=(N-i)/10; count+=i; i=N%10; N=(N-i)/10; count+=i; i=N%10; N=(N-i)/10; count=count+i+N%10; } return count; }}
+1
piyush9534974 months ago
JAVA
class Solution{ static int sumOfDigits(int N) { if(N<=0){ return 0; } return N%10 + sumOfDigits(N/10); }}
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": 295,
"s": 238,
"text": "Given a number, N. Find the sum of all the digits of N\n "
},
{
"code": null,
"e": 306,
"s": 295,
"text": "Example 1:"
},
{
"code": null,
"e": 373,
"s": 306,
"text": "Input:\nN = 12\nOutput:\n3\nExplanation:\nSum of 12's digits:\n1 + 2 = 3"
},
{
"code": null,
"e": 384,
"s": 373,
"text": "Example 2:"
},
{
"code": null,
"e": 451,
"s": 384,
"text": "Input:\nN = 23\nOutput\n5\nExplanation:\nSum of 23's digits:\n2 + 3 = 5\n"
},
{
"code": null,
"e": 658,
"s": 451,
"text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function sumOfDigits() which takes an integer N as input parameters and returns an integer, total sum of digits of N."
},
{
"code": null,
"e": 729,
"s": 658,
"text": "\nExpected Time Complexity: O(log10N)\nExpected Space Complexity: O(1)\n "
},
{
"code": null,
"e": 752,
"s": 729,
"text": "Constraints:\n1<=N<=105"
},
{
"code": null,
"e": 754,
"s": 752,
"text": "0"
},
{
"code": null,
"e": 780,
"s": 754,
"text": "mayank180919992 weeks ago"
},
{
"code": null,
"e": 971,
"s": 780,
"text": " int sumOfDigits(int N){\n //code here\n int digit,sum=0;\n while(N!=0){\n digit=N%10;\n sum+=digit;\n N=N/10;\n }\n return sum;\n }"
},
{
"code": null,
"e": 973,
"s": 971,
"text": "0"
},
{
"code": null,
"e": 1001,
"s": 973,
"text": "sayanmazumder9991 month ago"
},
{
"code": null,
"e": 1006,
"s": 1001,
"text": "JAVA"
},
{
"code": null,
"e": 1145,
"s": 1006,
"text": " String s = String.valueOf(N); int sum = 0; for(int i = 0; i < s.length(); i++) sum += (s.charAt(i) - '0'); return sum;"
},
{
"code": null,
"e": 1148,
"s": 1145,
"text": "-1"
},
{
"code": null,
"e": 1171,
"s": 1148,
"text": "0niharika22 months ago"
},
{
"code": null,
"e": 1239,
"s": 1171,
"text": "if(N==0) return 0; return sumOfDigits(N/10) + N%10;"
},
{
"code": null,
"e": 1242,
"s": 1239,
"text": "+2"
},
{
"code": null,
"e": 1265,
"s": 1242,
"text": "0niharika22 months ago"
},
{
"code": null,
"e": 1356,
"s": 1265,
"text": "int sum=0; while(N){ sum+=N%10; N/=10; } return sum;"
},
{
"code": null,
"e": 1358,
"s": 1356,
"text": "0"
},
{
"code": null,
"e": 1390,
"s": 1358,
"text": "iamprashantgehlot242 months ago"
},
{
"code": null,
"e": 1510,
"s": 1390,
"text": " int rem,sum=0; while(N){ rem=N%10; sum =sum+rem; N=N/10; } return sum;"
},
{
"code": null,
"e": 1512,
"s": 1510,
"text": "0"
},
{
"code": null,
"e": 1542,
"s": 1512,
"text": "rupanjalborphukan2 months ago"
},
{
"code": null,
"e": 1563,
"s": 1542,
"text": "Most efficient code:"
},
{
"code": null,
"e": 1604,
"s": 1563,
"text": "Time taken for this code: C++ : 0.0/1.1"
},
{
"code": null,
"e": 1660,
"s": 1604,
"text": " Java : 0.1/1.2"
},
{
"code": null,
"e": 1714,
"s": 1660,
"text": " Python : 0.0"
},
{
"code": null,
"e": 1806,
"s": 1716,
"text": "int ans = 0;\nwhile(N!=0){\n\tint digits = N%10;\n\tans = ans+digits;\n\tN = N/10;\n}\nreturn ans;"
},
{
"code": null,
"e": 1808,
"s": 1806,
"text": "0"
},
{
"code": null,
"e": 1835,
"s": 1808,
"text": "amoghyelasangi2 months ago"
},
{
"code": null,
"e": 1970,
"s": 1835,
"text": "class Solution: def sumOfDigits (self, N): sum = 0 for digit in str(N): sum = sum+int(digit) return sum"
},
{
"code": null,
"e": 1972,
"s": 1970,
"text": "0"
},
{
"code": null,
"e": 2003,
"s": 1972,
"text": "aadityajoshi2910203 months ago"
},
{
"code": null,
"e": 2024,
"s": 2003,
"text": "Very Easy Solution :"
},
{
"code": null,
"e": 2255,
"s": 2024,
"text": "class Solution{\n static int sumOfDigits(int N) {\n // code here\n int sum = 0;\n while(N != 0){\n int rem = N % 10;\n N = N/10;\n sum += rem;\n }\n return sum;\n }\n}"
},
{
"code": null,
"e": 2257,
"s": 2255,
"text": "0"
},
{
"code": null,
"e": 2292,
"s": 2257,
"text": "sarangrajendrabadgujar3 months ago"
},
{
"code": null,
"e": 2306,
"s": 2292,
"text": "JAVA Solution"
},
{
"code": null,
"e": 2693,
"s": 2306,
"text": "class Solution{ static int sumOfDigits(int N) { int i=0; int count=0; if(N<=99999){ i=N%10; N=(N-i)/10; count+=i; i=N%10; N=(N-i)/10; count+=i; i=N%10; N=(N-i)/10; count+=i; i=N%10; N=(N-i)/10; count=count+i+N%10; } return count; }}"
},
{
"code": null,
"e": 2696,
"s": 2693,
"text": "+1"
},
{
"code": null,
"e": 2721,
"s": 2696,
"text": "piyush9534974 months ago"
},
{
"code": null,
"e": 2726,
"s": 2721,
"text": "JAVA"
},
{
"code": null,
"e": 2864,
"s": 2726,
"text": "class Solution{ static int sumOfDigits(int N) { if(N<=0){ return 0; } return N%10 + sumOfDigits(N/10); }}"
},
{
"code": null,
"e": 3010,
"s": 2864,
"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": 3046,
"s": 3010,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 3056,
"s": 3046,
"text": "\nProblem\n"
},
{
"code": null,
"e": 3066,
"s": 3056,
"text": "\nContest\n"
},
{
"code": null,
"e": 3129,
"s": 3066,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 3277,
"s": 3129,
"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": 3485,
"s": 3277,
"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": 3591,
"s": 3485,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
How can we use WHERE clause with MySQL INSERT INTO command? | We can use conditional insert i.e. WHERE clause with INSERT INTO command in the case of new row insertion. It can be done with following ways −
In this case, we insert the value from dummy table along with some conditions. The syntax can be as follows −
INSERT INTO table_name(column1,column2,column3,...) Select value1,value2,value3,... From dual WHERE [conditional predicate];
mysql> Create table testing(id int, item_name varchar(10));
Query OK, 0 rows affected (0.15 sec)
mysql> Insert into testing (id,item_name)Select 1,'Book' From Dual Where 1=1;
Query OK, 1 row affected (0.11 sec)
Records: 1 Duplicates: 0 Warnings: 0
mysql> Select * from testing;
+------+-----------+
| id | item_name |
+------+-----------+
| 1 | Book |
+------+-----------+
1 row in set (0.00 sec)
In the example above, we have created a table ‘testing’ and for inserting rows into it we have used dummy table dual with a condition. If the condition is true MySQL insert the row into table otherwise not.
If we want to insert in a table whose structure is same as another table then in the following example it has been demonstrated that how we can have conditional insert i.e. how we can use WHERE clause with INSERT INTO statement.
mysql> Insert into dummy1(id,name)select id, name from dummy Where id =1;
Query OK, 1 row affected (0.06 sec)
Records: 1 Duplicates: 0 Warnings: 0
mysql> select * from dummy;
+------+--------+
| id | Name |
+------+--------+
| 1 | Gaurav |
| 2 | Aarav |
+------+--------+
2 rows in set (0.00 sec)
mysql> select * from dummy1;
+------+--------+
| id | Name |
+------+--------+
| 1 | Gaurav |
+------+--------+
1 row in set (0.00 sec)
Here in the example above, we have inserted the values in table ‘dummy1’, having the same structure as table ‘dummy’, with a condition to insert only that row where ‘id = 1’. | [
{
"code": null,
"e": 1206,
"s": 1062,
"text": "We can use conditional insert i.e. WHERE clause with INSERT INTO command in the case of new row insertion. It can be done with following ways −"
},
{
"code": null,
"e": 1316,
"s": 1206,
"text": "In this case, we insert the value from dummy table along with some conditions. The syntax can be as follows −"
},
{
"code": null,
"e": 1441,
"s": 1316,
"text": "INSERT INTO table_name(column1,column2,column3,...) Select value1,value2,value3,... From dual WHERE [conditional predicate];"
},
{
"code": null,
"e": 1852,
"s": 1441,
"text": "mysql> Create table testing(id int, item_name varchar(10));\nQuery OK, 0 rows affected (0.15 sec)\n\nmysql> Insert into testing (id,item_name)Select 1,'Book' From Dual Where 1=1;\nQuery OK, 1 row affected (0.11 sec)\nRecords: 1 Duplicates: 0 Warnings: 0\n\nmysql> Select * from testing;\n\n+------+-----------+\n| id | item_name |\n+------+-----------+\n| 1 | Book |\n+------+-----------+\n\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 2059,
"s": 1852,
"text": "In the example above, we have created a table ‘testing’ and for inserting rows into it we have used dummy table dual with a condition. If the condition is true MySQL insert the row into table otherwise not."
},
{
"code": null,
"e": 2288,
"s": 2059,
"text": "If we want to insert in a table whose structure is same as another table then in the following example it has been demonstrated that how we can have conditional insert i.e. how we can use WHERE clause with INSERT INTO statement."
},
{
"code": null,
"e": 2744,
"s": 2288,
"text": "mysql> Insert into dummy1(id,name)select id, name from dummy Where id =1;\nQuery OK, 1 row affected (0.06 sec)\nRecords: 1 Duplicates: 0 Warnings: 0\n\nmysql> select * from dummy;\n\n+------+--------+\n| id | Name |\n+------+--------+\n| 1 | Gaurav |\n| 2 | Aarav |\n+------+--------+\n\n2 rows in set (0.00 sec)\n\nmysql> select * from dummy1;\n\n+------+--------+\n| id | Name |\n+------+--------+\n| 1 | Gaurav |\n+------+--------+\n\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 2919,
"s": 2744,
"text": "Here in the example above, we have inserted the values in table ‘dummy1’, having the same structure as table ‘dummy’, with a condition to insert only that row where ‘id = 1’."
}
] |
Deploy Tensorflow Object Detection API on Kubernetes with Python, Flask and Docker | by Neeraj Krishna | Towards Data Science | The TensorFlow Object Detection API is an open source framework built on top of TensorFlow that makes it easy to construct, train and deploy object detection models.This article demonstrates how you can serve the Tensorflow Object Detection API with Flask, Dockerize the application and deploy it on Kubernetes using the Google Kubernetes Engine.
Once deployed, you can incorporate the API into your custom application, be it a mobile application or a web application to suit your needs.
These are the steps we will be doing:
Set up the Tensorflow Object Detection API
Serve the API using Flask
Containerize the application using Docker
Deploy the containerized application on Kubernetes
Note: We will not be covering the Tensorflow Object Detection API in-depth since that is not the main emphasis of this article. You can visit the official repo if you are interested. It’ll be really helpful if you’re acquainted with it. We also will not go through the entire process of setting up the environment since we can cut it down using Docker. However, you can refer to this amazing article if you are interested.
Clone my repository into the workspace. We will be working with this code throughout the article.
git clone https://github.com/wingedrasengan927/Tensorflow-2-Object-Detection-API-Flask-Application.git
Install Docker in your system if you haven’t already. A Docker container basically packages up code and all its dependencies so the application runs quickly and reliably in any environment. It includes everything needed to run an application and isolates the dependencies from the main environment.
Inside the repo you have cloned, you will find a Dockerfile. Dockerfiles describe the different processes that are assembled to build an Image and can also contain some metadata describing how to run a container based on this image. Our Dockerfile looks like this:
To build an image from the Dockerfile run the following from inside the repo:
docker build -t tf-od-api:latest .
-t indicates the tag you give to the Docker image. The building takes a lot of time. If you see something like this:
Successfully built 64edf7b4c21fSuccessfully tagged tf-od-api:latest
It means the image was successfully built. Now let’s run a container from the image. Run the following command:
docker run -d -p 5000:5000 tf-od-api:latest
This ensures that we detach from the running container and the container is exposed on the port 5000.
Now let’s test our application. This can be done by running the script client.py which is inside the repo, with the necessary arguments (you need to have opencv and numpy installed in your workspace to run the script):
python client.py --address http://127.0.0.1:5000 --image_path images/test_image.jpg --output_dir outputs/
If you see something like this as the output, then our application is working as expected:
Detections are: [{‘person’: ‘79%’}, {‘chair’: ‘34%’}]the image size is: size=1920x1281the image is being written in outputs/
When we build the image from the Dockerfile, we set the environment necessary to run the Tensorflow Object Detection API, this includes cloning the repository, compiling the protocol buffers, setting the environment variables, downloading the model and when we are ready, we clone the repository which contains the code for serving the application with Flask, and we launch the application on port 5000 and we make sure to expose that port when we run the container.
This is the application code:
You can change the parameters, pre-trained model in this file. Make sure you the changes are reflected in the Dockerfile, you can use COPY in Dockerfile to copy the changed repo from your local environment into the Dockerfile instead of cloning it.
On the client side, the request we send to the endpoint contains the image data. We can use API testing tools like Postman or the curl command to send data. The response we get back contains the detections in the image, the image size and image data with the bounding box overlay. We write this image to output_dir
You can run the application on your local system if you have set up the environment which includes adding the required paths to the PATH environment variable.If the Docker container did not run as expected, you can check the logs by running docker logs container_id to check what went wrongThis is a base version of the API and you can customize it according to your needs.
You can run the application on your local system if you have set up the environment which includes adding the required paths to the PATH environment variable.
If the Docker container did not run as expected, you can check the logs by running docker logs container_id to check what went wrong
This is a base version of the API and you can customize it according to your needs.
Before proceeding, you need to make sure that you have a working account on Google Cloud Platform, have the cloud SDK installed, and have created a project.
Right now we have the Image in our local environment, to deploy we need to host it on the cloud. In this section we will push our Docker Image to Google Container Registry .
First we need to configure Docker to use gcloud as a credential helper. To do so, run the command:
gcloud auth configure-docker
To push any local image to the Container Registry, we need to first tag it with the registry name and then push the image. To tag, run the following command:
docker tag tf-od-api gcr.io/${PROJECT_ID}/tf-od-api
gcr.io is the Hostname which specifies the location or repository where you will store the image.
To push the tagged image, run:
docker push gcr.io/${PROJECT_ID}/tf-od-api
To check if the image has been pushed, list out the images. To do so, run:
gcloud container images list
You should see the image name in the output if it was successfully pushed.
NAMEgcr.io/my-project-21212/tf-od-api
You definitely may have heard of Kubernetes, It has become the standard for deploying and managing containerized applications. In this section we will deploy our application on Kubernetes using the Google Kubernetes Engine.
Kubernetes is a container orchestration system. It helps deploy and manage containerized applications on a cluster. A Kubernetes cluster consists of a Master, which is responsible for managing the cluster and Nodes which are worker machines that run applications.
First, let’s install kubectl. kubectl is used to communicate with Kubernetes. To install kubectl, run:
gcloud components install kubectl
Let’s create a two-node cluster named object-detection. As mentioned, a Node is a worker machine in Kubernetes which may be a virtual machine or a physical machine, depending on the cluster. To create the cluster run the following command:
gcloud container clusters create object-detection --num-nodes=2OUTPUTNAME LOCATION MASTER_VERSION MASTER_IP MACHINE_TYPE NODE_VERSION NUM_NODES STATUSobject-detection us-central1-a 1.14.10-gke.27 35.193.127.147 n1-standard-1 1.14.10-gke.27 2 RUNNING
After the Cluster is created, It spins up two VM instances on Google Compute Engine which are Cluster’s Node Workers. To see them, run the following command:
gcloud compute instances listOUTPUTNAME ZONE MACHINE_TYPE PREEMPTIBLE INTERNAL_IP EXTERNAL_IP STATUSgke-object-detection-default-pool-cd7fa3ff-3zd6 us-central1-a n1-standard-1 10.128.0.4 34.67.58.20 RUNNINGgke-object-detection-default-pool-cd7fa3ff-z2hw us-central1-a n1-standard-1 10.128.0.5 35.222.93.20 RUNNING
Now that we have a cluster up and running, let’s deploy our containerized application. To do so, we have to create a Kubernetes Deployment. The Deployment instructs Kubernetes how to create and update instances of our application. When we create a Deployment, we have to specify the container image for our application and the name of the deployment. Run the following command to create a deployment:
kubectl create deployment object-detection --image=gcr.io/${PROJECT_ID}/tf-od-api
When we create a deployment, Kubernetes creates Pods to host the application instance. A Pod represents a group of one or more application containers. A Pod runs on a Node.To see the Pods created by Deployment, run:
kubectl get podsOUTPUTNAME READY STATUS RESTARTS AGEobject-detection-7c997cbfd8-5nz4j 1/1 Running 0 2m11s
We have to allow traffic from the internet to the application so that we can access it. To do so, run:
kubectl expose deployment object-detection --type=LoadBalancer --port 80 --target-port 5000
The port flag specifies the port number configured on the Load Balancer, and the target-port flag specifies the port number that the tf-od-api container is listening on.
To get the external IP, run the following command:
kubectl get serviceOUTPUTNAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGEkubernetes ClusterIP 10.51.240.1 <none> 443/TCP 30mobject-detection LoadBalancer 10.51.245.79 35.193.230.83 80:31667/TCP 4m57s
Now let’s check if our application is accessible. To do so we’ll run the same client.py but we have to give the external IP as the address argument:
python client.py --address http://35.193.230.83/(my external IP) --image_path images/input_image.jpg --output_dir outputs/OUTPUTDetections are: [{‘person’: ‘79%’}, {‘chair’: ‘34%’}]the image size is: size=1920x1281the image is being written in outputs/
If you see an output which is similar to when we ran it before, Congratulations! You’ve successfully deployed a containerized Tensorflow Object Detection API application on Kubernetes.
Do not forget to remove the cluster once you are done as it may incur charges. To do so, run the following command to delete the service:
kubectl delete service object-detection
And to delete the Cluster and it’s resources, run:
gcloud container clusters delete object-detectionOUTPUTDeleting cluster object-detection...done.Deleted [https://container.googleapis.com/v1/projects/temp-kubernetes/zones/us-central1-a/clusters/object-detection].
In this article, we have learned how to serve the Tensorflow Object Detection API using Flask, containerize the application using Docker and deploy the application on Kubernetes. Hope it has been of help.
If you have any feedback or want to get in touch in general, please drop me a note on [email protected] | [
{
"code": null,
"e": 519,
"s": 172,
"text": "The TensorFlow Object Detection API is an open source framework built on top of TensorFlow that makes it easy to construct, train and deploy object detection models.This article demonstrates how you can serve the Tensorflow Object Detection API with Flask, Dockerize the application and deploy it on Kubernetes using the Google Kubernetes Engine."
},
{
"code": null,
"e": 660,
"s": 519,
"text": "Once deployed, you can incorporate the API into your custom application, be it a mobile application or a web application to suit your needs."
},
{
"code": null,
"e": 698,
"s": 660,
"text": "These are the steps we will be doing:"
},
{
"code": null,
"e": 741,
"s": 698,
"text": "Set up the Tensorflow Object Detection API"
},
{
"code": null,
"e": 767,
"s": 741,
"text": "Serve the API using Flask"
},
{
"code": null,
"e": 809,
"s": 767,
"text": "Containerize the application using Docker"
},
{
"code": null,
"e": 860,
"s": 809,
"text": "Deploy the containerized application on Kubernetes"
},
{
"code": null,
"e": 1283,
"s": 860,
"text": "Note: We will not be covering the Tensorflow Object Detection API in-depth since that is not the main emphasis of this article. You can visit the official repo if you are interested. It’ll be really helpful if you’re acquainted with it. We also will not go through the entire process of setting up the environment since we can cut it down using Docker. However, you can refer to this amazing article if you are interested."
},
{
"code": null,
"e": 1381,
"s": 1283,
"text": "Clone my repository into the workspace. We will be working with this code throughout the article."
},
{
"code": null,
"e": 1484,
"s": 1381,
"text": "git clone https://github.com/wingedrasengan927/Tensorflow-2-Object-Detection-API-Flask-Application.git"
},
{
"code": null,
"e": 1783,
"s": 1484,
"text": "Install Docker in your system if you haven’t already. A Docker container basically packages up code and all its dependencies so the application runs quickly and reliably in any environment. It includes everything needed to run an application and isolates the dependencies from the main environment."
},
{
"code": null,
"e": 2048,
"s": 1783,
"text": "Inside the repo you have cloned, you will find a Dockerfile. Dockerfiles describe the different processes that are assembled to build an Image and can also contain some metadata describing how to run a container based on this image. Our Dockerfile looks like this:"
},
{
"code": null,
"e": 2126,
"s": 2048,
"text": "To build an image from the Dockerfile run the following from inside the repo:"
},
{
"code": null,
"e": 2161,
"s": 2126,
"text": "docker build -t tf-od-api:latest ."
},
{
"code": null,
"e": 2278,
"s": 2161,
"text": "-t indicates the tag you give to the Docker image. The building takes a lot of time. If you see something like this:"
},
{
"code": null,
"e": 2346,
"s": 2278,
"text": "Successfully built 64edf7b4c21fSuccessfully tagged tf-od-api:latest"
},
{
"code": null,
"e": 2458,
"s": 2346,
"text": "It means the image was successfully built. Now let’s run a container from the image. Run the following command:"
},
{
"code": null,
"e": 2502,
"s": 2458,
"text": "docker run -d -p 5000:5000 tf-od-api:latest"
},
{
"code": null,
"e": 2604,
"s": 2502,
"text": "This ensures that we detach from the running container and the container is exposed on the port 5000."
},
{
"code": null,
"e": 2823,
"s": 2604,
"text": "Now let’s test our application. This can be done by running the script client.py which is inside the repo, with the necessary arguments (you need to have opencv and numpy installed in your workspace to run the script):"
},
{
"code": null,
"e": 2929,
"s": 2823,
"text": "python client.py --address http://127.0.0.1:5000 --image_path images/test_image.jpg --output_dir outputs/"
},
{
"code": null,
"e": 3020,
"s": 2929,
"text": "If you see something like this as the output, then our application is working as expected:"
},
{
"code": null,
"e": 3145,
"s": 3020,
"text": "Detections are: [{‘person’: ‘79%’}, {‘chair’: ‘34%’}]the image size is: size=1920x1281the image is being written in outputs/"
},
{
"code": null,
"e": 3612,
"s": 3145,
"text": "When we build the image from the Dockerfile, we set the environment necessary to run the Tensorflow Object Detection API, this includes cloning the repository, compiling the protocol buffers, setting the environment variables, downloading the model and when we are ready, we clone the repository which contains the code for serving the application with Flask, and we launch the application on port 5000 and we make sure to expose that port when we run the container."
},
{
"code": null,
"e": 3642,
"s": 3612,
"text": "This is the application code:"
},
{
"code": null,
"e": 3891,
"s": 3642,
"text": "You can change the parameters, pre-trained model in this file. Make sure you the changes are reflected in the Dockerfile, you can use COPY in Dockerfile to copy the changed repo from your local environment into the Dockerfile instead of cloning it."
},
{
"code": null,
"e": 4206,
"s": 3891,
"text": "On the client side, the request we send to the endpoint contains the image data. We can use API testing tools like Postman or the curl command to send data. The response we get back contains the detections in the image, the image size and image data with the bounding box overlay. We write this image to output_dir"
},
{
"code": null,
"e": 4580,
"s": 4206,
"text": "You can run the application on your local system if you have set up the environment which includes adding the required paths to the PATH environment variable.If the Docker container did not run as expected, you can check the logs by running docker logs container_id to check what went wrongThis is a base version of the API and you can customize it according to your needs."
},
{
"code": null,
"e": 4739,
"s": 4580,
"text": "You can run the application on your local system if you have set up the environment which includes adding the required paths to the PATH environment variable."
},
{
"code": null,
"e": 4872,
"s": 4739,
"text": "If the Docker container did not run as expected, you can check the logs by running docker logs container_id to check what went wrong"
},
{
"code": null,
"e": 4956,
"s": 4872,
"text": "This is a base version of the API and you can customize it according to your needs."
},
{
"code": null,
"e": 5113,
"s": 4956,
"text": "Before proceeding, you need to make sure that you have a working account on Google Cloud Platform, have the cloud SDK installed, and have created a project."
},
{
"code": null,
"e": 5287,
"s": 5113,
"text": "Right now we have the Image in our local environment, to deploy we need to host it on the cloud. In this section we will push our Docker Image to Google Container Registry ."
},
{
"code": null,
"e": 5386,
"s": 5287,
"text": "First we need to configure Docker to use gcloud as a credential helper. To do so, run the command:"
},
{
"code": null,
"e": 5415,
"s": 5386,
"text": "gcloud auth configure-docker"
},
{
"code": null,
"e": 5573,
"s": 5415,
"text": "To push any local image to the Container Registry, we need to first tag it with the registry name and then push the image. To tag, run the following command:"
},
{
"code": null,
"e": 5625,
"s": 5573,
"text": "docker tag tf-od-api gcr.io/${PROJECT_ID}/tf-od-api"
},
{
"code": null,
"e": 5723,
"s": 5625,
"text": "gcr.io is the Hostname which specifies the location or repository where you will store the image."
},
{
"code": null,
"e": 5754,
"s": 5723,
"text": "To push the tagged image, run:"
},
{
"code": null,
"e": 5797,
"s": 5754,
"text": "docker push gcr.io/${PROJECT_ID}/tf-od-api"
},
{
"code": null,
"e": 5872,
"s": 5797,
"text": "To check if the image has been pushed, list out the images. To do so, run:"
},
{
"code": null,
"e": 5901,
"s": 5872,
"text": "gcloud container images list"
},
{
"code": null,
"e": 5976,
"s": 5901,
"text": "You should see the image name in the output if it was successfully pushed."
},
{
"code": null,
"e": 6014,
"s": 5976,
"text": "NAMEgcr.io/my-project-21212/tf-od-api"
},
{
"code": null,
"e": 6238,
"s": 6014,
"text": "You definitely may have heard of Kubernetes, It has become the standard for deploying and managing containerized applications. In this section we will deploy our application on Kubernetes using the Google Kubernetes Engine."
},
{
"code": null,
"e": 6502,
"s": 6238,
"text": "Kubernetes is a container orchestration system. It helps deploy and manage containerized applications on a cluster. A Kubernetes cluster consists of a Master, which is responsible for managing the cluster and Nodes which are worker machines that run applications."
},
{
"code": null,
"e": 6605,
"s": 6502,
"text": "First, let’s install kubectl. kubectl is used to communicate with Kubernetes. To install kubectl, run:"
},
{
"code": null,
"e": 6639,
"s": 6605,
"text": "gcloud components install kubectl"
},
{
"code": null,
"e": 6879,
"s": 6639,
"text": "Let’s create a two-node cluster named object-detection. As mentioned, a Node is a worker machine in Kubernetes which may be a virtual machine or a physical machine, depending on the cluster. To create the cluster run the following command:"
},
{
"code": null,
"e": 7176,
"s": 6879,
"text": "gcloud container clusters create object-detection --num-nodes=2OUTPUTNAME LOCATION MASTER_VERSION MASTER_IP MACHINE_TYPE NODE_VERSION NUM_NODES STATUSobject-detection us-central1-a 1.14.10-gke.27 35.193.127.147 n1-standard-1 1.14.10-gke.27 2 RUNNING"
},
{
"code": null,
"e": 7334,
"s": 7176,
"text": "After the Cluster is created, It spins up two VM instances on Google Compute Engine which are Cluster’s Node Workers. To see them, run the following command:"
},
{
"code": null,
"e": 7747,
"s": 7334,
"text": "gcloud compute instances listOUTPUTNAME ZONE MACHINE_TYPE PREEMPTIBLE INTERNAL_IP EXTERNAL_IP STATUSgke-object-detection-default-pool-cd7fa3ff-3zd6 us-central1-a n1-standard-1 10.128.0.4 34.67.58.20 RUNNINGgke-object-detection-default-pool-cd7fa3ff-z2hw us-central1-a n1-standard-1 10.128.0.5 35.222.93.20 RUNNING"
},
{
"code": null,
"e": 8148,
"s": 7747,
"text": "Now that we have a cluster up and running, let’s deploy our containerized application. To do so, we have to create a Kubernetes Deployment. The Deployment instructs Kubernetes how to create and update instances of our application. When we create a Deployment, we have to specify the container image for our application and the name of the deployment. Run the following command to create a deployment:"
},
{
"code": null,
"e": 8230,
"s": 8148,
"text": "kubectl create deployment object-detection --image=gcr.io/${PROJECT_ID}/tf-od-api"
},
{
"code": null,
"e": 8446,
"s": 8230,
"text": "When we create a deployment, Kubernetes creates Pods to host the application instance. A Pod represents a group of one or more application containers. A Pod runs on a Node.To see the Pods created by Deployment, run:"
},
{
"code": null,
"e": 8607,
"s": 8446,
"text": "kubectl get podsOUTPUTNAME READY STATUS RESTARTS AGEobject-detection-7c997cbfd8-5nz4j 1/1 Running 0 2m11s"
},
{
"code": null,
"e": 8710,
"s": 8607,
"text": "We have to allow traffic from the internet to the application so that we can access it. To do so, run:"
},
{
"code": null,
"e": 8802,
"s": 8710,
"text": "kubectl expose deployment object-detection --type=LoadBalancer --port 80 --target-port 5000"
},
{
"code": null,
"e": 8972,
"s": 8802,
"text": "The port flag specifies the port number configured on the Load Balancer, and the target-port flag specifies the port number that the tf-od-api container is listening on."
},
{
"code": null,
"e": 9023,
"s": 8972,
"text": "To get the external IP, run the following command:"
},
{
"code": null,
"e": 9300,
"s": 9023,
"text": "kubectl get serviceOUTPUTNAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGEkubernetes ClusterIP 10.51.240.1 <none> 443/TCP 30mobject-detection LoadBalancer 10.51.245.79 35.193.230.83 80:31667/TCP 4m57s"
},
{
"code": null,
"e": 9449,
"s": 9300,
"text": "Now let’s check if our application is accessible. To do so we’ll run the same client.py but we have to give the external IP as the address argument:"
},
{
"code": null,
"e": 9702,
"s": 9449,
"text": "python client.py --address http://35.193.230.83/(my external IP) --image_path images/input_image.jpg --output_dir outputs/OUTPUTDetections are: [{‘person’: ‘79%’}, {‘chair’: ‘34%’}]the image size is: size=1920x1281the image is being written in outputs/"
},
{
"code": null,
"e": 9887,
"s": 9702,
"text": "If you see an output which is similar to when we ran it before, Congratulations! You’ve successfully deployed a containerized Tensorflow Object Detection API application on Kubernetes."
},
{
"code": null,
"e": 10025,
"s": 9887,
"text": "Do not forget to remove the cluster once you are done as it may incur charges. To do so, run the following command to delete the service:"
},
{
"code": null,
"e": 10065,
"s": 10025,
"text": "kubectl delete service object-detection"
},
{
"code": null,
"e": 10116,
"s": 10065,
"text": "And to delete the Cluster and it’s resources, run:"
},
{
"code": null,
"e": 10330,
"s": 10116,
"text": "gcloud container clusters delete object-detectionOUTPUTDeleting cluster object-detection...done.Deleted [https://container.googleapis.com/v1/projects/temp-kubernetes/zones/us-central1-a/clusters/object-detection]."
},
{
"code": null,
"e": 10535,
"s": 10330,
"text": "In this article, we have learned how to serve the Tensorflow Object Detection API using Flask, containerize the application using Docker and deploy the application on Kubernetes. Hope it has been of help."
}
] |
How do you make a button that adds text in HTML <input>? | Let’s say the following is our HTML button −
<button id="clickButton">Click the button to add the input into the belowText Box</button>
Use document.getElementById() to add a text in <input> on button click. Following is the code −
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<button id="clickButton">Click the button to add the input into the
below Text Box</button>
<br/><br />
<input id="readTheInput" />
<script>
document.getElementById("clickButton").addEventListener("click", () =>{
document.getElementById("readTheInput").value += "JavaScript";
});
</script>
</body>
</html>
To run the above program, save the file name “anyName.html(index.html)” and right click on the
file. Select the option “Open with Live Server” in VS Code editor.
This will produce the following output −
Here, I am going to click the button two times. This will produce the following output − | [
{
"code": null,
"e": 1107,
"s": 1062,
"text": "Let’s say the following is our HTML button −"
},
{
"code": null,
"e": 1198,
"s": 1107,
"text": "<button id=\"clickButton\">Click the button to add the input into the belowText Box</button>"
},
{
"code": null,
"e": 1294,
"s": 1198,
"text": "Use document.getElementById() to add a text in <input> on button click. Following is the code −"
},
{
"code": null,
"e": 1305,
"s": 1294,
"text": " Live Demo"
},
{
"code": null,
"e": 2016,
"s": 1305,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initialscale=1.0\">\n<title>Document</title>\n<link rel=\"stylesheet\" href=\"//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css\">\n<script src=\"https://code.jquery.com/jquery-1.12.4.js\"></script>\n<script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"></script>\n</head>\n<body>\n<button id=\"clickButton\">Click the button to add the input into the\nbelow Text Box</button>\n<br/><br />\n<input id=\"readTheInput\" />\n<script>\n document.getElementById(\"clickButton\").addEventListener(\"click\", () =>{\n document.getElementById(\"readTheInput\").value += \"JavaScript\";\n });\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2178,
"s": 2016,
"text": "To run the above program, save the file name “anyName.html(index.html)” and right click on the\nfile. Select the option “Open with Live Server” in VS Code editor."
},
{
"code": null,
"e": 2219,
"s": 2178,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2308,
"s": 2219,
"text": "Here, I am going to click the button two times. This will produce the following output −"
}
] |
CIFAR 100: Transfer Learning using EfficientNet | Towards Data Science | Convolutional Neural Network (CNN) is a class of deep neural networks commonly used to analyze images. In this article, we will together build a CNN model that can correctly recognize and classify colored images of objects into one of the 100 available classes of the CIFAR-100 dataset. In particular, we will reuse a state-of-the-art as the starting point for our model. This technique is called transfer learning. ➡️
Let us first understand what transfer learning is. I will not go into a lot of detail but will try to share some knowledge. 📝
As stated in the Handbook of Research on Machine Learning Applications, transfer learning is the improvement of learning in a new task through the transfer of knowledge from a related task that has already been learned.
In simple terms, transfer learning is a machine learning technique where a model trained on one task is re-purposed on a second related task. Deep learning networks are resource hungry and computationally expensive with millions of parameters. These networks are trained with a massive amount of data to avoid overfitting. Thus, when a state-of-the-art model is created it often takes researchers a lot of time in training. As a state-of-the-art model is trained after spending such a huge amount of resources, researchers thought that the benefits of such investments should be reaped many times and thus aroused the concept of transfer learning.
The best part of transfer learning is that we can either re-use the entire model or a certain part of it. Umm, intelligent! 😎 This way we don’t have to train the whole model. In particular, transfer learning saves time and gives better performance. For instance, using a pre-trained model which can recognize cars to now recognize trucks.
Let us now know a bit about the state-of-the-art model we will be using here.
EfficientNet is a family of CNN's built by Google. ✌ ️These CNNs not only provide better accuracy but also improve the efficiency of the models by reducing the number of parameters as compared to the other state-of-the-art models. EfficientNet-B0 model is a simple mobile-size baseline architecture and trained on the ImageNet dataset.
While building a neural network, our basic approach to improve the model performance is to increase the number of units or the number of layers. However, this approach or strategy doesn’t work always or I must say doesn’t help after a point. For instance, I built a 9-layer convolutional neural network model for the CIFAR-100 dataset and managed to achieve an accuracy of just 59%. Just a little more than random chance. 😏 My attempts of increasing the number of layers or units didn’t further improve the accuracy. ☹️ (Link to code)
EfficientNet works on the idea that providing an effective compound scaling method (scaling all dimensions of depth/width/resolution) for increasing the model size can help the model achieve maximum accuracy gains. The figure below is from the original paper which gives a nice visualization of scaling.
Note: EfficientNet comes in a lot of variants. I used EfficientNet-B0 because it's a small model. If you want you can try out other variants of EfficientNet.
So, let’s build an image recognition model using EfficientNet-B0. Please note that I will just be training the model in the blog post. In case you want to know the pre-processing part, please refer to this blog post.
Note: I will try to make most of the concepts clear but still, this article assumes a basic understanding of the Convolutional Neural Network (CNN). 📖
The code for this task is available on my Github. Please feel free to use it to build a more intelligent image recognition system.
To train a machine learning model, we need a training set. A good practice is to keep a validation set to choose the hyperparameters and a test set to test the model on unseen data.
Let us first import the libraries.
from sklearn.model_selection import StratifiedShuffleSplitimport cv2import albumentations as albufrom skimage.transform import resizeimport numpy as npimport pandas as pdimport matplotlib.pyplot as plt%matplotlib inlinefrom pylab import rcParamsfrom sklearn.metrics import accuracy_score, confusion_matrix, classification_reportfrom keras.callbacks import Callback, EarlyStopping, ReduceLROnPlateauimport tensorflow as tfimport kerasfrom keras.models import Sequential, load_modelfrom keras.layers import Dropout, Dense, GlobalAveragePooling2Dfrom keras.optimizers import Adamimport efficientnet.keras as efn
I have used stratified shuffle split to split my training set into training and validation set because it will preserve the percentage of samples in each of the 100 classes. Here is the code to perform splitting.
sss = StratifiedShuffleSplit(n_splits=2, test_size=0.2, random_state=123)for train_index, val_index in sss.split(X_train, y_train): X_train_data, X_val_data = X_train[train_index], X_train[val_index] y_train_data, y_val_data = y_train[train_index], y_train[val_index]print("Number of training samples: ", X_train_data.shape[0])print("Number of validation samples: ", X_val_data.shape[0])
The output gives the number of samples in each set.
Number of training samples: 40000 Number of validation samples: 10000
As per EfficientNet, we need to not only scale the width and depth of the model (which will be taken care by the pre-trained model) but the resolution of the images as well. EfficientNet-B0 model architecture requires the image to be of size (224, 224). So, let us resize our images of size (32, 32) to the new size.
height = 224width = 224channels = 3input_shape = (height, width, channels)
The below function resize_img will take image and shape as the input and resize each image. I have used the bicubic interpolation method to upscale the images. It considers the closest 4 * 4 neighborhood of known pixels for a total of 16 pixels. This method produces noticeably sharper images and is considered an ideal combination of processing time and output quality.
def resize_img(img, shape): return cv2.resize(img, (shape[1], shape[0]), interpolation=cv2.INTER_CUBIC)
We all know that the performance of the deep learning model usually improves with the addition of more data, so I planned for image augmentation but memory is always a big constraint for deep learning models as they have a lot of trainable parameters. So, I opted for the albumentations library of python which helped in real-time data augmentation. (If you are not aware of this library, I strongly recommend you to look at its website and GitHub page.)
I created my own custom data generator class using the Keras data generator class. The parameters, horizontal flip, vertical flip, grid distortion, and elastic transformation were tuned to extend the dataset (you can try out other parameters too).
As the distribution of the feature values in the images can be very different from each other, the images are normalized by dividing each image by 255 as the range of each individual color is [0,255]. Thus, the rescaled images have all features in the new range [0,1].
I did all these transformations batch-wise. Also, I only applied augmentation to the training dataset and left the validation and the test dataset as it is.
Before writing the custom data generator class, let us first set our constants.
n_classes = 100epochs = 15batch_size = 8
Here is the code for the custom data generator class.
class DataGenerator(keras.utils.Sequence): def __init__(self, images, labels=None, mode='fit', batch_size=batch_size, dim=(height, width), channels=channels, n_classes=n_classes, shuffle=True, augment=False): #initializing the configuration of the generator self.images = images self.labels = labels self.mode = mode self.batch_size = batch_size self.dim = dim self.channels = channels self.n_classes = n_classes self.shuffle = shuffle self.augment = augment self.on_epoch_end() #method to be called after every epoch def on_epoch_end(self): self.indexes = np.arange(self.images.shape[0]) if self.shuffle == True: np.random.shuffle(self.indexes) #return numbers of steps in an epoch using samples & batch size def __len__(self): return int(np.floor(len(self.images) / self.batch_size)) #this method is called with the batch number as an argument to #obtain a given batch of data def __getitem__(self, index): #generate one batch of data #generate indexes of batch batch_indexes = self.indexes[index * self.batch_size:(index+1) * self.batch_size] #generate mini-batch of X X = np.empty((self.batch_size, *self.dim, self.channels)) for i, ID in enumerate(batch_indexes): #generate pre-processed image img = self.images[ID] #image rescaling img = img.astype(np.float32)/255. #resizing as per new dimensions img = resize_img(img, self.dim) X[i] = img #generate mini-batch of y if self.mode == 'fit': y = self.labels[batch_indexes] #augmentation on the training dataset if self.augment == True: X = self.__augment_batch(X) return X, y elif self.mode == 'predict': return X else: raise AttributeError("The mode should be set to either 'fit' or 'predict'.") #augmentation for one image def __random_transform(self, img): composition = albu.Compose([albu.HorizontalFlip(p=0.5), albu.VerticalFlip(p=0.5), albu.GridDistortion(p=0.2), albu.ElasticTransform(p=0.2)]) return composition(image=img)['image'] #augmentation for batch of images def __augment_batch(self, img_batch): for i in range(img_batch.shape[0]): img_batch[i] = self.__random_transform(img_batch[i]) return img_batch
Let us apply the data generator class to our training and validation sets.
train_data_generator = DataGenerator(X_train_data, y_train_data, augment=True) valid_data_generator = DataGenerator(X_val_data, y_val_data, augment=False)
The EfficientNet class is available in Keras to help in transfer learning with ease. I used the EfficientNet-B0 class with ImageNet weights. Since I used this model just for feature extraction, I did not include the fully-connected layer at the top of the network instead specified the input shape and pooling. I also added my own pooling and dense layers.
Here is the code to use the pre-trained EfficientNet-B0 model.
efnb0 = efn.EfficientNetB0(weights='imagenet', include_top=False, input_shape=input_shape, classes=n_classes)model = Sequential()model.add(efnb0)model.add(GlobalAveragePooling2D())model.add(Dropout(0.5))model.add(Dense(n_classes, activation='softmax'))model.summary()
Here is the output.
The model has 4,135,648 trainable parameters. 😳
optimizer = Adam(lr=0.0001)#early stopping to monitor the validation loss and avoid overfittingearly_stop = EarlyStopping(monitor='val_loss', mode='min', verbose=1, patience=10, restore_best_weights=True)#reducing learning rate on plateaurlrop = ReduceLROnPlateau(monitor='val_loss', mode='min', patience= 5, factor= 0.5, min_lr= 1e-6, verbose=1)#model compilingmodel.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])
After compiling our model, let us fit it on our training dataset and validate it on the validation dataset.
model_history = model.fit_generator(train_data_generator, validation_data = valid_data_generator, callbacks = [early_stop, rlrop],verbose = 1, epochs = epochs)#saving the trained model weights as data file in .h5 formatmodel.save_weights("cifar_efficientnetb0_weights.h5")
Here are the snippets of training.
We can see that the model adjusted the learning rate on the 14th epoch and we get a final accuracy of 84.82% on the training set, which is pretty good. But wait, we need to look at the test accuracy too.
Visualization helps to see things better. So, let’s plot the accuracy and loss plots.
#plot to visualize the loss and accuracy against number of epochsplt.figure(figsize=(18,8))plt.suptitle('Loss and Accuracy Plots', fontsize=18)plt.subplot(1,2,1)plt.plot(model_history.history['loss'], label='Training Loss')plt.plot(model_history.history['val_loss'], label='Validation Loss')plt.legend()plt.xlabel('Number of epochs', fontsize=15)plt.ylabel('Loss', fontsize=15)plt.subplot(1,2,2)plt.plot(model_history.history['accuracy'], label='Train Accuracy')plt.plot(model_history.history['val_accuracy'], label='Validation Accuracy')plt.legend()plt.xlabel('Number of epochs', fontsize=14)plt.ylabel('Accuracy', fontsize=14)plt.show()
Let us evaluate our model now.
valid_loss, valid_accuracy = model.evaluate_generator(generator = valid_data_generator, verbose = 1)print('Validation Accuracy: ', round((valid_accuracy * 100), 2), "%")
Output:
1250/1250 [==============================] - 85s 68ms/step Validation Accuracy: 82.3 %
Now, it's time to look at the test dataset accuracy.
y_pred = model.predict_generator(DataGenerator(X_test, mode='predict', augment=False, shuffle=False), verbose=1)y_pred = np.argmax(y_pred, axis=1)test_accuracy = accuracy_score(np.argmax(y_test, axis=1), y_pred)print('Test Accuracy: ', round((test_accuracy * 100), 2), "%")
Output:
1250/1250 [==============================] - 78s 63ms/stepTest Accuracy: 81.79 %
The results of the training are pretty good. We got an accuracy of 81.79% on the test dataset. 💃
Confusion matrix and classification reports can be generated for the model using the following code.
cm = confusion_matrix(np.argmax(y_test, axis=1), y_pred)print(cm)target = ["Category {}".format(i) for i in range(n_classes)]print(classification_report(np.argmax(y_test, axis=1), y_pred, target_names=target))
Here is a code snippet for the first 11 classes.
From the classification report, we can see that a few categories have been predicted well whereas a few have been incorrectly predicted.
If you want to visualize the predictions, here is the code.
prediction = pd.DataFrame(y_pred)rcParams['figure.figsize'] = 12,15num_row = 4num_col = 4imageId = np.random.randint(0, len(X_test), num_row * num_col)fig, axes = plt.subplots(num_row, num_col)for i in range(0, num_row): for j in range(0, num_col): k = (i*num_col)+j axes[i,j].imshow(X_test[imageId[k]]) axes[i,j].set_title("True: " + str(subCategory.iloc[testData['fine_labels'][imageId[k]]][0]).capitalize() + "\nPredicted: " + str(subCategory.iloc[prediction.iloc[imageId[k]]]).split()[2].capitalize(), fontsize=14) axes[i,j].axis('off') fig.suptitle("Images with True and Predicted Labels", fontsize=18) plt.show()
Here is the snippet of the output.
You can see that our model got confused between a motorcycle and a bicycle. 🙄 But, we can see that most of the predictions were correct. ✅
Deep learning is all about experimentation. It is quite possible that the performance of this model can be improved further using the other state-of-the-art versions of EfficientNet. Hyperparameter tuning is also an important aspect of deep learning and can help in increasing accuracy.
I hope the blog helped you in understanding how to perform transfer learning. Please feel free to experiment more to get better performance. Check out my GitHub for the complete code and my previous article for the initial steps. Also, I highly recommend you to read the original paper. It is an interesting read!
Related article:
towardsdatascience.com
Reference:
Original paper: https://arxiv.org/pdf/1905.11946.pdfThis Kaggle notebook gave me direction on how to perform transfer learning.
Original paper: https://arxiv.org/pdf/1905.11946.pdf
This Kaggle notebook gave me direction on how to perform transfer learning.
Thank you, everyone, for reading this. Do share your valuable feedback or suggestion. Happy reading! 📗 🖌 Also, I would love to know if you get better performance on CIFAR-100 using transfer learning. | [
{
"code": null,
"e": 591,
"s": 172,
"text": "Convolutional Neural Network (CNN) is a class of deep neural networks commonly used to analyze images. In this article, we will together build a CNN model that can correctly recognize and classify colored images of objects into one of the 100 available classes of the CIFAR-100 dataset. In particular, we will reuse a state-of-the-art as the starting point for our model. This technique is called transfer learning. ➡️"
},
{
"code": null,
"e": 717,
"s": 591,
"text": "Let us first understand what transfer learning is. I will not go into a lot of detail but will try to share some knowledge. 📝"
},
{
"code": null,
"e": 937,
"s": 717,
"text": "As stated in the Handbook of Research on Machine Learning Applications, transfer learning is the improvement of learning in a new task through the transfer of knowledge from a related task that has already been learned."
},
{
"code": null,
"e": 1585,
"s": 937,
"text": "In simple terms, transfer learning is a machine learning technique where a model trained on one task is re-purposed on a second related task. Deep learning networks are resource hungry and computationally expensive with millions of parameters. These networks are trained with a massive amount of data to avoid overfitting. Thus, when a state-of-the-art model is created it often takes researchers a lot of time in training. As a state-of-the-art model is trained after spending such a huge amount of resources, researchers thought that the benefits of such investments should be reaped many times and thus aroused the concept of transfer learning."
},
{
"code": null,
"e": 1924,
"s": 1585,
"text": "The best part of transfer learning is that we can either re-use the entire model or a certain part of it. Umm, intelligent! 😎 This way we don’t have to train the whole model. In particular, transfer learning saves time and gives better performance. For instance, using a pre-trained model which can recognize cars to now recognize trucks."
},
{
"code": null,
"e": 2002,
"s": 1924,
"text": "Let us now know a bit about the state-of-the-art model we will be using here."
},
{
"code": null,
"e": 2338,
"s": 2002,
"text": "EfficientNet is a family of CNN's built by Google. ✌ ️These CNNs not only provide better accuracy but also improve the efficiency of the models by reducing the number of parameters as compared to the other state-of-the-art models. EfficientNet-B0 model is a simple mobile-size baseline architecture and trained on the ImageNet dataset."
},
{
"code": null,
"e": 2873,
"s": 2338,
"text": "While building a neural network, our basic approach to improve the model performance is to increase the number of units or the number of layers. However, this approach or strategy doesn’t work always or I must say doesn’t help after a point. For instance, I built a 9-layer convolutional neural network model for the CIFAR-100 dataset and managed to achieve an accuracy of just 59%. Just a little more than random chance. 😏 My attempts of increasing the number of layers or units didn’t further improve the accuracy. ☹️ (Link to code)"
},
{
"code": null,
"e": 3177,
"s": 2873,
"text": "EfficientNet works on the idea that providing an effective compound scaling method (scaling all dimensions of depth/width/resolution) for increasing the model size can help the model achieve maximum accuracy gains. The figure below is from the original paper which gives a nice visualization of scaling."
},
{
"code": null,
"e": 3335,
"s": 3177,
"text": "Note: EfficientNet comes in a lot of variants. I used EfficientNet-B0 because it's a small model. If you want you can try out other variants of EfficientNet."
},
{
"code": null,
"e": 3552,
"s": 3335,
"text": "So, let’s build an image recognition model using EfficientNet-B0. Please note that I will just be training the model in the blog post. In case you want to know the pre-processing part, please refer to this blog post."
},
{
"code": null,
"e": 3703,
"s": 3552,
"text": "Note: I will try to make most of the concepts clear but still, this article assumes a basic understanding of the Convolutional Neural Network (CNN). 📖"
},
{
"code": null,
"e": 3834,
"s": 3703,
"text": "The code for this task is available on my Github. Please feel free to use it to build a more intelligent image recognition system."
},
{
"code": null,
"e": 4016,
"s": 3834,
"text": "To train a machine learning model, we need a training set. A good practice is to keep a validation set to choose the hyperparameters and a test set to test the model on unseen data."
},
{
"code": null,
"e": 4051,
"s": 4016,
"text": "Let us first import the libraries."
},
{
"code": null,
"e": 4660,
"s": 4051,
"text": "from sklearn.model_selection import StratifiedShuffleSplitimport cv2import albumentations as albufrom skimage.transform import resizeimport numpy as npimport pandas as pdimport matplotlib.pyplot as plt%matplotlib inlinefrom pylab import rcParamsfrom sklearn.metrics import accuracy_score, confusion_matrix, classification_reportfrom keras.callbacks import Callback, EarlyStopping, ReduceLROnPlateauimport tensorflow as tfimport kerasfrom keras.models import Sequential, load_modelfrom keras.layers import Dropout, Dense, GlobalAveragePooling2Dfrom keras.optimizers import Adamimport efficientnet.keras as efn"
},
{
"code": null,
"e": 4873,
"s": 4660,
"text": "I have used stratified shuffle split to split my training set into training and validation set because it will preserve the percentage of samples in each of the 100 classes. Here is the code to perform splitting."
},
{
"code": null,
"e": 5267,
"s": 4873,
"text": "sss = StratifiedShuffleSplit(n_splits=2, test_size=0.2, random_state=123)for train_index, val_index in sss.split(X_train, y_train): X_train_data, X_val_data = X_train[train_index], X_train[val_index] y_train_data, y_val_data = y_train[train_index], y_train[val_index]print(\"Number of training samples: \", X_train_data.shape[0])print(\"Number of validation samples: \", X_val_data.shape[0])"
},
{
"code": null,
"e": 5319,
"s": 5267,
"text": "The output gives the number of samples in each set."
},
{
"code": null,
"e": 5391,
"s": 5319,
"text": "Number of training samples: 40000 Number of validation samples: 10000"
},
{
"code": null,
"e": 5708,
"s": 5391,
"text": "As per EfficientNet, we need to not only scale the width and depth of the model (which will be taken care by the pre-trained model) but the resolution of the images as well. EfficientNet-B0 model architecture requires the image to be of size (224, 224). So, let us resize our images of size (32, 32) to the new size."
},
{
"code": null,
"e": 5783,
"s": 5708,
"text": "height = 224width = 224channels = 3input_shape = (height, width, channels)"
},
{
"code": null,
"e": 6154,
"s": 5783,
"text": "The below function resize_img will take image and shape as the input and resize each image. I have used the bicubic interpolation method to upscale the images. It considers the closest 4 * 4 neighborhood of known pixels for a total of 16 pixels. This method produces noticeably sharper images and is considered an ideal combination of processing time and output quality."
},
{
"code": null,
"e": 6261,
"s": 6154,
"text": "def resize_img(img, shape): return cv2.resize(img, (shape[1], shape[0]), interpolation=cv2.INTER_CUBIC)"
},
{
"code": null,
"e": 6716,
"s": 6261,
"text": "We all know that the performance of the deep learning model usually improves with the addition of more data, so I planned for image augmentation but memory is always a big constraint for deep learning models as they have a lot of trainable parameters. So, I opted for the albumentations library of python which helped in real-time data augmentation. (If you are not aware of this library, I strongly recommend you to look at its website and GitHub page.)"
},
{
"code": null,
"e": 6964,
"s": 6716,
"text": "I created my own custom data generator class using the Keras data generator class. The parameters, horizontal flip, vertical flip, grid distortion, and elastic transformation were tuned to extend the dataset (you can try out other parameters too)."
},
{
"code": null,
"e": 7233,
"s": 6964,
"text": "As the distribution of the feature values in the images can be very different from each other, the images are normalized by dividing each image by 255 as the range of each individual color is [0,255]. Thus, the rescaled images have all features in the new range [0,1]."
},
{
"code": null,
"e": 7390,
"s": 7233,
"text": "I did all these transformations batch-wise. Also, I only applied augmentation to the training dataset and left the validation and the test dataset as it is."
},
{
"code": null,
"e": 7470,
"s": 7390,
"text": "Before writing the custom data generator class, let us first set our constants."
},
{
"code": null,
"e": 7511,
"s": 7470,
"text": "n_classes = 100epochs = 15batch_size = 8"
},
{
"code": null,
"e": 7565,
"s": 7511,
"text": "Here is the code for the custom data generator class."
},
{
"code": null,
"e": 10231,
"s": 7565,
"text": "class DataGenerator(keras.utils.Sequence): def __init__(self, images, labels=None, mode='fit', batch_size=batch_size, dim=(height, width), channels=channels, n_classes=n_classes, shuffle=True, augment=False): #initializing the configuration of the generator self.images = images self.labels = labels self.mode = mode self.batch_size = batch_size self.dim = dim self.channels = channels self.n_classes = n_classes self.shuffle = shuffle self.augment = augment self.on_epoch_end() #method to be called after every epoch def on_epoch_end(self): self.indexes = np.arange(self.images.shape[0]) if self.shuffle == True: np.random.shuffle(self.indexes) #return numbers of steps in an epoch using samples & batch size def __len__(self): return int(np.floor(len(self.images) / self.batch_size)) #this method is called with the batch number as an argument to #obtain a given batch of data def __getitem__(self, index): #generate one batch of data #generate indexes of batch batch_indexes = self.indexes[index * self.batch_size:(index+1) * self.batch_size] #generate mini-batch of X X = np.empty((self.batch_size, *self.dim, self.channels)) for i, ID in enumerate(batch_indexes): #generate pre-processed image img = self.images[ID] #image rescaling img = img.astype(np.float32)/255. #resizing as per new dimensions img = resize_img(img, self.dim) X[i] = img #generate mini-batch of y if self.mode == 'fit': y = self.labels[batch_indexes] #augmentation on the training dataset if self.augment == True: X = self.__augment_batch(X) return X, y elif self.mode == 'predict': return X else: raise AttributeError(\"The mode should be set to either 'fit' or 'predict'.\") #augmentation for one image def __random_transform(self, img): composition = albu.Compose([albu.HorizontalFlip(p=0.5), albu.VerticalFlip(p=0.5), albu.GridDistortion(p=0.2), albu.ElasticTransform(p=0.2)]) return composition(image=img)['image'] #augmentation for batch of images def __augment_batch(self, img_batch): for i in range(img_batch.shape[0]): img_batch[i] = self.__random_transform(img_batch[i]) return img_batch"
},
{
"code": null,
"e": 10306,
"s": 10231,
"text": "Let us apply the data generator class to our training and validation sets."
},
{
"code": null,
"e": 10461,
"s": 10306,
"text": "train_data_generator = DataGenerator(X_train_data, y_train_data, augment=True) valid_data_generator = DataGenerator(X_val_data, y_val_data, augment=False)"
},
{
"code": null,
"e": 10818,
"s": 10461,
"text": "The EfficientNet class is available in Keras to help in transfer learning with ease. I used the EfficientNet-B0 class with ImageNet weights. Since I used this model just for feature extraction, I did not include the fully-connected layer at the top of the network instead specified the input shape and pooling. I also added my own pooling and dense layers."
},
{
"code": null,
"e": 10881,
"s": 10818,
"text": "Here is the code to use the pre-trained EfficientNet-B0 model."
},
{
"code": null,
"e": 11149,
"s": 10881,
"text": "efnb0 = efn.EfficientNetB0(weights='imagenet', include_top=False, input_shape=input_shape, classes=n_classes)model = Sequential()model.add(efnb0)model.add(GlobalAveragePooling2D())model.add(Dropout(0.5))model.add(Dense(n_classes, activation='softmax'))model.summary()"
},
{
"code": null,
"e": 11169,
"s": 11149,
"text": "Here is the output."
},
{
"code": null,
"e": 11217,
"s": 11169,
"text": "The model has 4,135,648 trainable parameters. 😳"
},
{
"code": null,
"e": 11669,
"s": 11217,
"text": "optimizer = Adam(lr=0.0001)#early stopping to monitor the validation loss and avoid overfittingearly_stop = EarlyStopping(monitor='val_loss', mode='min', verbose=1, patience=10, restore_best_weights=True)#reducing learning rate on plateaurlrop = ReduceLROnPlateau(monitor='val_loss', mode='min', patience= 5, factor= 0.5, min_lr= 1e-6, verbose=1)#model compilingmodel.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])"
},
{
"code": null,
"e": 11777,
"s": 11669,
"text": "After compiling our model, let us fit it on our training dataset and validate it on the validation dataset."
},
{
"code": null,
"e": 12050,
"s": 11777,
"text": "model_history = model.fit_generator(train_data_generator, validation_data = valid_data_generator, callbacks = [early_stop, rlrop],verbose = 1, epochs = epochs)#saving the trained model weights as data file in .h5 formatmodel.save_weights(\"cifar_efficientnetb0_weights.h5\")"
},
{
"code": null,
"e": 12085,
"s": 12050,
"text": "Here are the snippets of training."
},
{
"code": null,
"e": 12289,
"s": 12085,
"text": "We can see that the model adjusted the learning rate on the 14th epoch and we get a final accuracy of 84.82% on the training set, which is pretty good. But wait, we need to look at the test accuracy too."
},
{
"code": null,
"e": 12375,
"s": 12289,
"text": "Visualization helps to see things better. So, let’s plot the accuracy and loss plots."
},
{
"code": null,
"e": 13014,
"s": 12375,
"text": "#plot to visualize the loss and accuracy against number of epochsplt.figure(figsize=(18,8))plt.suptitle('Loss and Accuracy Plots', fontsize=18)plt.subplot(1,2,1)plt.plot(model_history.history['loss'], label='Training Loss')plt.plot(model_history.history['val_loss'], label='Validation Loss')plt.legend()plt.xlabel('Number of epochs', fontsize=15)plt.ylabel('Loss', fontsize=15)plt.subplot(1,2,2)plt.plot(model_history.history['accuracy'], label='Train Accuracy')plt.plot(model_history.history['val_accuracy'], label='Validation Accuracy')plt.legend()plt.xlabel('Number of epochs', fontsize=14)plt.ylabel('Accuracy', fontsize=14)plt.show()"
},
{
"code": null,
"e": 13045,
"s": 13014,
"text": "Let us evaluate our model now."
},
{
"code": null,
"e": 13215,
"s": 13045,
"text": "valid_loss, valid_accuracy = model.evaluate_generator(generator = valid_data_generator, verbose = 1)print('Validation Accuracy: ', round((valid_accuracy * 100), 2), \"%\")"
},
{
"code": null,
"e": 13223,
"s": 13215,
"text": "Output:"
},
{
"code": null,
"e": 13311,
"s": 13223,
"text": "1250/1250 [==============================] - 85s 68ms/step Validation Accuracy: 82.3 %"
},
{
"code": null,
"e": 13364,
"s": 13311,
"text": "Now, it's time to look at the test dataset accuracy."
},
{
"code": null,
"e": 13638,
"s": 13364,
"text": "y_pred = model.predict_generator(DataGenerator(X_test, mode='predict', augment=False, shuffle=False), verbose=1)y_pred = np.argmax(y_pred, axis=1)test_accuracy = accuracy_score(np.argmax(y_test, axis=1), y_pred)print('Test Accuracy: ', round((test_accuracy * 100), 2), \"%\")"
},
{
"code": null,
"e": 13646,
"s": 13638,
"text": "Output:"
},
{
"code": null,
"e": 13728,
"s": 13646,
"text": "1250/1250 [==============================] - 78s 63ms/stepTest Accuracy: 81.79 %"
},
{
"code": null,
"e": 13825,
"s": 13728,
"text": "The results of the training are pretty good. We got an accuracy of 81.79% on the test dataset. 💃"
},
{
"code": null,
"e": 13926,
"s": 13825,
"text": "Confusion matrix and classification reports can be generated for the model using the following code."
},
{
"code": null,
"e": 14136,
"s": 13926,
"text": "cm = confusion_matrix(np.argmax(y_test, axis=1), y_pred)print(cm)target = [\"Category {}\".format(i) for i in range(n_classes)]print(classification_report(np.argmax(y_test, axis=1), y_pred, target_names=target))"
},
{
"code": null,
"e": 14185,
"s": 14136,
"text": "Here is a code snippet for the first 11 classes."
},
{
"code": null,
"e": 14322,
"s": 14185,
"text": "From the classification report, we can see that a few categories have been predicted well whereas a few have been incorrectly predicted."
},
{
"code": null,
"e": 14382,
"s": 14322,
"text": "If you want to visualize the predictions, here is the code."
},
{
"code": null,
"e": 15039,
"s": 14382,
"text": "prediction = pd.DataFrame(y_pred)rcParams['figure.figsize'] = 12,15num_row = 4num_col = 4imageId = np.random.randint(0, len(X_test), num_row * num_col)fig, axes = plt.subplots(num_row, num_col)for i in range(0, num_row): for j in range(0, num_col): k = (i*num_col)+j axes[i,j].imshow(X_test[imageId[k]]) axes[i,j].set_title(\"True: \" + str(subCategory.iloc[testData['fine_labels'][imageId[k]]][0]).capitalize() + \"\\nPredicted: \" + str(subCategory.iloc[prediction.iloc[imageId[k]]]).split()[2].capitalize(), fontsize=14) axes[i,j].axis('off') fig.suptitle(\"Images with True and Predicted Labels\", fontsize=18) plt.show()"
},
{
"code": null,
"e": 15074,
"s": 15039,
"text": "Here is the snippet of the output."
},
{
"code": null,
"e": 15213,
"s": 15074,
"text": "You can see that our model got confused between a motorcycle and a bicycle. 🙄 But, we can see that most of the predictions were correct. ✅"
},
{
"code": null,
"e": 15500,
"s": 15213,
"text": "Deep learning is all about experimentation. It is quite possible that the performance of this model can be improved further using the other state-of-the-art versions of EfficientNet. Hyperparameter tuning is also an important aspect of deep learning and can help in increasing accuracy."
},
{
"code": null,
"e": 15814,
"s": 15500,
"text": "I hope the blog helped you in understanding how to perform transfer learning. Please feel free to experiment more to get better performance. Check out my GitHub for the complete code and my previous article for the initial steps. Also, I highly recommend you to read the original paper. It is an interesting read!"
},
{
"code": null,
"e": 15831,
"s": 15814,
"text": "Related article:"
},
{
"code": null,
"e": 15854,
"s": 15831,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 15865,
"s": 15854,
"text": "Reference:"
},
{
"code": null,
"e": 15993,
"s": 15865,
"text": "Original paper: https://arxiv.org/pdf/1905.11946.pdfThis Kaggle notebook gave me direction on how to perform transfer learning."
},
{
"code": null,
"e": 16046,
"s": 15993,
"text": "Original paper: https://arxiv.org/pdf/1905.11946.pdf"
},
{
"code": null,
"e": 16122,
"s": 16046,
"text": "This Kaggle notebook gave me direction on how to perform transfer learning."
}
] |
Proof that vertex cover is NP complete - GeeksforGeeks | 03 Aug, 2018
Prerequisite – Vertex Cover Problem, NP-CompletenessProblem – Given a graph G(V, E) and a positive integer k, the problem is to find whether there is a subset V’ of vertices of size at most k, such that every edge in the graph is connected to some vertex in V’.
Explanation –First let us understand the notion of an instance of a problem. An instance of a problem is nothing but an input to the given problem. An instance of the Vertex Cover problem is a graph G (V, E) and a positive integer k, and the problem is to check whether a vertex cover of size at most k exists in G. Since an NP Complete problem, by definition, is a problem which is both in NP and NP hard, the proof for the statement that a problem is NP Complete consists of two parts:
Proof that vertex cover is in NP –If any problem is in NP, then, given a ‘certificate’ (a solution) to the problem and an instance of the problem (a graph G and a positive integer k, in this case), we will be able to verify (check whether the solution given is correct or not) the certificate in polynomial time.The certificate for the vertex cover problem is a subset V’ of V, which contains the vertices in the vertex cover. We can check whether the set V’ is a vertex cover of size k using the following strategy (for a graph G(V, E)):let count be an integer
set count to 0
for each vertex v in V’
remove all edges adjacent to v from set E
increment count by 1
if count = k and E is empty
then
the given solution is correct
else
the given solution is wrong
It is plain to see that this can be done in polynomial time. Thus the vertex cover problem is in the class NP.Proof that vertex cover is NP Hard –To prove that Vertex Cover is NP Hard, we take some problem which has already been proven to be NP Hard, and show that this problem can be reduced to the Vertex Cover problem. For this, we consider the Clique problem, which is NP Complete (and hence NP Hard).“In computer science, the clique problem is the computational problem of finding cliques (subsets of vertices, all adjacent to each other, also called complete subgraphs) in a graph.”Here, we consider the problem of finding out whether there is a clique of size k in the given graph. Therefore, an instance of the clique problem is a graph G (V, E) and a non-negative integer k, and we need to check for the existence of a clique ofsize k in G.Now, we need to show that any instance (G, k) of the Clique problem can be reduced to an instance of the vertex cover problem. Consider the graph G’ which consists of all edges not in G, but in the complete graph using all vertices in G. Let us call this the complement of G. Now, the problem of finding whether a clique of size k exists in the graph G is the same as the problem of finding whether there is a vertex cover of size |V| – k in G’. We need to show that this is indeed the case.Assume that there is a clique of size k in G. Let the set of vertices in the clique be V’. This means |V’| = k. In the complement graph G’, let us pick any edge (u, v). Then at least one of u or v must be in the set V – V’. This is because, if both u and v were from the set V’, then the edge (u, v) would belong to V’, which, in turn would mean that the edge (u, v) is in G. This is not possible since (u, v) is not in G. Thus, all edges in G’ are covered by vertices in the set V – V’.Now assume that there is a vertex cover V’’ of size |V| – k in G’. This means that all edges in G’ are connected to some vertex in V’’. As a result, if we pick any edge (u, v) from G’, both of them cannot be outside the set V’’. This means, alledges (u, v) such that both u and v are outside the set V’’ are in G, i.e., these edges constitute a clique of size k.
Proof that vertex cover is in NP –If any problem is in NP, then, given a ‘certificate’ (a solution) to the problem and an instance of the problem (a graph G and a positive integer k, in this case), we will be able to verify (check whether the solution given is correct or not) the certificate in polynomial time.The certificate for the vertex cover problem is a subset V’ of V, which contains the vertices in the vertex cover. We can check whether the set V’ is a vertex cover of size k using the following strategy (for a graph G(V, E)):let count be an integer
set count to 0
for each vertex v in V’
remove all edges adjacent to v from set E
increment count by 1
if count = k and E is empty
then
the given solution is correct
else
the given solution is wrong
It is plain to see that this can be done in polynomial time. Thus the vertex cover problem is in the class NP.
The certificate for the vertex cover problem is a subset V’ of V, which contains the vertices in the vertex cover. We can check whether the set V’ is a vertex cover of size k using the following strategy (for a graph G(V, E)):
let count be an integer
set count to 0
for each vertex v in V’
remove all edges adjacent to v from set E
increment count by 1
if count = k and E is empty
then
the given solution is correct
else
the given solution is wrong
It is plain to see that this can be done in polynomial time. Thus the vertex cover problem is in the class NP.
Proof that vertex cover is NP Hard –To prove that Vertex Cover is NP Hard, we take some problem which has already been proven to be NP Hard, and show that this problem can be reduced to the Vertex Cover problem. For this, we consider the Clique problem, which is NP Complete (and hence NP Hard).“In computer science, the clique problem is the computational problem of finding cliques (subsets of vertices, all adjacent to each other, also called complete subgraphs) in a graph.”Here, we consider the problem of finding out whether there is a clique of size k in the given graph. Therefore, an instance of the clique problem is a graph G (V, E) and a non-negative integer k, and we need to check for the existence of a clique ofsize k in G.Now, we need to show that any instance (G, k) of the Clique problem can be reduced to an instance of the vertex cover problem. Consider the graph G’ which consists of all edges not in G, but in the complete graph using all vertices in G. Let us call this the complement of G. Now, the problem of finding whether a clique of size k exists in the graph G is the same as the problem of finding whether there is a vertex cover of size |V| – k in G’. We need to show that this is indeed the case.Assume that there is a clique of size k in G. Let the set of vertices in the clique be V’. This means |V’| = k. In the complement graph G’, let us pick any edge (u, v). Then at least one of u or v must be in the set V – V’. This is because, if both u and v were from the set V’, then the edge (u, v) would belong to V’, which, in turn would mean that the edge (u, v) is in G. This is not possible since (u, v) is not in G. Thus, all edges in G’ are covered by vertices in the set V – V’.Now assume that there is a vertex cover V’’ of size |V| – k in G’. This means that all edges in G’ are connected to some vertex in V’’. As a result, if we pick any edge (u, v) from G’, both of them cannot be outside the set V’’. This means, alledges (u, v) such that both u and v are outside the set V’’ are in G, i.e., these edges constitute a clique of size k.
“In computer science, the clique problem is the computational problem of finding cliques (subsets of vertices, all adjacent to each other, also called complete subgraphs) in a graph.”
Here, we consider the problem of finding out whether there is a clique of size k in the given graph. Therefore, an instance of the clique problem is a graph G (V, E) and a non-negative integer k, and we need to check for the existence of a clique ofsize k in G.
Now, we need to show that any instance (G, k) of the Clique problem can be reduced to an instance of the vertex cover problem. Consider the graph G’ which consists of all edges not in G, but in the complete graph using all vertices in G. Let us call this the complement of G. Now, the problem of finding whether a clique of size k exists in the graph G is the same as the problem of finding whether there is a vertex cover of size |V| – k in G’. We need to show that this is indeed the case.
Assume that there is a clique of size k in G. Let the set of vertices in the clique be V’. This means |V’| = k. In the complement graph G’, let us pick any edge (u, v). Then at least one of u or v must be in the set V – V’. This is because, if both u and v were from the set V’, then the edge (u, v) would belong to V’, which, in turn would mean that the edge (u, v) is in G. This is not possible since (u, v) is not in G. Thus, all edges in G’ are covered by vertices in the set V – V’.
Now assume that there is a vertex cover V’’ of size |V| – k in G’. This means that all edges in G’ are connected to some vertex in V’’. As a result, if we pick any edge (u, v) from G’, both of them cannot be outside the set V’’. This means, alledges (u, v) such that both u and v are outside the set V’’ are in G, i.e., these edges constitute a clique of size k.
Thus, we can say that there is a clique of size k in graph G if and only if there is a vertex cover of size |V| – k in G’, and hence, any instance of the clique problem can be reduced to an instance of the vertex cover problem. Thus, vertex cover is NP Hard. Since vertex cover is in both NP and NP Hard classes, it is NP Complete.
To understand the proof, consider the following example graph and its complement:
See for – Proof that Hamiltonian Path is NP-Complete
Algorithms-NP Complete
NP Complete
NPHard
Engineering Mathematics
GATE CS
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Relationship between number of nodes and height of binary tree
Inequalities in LaTeX
Mathematics | Walks, Trails, Paths, Cycles and Circuits in Graph
Arrow Symbols in LaTeX
Newton's Divided Difference Interpolation Formula
Layers of OSI Model
ACID Properties in DBMS
TCP/IP Model
Page Replacement Algorithms in Operating Systems
Types of Operating Systems | [
{
"code": null,
"e": 29836,
"s": 29808,
"text": "\n03 Aug, 2018"
},
{
"code": null,
"e": 30098,
"s": 29836,
"text": "Prerequisite – Vertex Cover Problem, NP-CompletenessProblem – Given a graph G(V, E) and a positive integer k, the problem is to find whether there is a subset V’ of vertices of size at most k, such that every edge in the graph is connected to some vertex in V’."
},
{
"code": null,
"e": 30586,
"s": 30098,
"text": "Explanation –First let us understand the notion of an instance of a problem. An instance of a problem is nothing but an input to the given problem. An instance of the Vertex Cover problem is a graph G (V, E) and a positive integer k, and the problem is to check whether a vertex cover of size at most k exists in G. Since an NP Complete problem, by definition, is a problem which is both in NP and NP hard, the proof for the statement that a problem is NP Complete consists of two parts:"
},
{
"code": null,
"e": 33572,
"s": 30586,
"text": "Proof that vertex cover is in NP –If any problem is in NP, then, given a ‘certificate’ (a solution) to the problem and an instance of the problem (a graph G and a positive integer k, in this case), we will be able to verify (check whether the solution given is correct or not) the certificate in polynomial time.The certificate for the vertex cover problem is a subset V’ of V, which contains the vertices in the vertex cover. We can check whether the set V’ is a vertex cover of size k using the following strategy (for a graph G(V, E)):let count be an integer\nset count to 0\nfor each vertex v in V’\n remove all edges adjacent to v from set E\n increment count by 1\n if count = k and E is empty\n then\n the given solution is correct\n else\n the given solution is wrong\nIt is plain to see that this can be done in polynomial time. Thus the vertex cover problem is in the class NP.Proof that vertex cover is NP Hard –To prove that Vertex Cover is NP Hard, we take some problem which has already been proven to be NP Hard, and show that this problem can be reduced to the Vertex Cover problem. For this, we consider the Clique problem, which is NP Complete (and hence NP Hard).“In computer science, the clique problem is the computational problem of finding cliques (subsets of vertices, all adjacent to each other, also called complete subgraphs) in a graph.”Here, we consider the problem of finding out whether there is a clique of size k in the given graph. Therefore, an instance of the clique problem is a graph G (V, E) and a non-negative integer k, and we need to check for the existence of a clique ofsize k in G.Now, we need to show that any instance (G, k) of the Clique problem can be reduced to an instance of the vertex cover problem. Consider the graph G’ which consists of all edges not in G, but in the complete graph using all vertices in G. Let us call this the complement of G. Now, the problem of finding whether a clique of size k exists in the graph G is the same as the problem of finding whether there is a vertex cover of size |V| – k in G’. We need to show that this is indeed the case.Assume that there is a clique of size k in G. Let the set of vertices in the clique be V’. This means |V’| = k. In the complement graph G’, let us pick any edge (u, v). Then at least one of u or v must be in the set V – V’. This is because, if both u and v were from the set V’, then the edge (u, v) would belong to V’, which, in turn would mean that the edge (u, v) is in G. This is not possible since (u, v) is not in G. Thus, all edges in G’ are covered by vertices in the set V – V’.Now assume that there is a vertex cover V’’ of size |V| – k in G’. This means that all edges in G’ are connected to some vertex in V’’. As a result, if we pick any edge (u, v) from G’, both of them cannot be outside the set V’’. This means, alledges (u, v) such that both u and v are outside the set V’’ are in G, i.e., these edges constitute a clique of size k."
},
{
"code": null,
"e": 34479,
"s": 33572,
"text": "Proof that vertex cover is in NP –If any problem is in NP, then, given a ‘certificate’ (a solution) to the problem and an instance of the problem (a graph G and a positive integer k, in this case), we will be able to verify (check whether the solution given is correct or not) the certificate in polynomial time.The certificate for the vertex cover problem is a subset V’ of V, which contains the vertices in the vertex cover. We can check whether the set V’ is a vertex cover of size k using the following strategy (for a graph G(V, E)):let count be an integer\nset count to 0\nfor each vertex v in V’\n remove all edges adjacent to v from set E\n increment count by 1\n if count = k and E is empty\n then\n the given solution is correct\n else\n the given solution is wrong\nIt is plain to see that this can be done in polynomial time. Thus the vertex cover problem is in the class NP."
},
{
"code": null,
"e": 34706,
"s": 34479,
"text": "The certificate for the vertex cover problem is a subset V’ of V, which contains the vertices in the vertex cover. We can check whether the set V’ is a vertex cover of size k using the following strategy (for a graph G(V, E)):"
},
{
"code": null,
"e": 34965,
"s": 34706,
"text": "let count be an integer\nset count to 0\nfor each vertex v in V’\n remove all edges adjacent to v from set E\n increment count by 1\n if count = k and E is empty\n then\n the given solution is correct\n else\n the given solution is wrong\n"
},
{
"code": null,
"e": 35076,
"s": 34965,
"text": "It is plain to see that this can be done in polynomial time. Thus the vertex cover problem is in the class NP."
},
{
"code": null,
"e": 37156,
"s": 35076,
"text": "Proof that vertex cover is NP Hard –To prove that Vertex Cover is NP Hard, we take some problem which has already been proven to be NP Hard, and show that this problem can be reduced to the Vertex Cover problem. For this, we consider the Clique problem, which is NP Complete (and hence NP Hard).“In computer science, the clique problem is the computational problem of finding cliques (subsets of vertices, all adjacent to each other, also called complete subgraphs) in a graph.”Here, we consider the problem of finding out whether there is a clique of size k in the given graph. Therefore, an instance of the clique problem is a graph G (V, E) and a non-negative integer k, and we need to check for the existence of a clique ofsize k in G.Now, we need to show that any instance (G, k) of the Clique problem can be reduced to an instance of the vertex cover problem. Consider the graph G’ which consists of all edges not in G, but in the complete graph using all vertices in G. Let us call this the complement of G. Now, the problem of finding whether a clique of size k exists in the graph G is the same as the problem of finding whether there is a vertex cover of size |V| – k in G’. We need to show that this is indeed the case.Assume that there is a clique of size k in G. Let the set of vertices in the clique be V’. This means |V’| = k. In the complement graph G’, let us pick any edge (u, v). Then at least one of u or v must be in the set V – V’. This is because, if both u and v were from the set V’, then the edge (u, v) would belong to V’, which, in turn would mean that the edge (u, v) is in G. This is not possible since (u, v) is not in G. Thus, all edges in G’ are covered by vertices in the set V – V’.Now assume that there is a vertex cover V’’ of size |V| – k in G’. This means that all edges in G’ are connected to some vertex in V’’. As a result, if we pick any edge (u, v) from G’, both of them cannot be outside the set V’’. This means, alledges (u, v) such that both u and v are outside the set V’’ are in G, i.e., these edges constitute a clique of size k."
},
{
"code": null,
"e": 37340,
"s": 37156,
"text": "“In computer science, the clique problem is the computational problem of finding cliques (subsets of vertices, all adjacent to each other, also called complete subgraphs) in a graph.”"
},
{
"code": null,
"e": 37602,
"s": 37340,
"text": "Here, we consider the problem of finding out whether there is a clique of size k in the given graph. Therefore, an instance of the clique problem is a graph G (V, E) and a non-negative integer k, and we need to check for the existence of a clique ofsize k in G."
},
{
"code": null,
"e": 38094,
"s": 37602,
"text": "Now, we need to show that any instance (G, k) of the Clique problem can be reduced to an instance of the vertex cover problem. Consider the graph G’ which consists of all edges not in G, but in the complete graph using all vertices in G. Let us call this the complement of G. Now, the problem of finding whether a clique of size k exists in the graph G is the same as the problem of finding whether there is a vertex cover of size |V| – k in G’. We need to show that this is indeed the case."
},
{
"code": null,
"e": 38582,
"s": 38094,
"text": "Assume that there is a clique of size k in G. Let the set of vertices in the clique be V’. This means |V’| = k. In the complement graph G’, let us pick any edge (u, v). Then at least one of u or v must be in the set V – V’. This is because, if both u and v were from the set V’, then the edge (u, v) would belong to V’, which, in turn would mean that the edge (u, v) is in G. This is not possible since (u, v) is not in G. Thus, all edges in G’ are covered by vertices in the set V – V’."
},
{
"code": null,
"e": 38945,
"s": 38582,
"text": "Now assume that there is a vertex cover V’’ of size |V| – k in G’. This means that all edges in G’ are connected to some vertex in V’’. As a result, if we pick any edge (u, v) from G’, both of them cannot be outside the set V’’. This means, alledges (u, v) such that both u and v are outside the set V’’ are in G, i.e., these edges constitute a clique of size k."
},
{
"code": null,
"e": 39277,
"s": 38945,
"text": "Thus, we can say that there is a clique of size k in graph G if and only if there is a vertex cover of size |V| – k in G’, and hence, any instance of the clique problem can be reduced to an instance of the vertex cover problem. Thus, vertex cover is NP Hard. Since vertex cover is in both NP and NP Hard classes, it is NP Complete."
},
{
"code": null,
"e": 39359,
"s": 39277,
"text": "To understand the proof, consider the following example graph and its complement:"
},
{
"code": null,
"e": 39412,
"s": 39359,
"text": "See for – Proof that Hamiltonian Path is NP-Complete"
},
{
"code": null,
"e": 39435,
"s": 39412,
"text": "Algorithms-NP Complete"
},
{
"code": null,
"e": 39447,
"s": 39435,
"text": "NP Complete"
},
{
"code": null,
"e": 39454,
"s": 39447,
"text": "NPHard"
},
{
"code": null,
"e": 39478,
"s": 39454,
"text": "Engineering Mathematics"
},
{
"code": null,
"e": 39486,
"s": 39478,
"text": "GATE CS"
},
{
"code": null,
"e": 39519,
"s": 39486,
"text": "Theory of Computation & Automata"
},
{
"code": null,
"e": 39617,
"s": 39519,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39680,
"s": 39617,
"text": "Relationship between number of nodes and height of binary tree"
},
{
"code": null,
"e": 39702,
"s": 39680,
"text": "Inequalities in LaTeX"
},
{
"code": null,
"e": 39767,
"s": 39702,
"text": "Mathematics | Walks, Trails, Paths, Cycles and Circuits in Graph"
},
{
"code": null,
"e": 39790,
"s": 39767,
"text": "Arrow Symbols in LaTeX"
},
{
"code": null,
"e": 39840,
"s": 39790,
"text": "Newton's Divided Difference Interpolation Formula"
},
{
"code": null,
"e": 39860,
"s": 39840,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 39884,
"s": 39860,
"text": "ACID Properties in DBMS"
},
{
"code": null,
"e": 39897,
"s": 39884,
"text": "TCP/IP Model"
},
{
"code": null,
"e": 39946,
"s": 39897,
"text": "Page Replacement Algorithms in Operating Systems"
}
] |
Do static variables get initialized in a default constructor in java? | A static filed/variable belongs to the class and it will be loaded into the memory along with the class. You can invoke them without creating an object. (using the class name as reference). There is only one copy of the static field available throughout the class i.e. the value of the static field will be same in all objects. You can define a static field using the static keyword.
public class Sample{
static int num = 50;
public void demo(){
System.out.println("Value of num in the demo method "+ Sample.num);
}
public static void main(String args[]){
System.out.println("Value of num in the main method "+ Sample.num);
new Sample().demo();
}
}
Value of num in the main method 50
Value of num in the demo method 50
If you declare a static variable in a class, if you haven’t initialized them, just like with instance variables compiler initializes these with default values in the default constructor.
public class Sample{
static int num;
static String str;
static float fl;
static boolean bool;
public static void main(String args[]){
System.out.println(Sample.num);
System.out.println(Sample.str);
System.out.println(Sample.fl);
System.out.println(Sample.bool);
}
}
0
null
0.0
false
But if you declare an instance variable static and final Java compiler will not initialize it in the default constructor therefore, it is mandatory to initialize static and final variables. If you don’t a compile time error is generated.
public class Sample{
final static int num;
final static String str;
final static float fl;
final static boolean bool;
public static void main(String args[]){
System.out.println(Sample.num);
System.out.println(Sample.str);
System.out.println(Sample.fl);
System.out.println(Sample.bool);
}
}
Sample.java:2: error: variable num not initialized in the default constructor
final static int num;
^
Sample.java:3: error: variable str not initialized in the default constructor
final static String str;
^
Sample.java:4: error: variable fl not initialized in the default constructor
final static float fl;
^
Sample.java:5: error: variable bool not initialized in the default constructor
final static boolean bool;
^
4 errors
You cannot assign values to a final variable from a constructor −
public class Sample{
final static int num;
Sample(){
num =100;
}
}
Sample.java:4: error: cannot assign a value to final variable num
num =100;
^
1 error
The only way to initialize static final variables other than the declaration statement is Static block.
A static block is a block of code with a static keyword. In general, these are used to initialize the static members. JVM executes static blocks before the main method at the time of class loading.
public class Sample{
final static int num;
final static String str;
final static float fl;
final static boolean bool;
static{
num =100;
str= "krishna";
fl=100.25f;
bool =true;
}
public static void main(String args[]){
System.out.println(Sample.num);
System.out.println(Sample.str);
System.out.println(Sample.fl);
System.out.println(Sample.bool);
}
}
100
krishna
100.25
true | [
{
"code": null,
"e": 1446,
"s": 1062,
"text": "A static filed/variable belongs to the class and it will be loaded into the memory along with the class. You can invoke them without creating an object. (using the class name as reference). There is only one copy of the static field available throughout the class i.e. the value of the static field will be same in all objects. You can define a static field using the static keyword."
},
{
"code": null,
"e": 1744,
"s": 1446,
"text": "public class Sample{\n static int num = 50;\n public void demo(){\n System.out.println(\"Value of num in the demo method \"+ Sample.num);\n }\n public static void main(String args[]){\n System.out.println(\"Value of num in the main method \"+ Sample.num);\n new Sample().demo();\n }\n}"
},
{
"code": null,
"e": 1814,
"s": 1744,
"text": "Value of num in the main method 50\nValue of num in the demo method 50"
},
{
"code": null,
"e": 2001,
"s": 1814,
"text": "If you declare a static variable in a class, if you haven’t initialized them, just like with instance variables compiler initializes these with default values in the default constructor."
},
{
"code": null,
"e": 2309,
"s": 2001,
"text": "public class Sample{\n static int num;\n static String str;\n static float fl;\n static boolean bool;\n public static void main(String args[]){\n System.out.println(Sample.num);\n System.out.println(Sample.str);\n System.out.println(Sample.fl);\n System.out.println(Sample.bool);\n }\n}"
},
{
"code": null,
"e": 2326,
"s": 2309,
"text": "0\nnull\n0.0\nfalse"
},
{
"code": null,
"e": 2564,
"s": 2326,
"text": "But if you declare an instance variable static and final Java compiler will not initialize it in the default constructor therefore, it is mandatory to initialize static and final variables. If you don’t a compile time error is generated."
},
{
"code": null,
"e": 2896,
"s": 2564,
"text": "public class Sample{\n final static int num;\n final static String str;\n final static float fl;\n final static boolean bool;\n public static void main(String args[]){\n System.out.println(Sample.num);\n System.out.println(Sample.str);\n System.out.println(Sample.fl);\n System.out.println(Sample.bool);\n }\n}"
},
{
"code": null,
"e": 3334,
"s": 2896,
"text": "Sample.java:2: error: variable num not initialized in the default constructor\n final static int num;\n^\nSample.java:3: error: variable str not initialized in the default constructor\n final static String str;\n^\nSample.java:4: error: variable fl not initialized in the default constructor\n final static float fl;\n^\nSample.java:5: error: variable bool not initialized in the default constructor\n final static boolean bool;\n^\n4 errors"
},
{
"code": null,
"e": 3400,
"s": 3334,
"text": "You cannot assign values to a final variable from a constructor −"
},
{
"code": null,
"e": 3482,
"s": 3400,
"text": "public class Sample{\n final static int num;\n Sample(){\n num =100;\n }\n}"
},
{
"code": null,
"e": 3571,
"s": 3482,
"text": "Sample.java:4: error: cannot assign a value to final variable num\n num =100;\n^\n1 error"
},
{
"code": null,
"e": 3675,
"s": 3571,
"text": "The only way to initialize static final variables other than the declaration statement is Static block."
},
{
"code": null,
"e": 3873,
"s": 3675,
"text": "A static block is a block of code with a static keyword. In general, these are used to initialize the static members. JVM executes static blocks before the main method at the time of class loading."
},
{
"code": null,
"e": 4295,
"s": 3873,
"text": "public class Sample{\n final static int num;\n final static String str;\n final static float fl;\n final static boolean bool;\n static{\n num =100;\n str= \"krishna\";\n fl=100.25f;\n bool =true;\n }\n public static void main(String args[]){\n System.out.println(Sample.num);\n System.out.println(Sample.str);\n System.out.println(Sample.fl);\n System.out.println(Sample.bool);\n }\n}"
},
{
"code": null,
"e": 4319,
"s": 4295,
"text": "100\nkrishna\n100.25\ntrue"
}
] |
Search a 2D Matrix II in Python | Suppose we have one m x n matrix. We have to write an efficient algorithm that searches for a value in that matrix. This matrix has the following properties −
Integers in each row are sorted in ascending from left to right.
Integers in each column are sorted in ascending from top to bottom.
So if the matrix is like −
If target is 5, then return true, if target is 20, then return false
To solve this, we will follow these steps −
len := number of columns, c1 := 0, c2 := len – 1
while trueif matrix[c1, c2] = target, then return trueelse if matrix[c1, c2] > target, then c2 := c2 – 1, continuec1 := c1 + 1if c1 >= row count or c2 < 0, then return falsereturn false
if matrix[c1, c2] = target, then return true
else if matrix[c1, c2] > target, then c2 := c2 – 1, continue
c1 := c1 + 1
if c1 >= row count or c2 < 0, then return false
return false
Let us see the following implementation to get better understanding −
Live Demo
class Solution:
def searchMatrix(self, matrix, target):
try:
length = len(matrix[0])
counter1, counter2 = 0, length-1
while True:
if matrix[counter1][counter2] == target:
return True
elif matrix[counter1][counter2]>target:
counter2-=1
continue
counter1 = counter1 + 1
if counter1 >= len(matrix) or counter2<0:
return False
except:
return False
ob1 = Solution()
print(ob1.searchMatrix([[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], 5))
[[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]]
5
True | [
{
"code": null,
"e": 1224,
"s": 1062,
"text": " Suppose we have one m x n matrix. We have to write an efficient algorithm that searches for a value in that matrix. This matrix has the following properties −"
},
{
"code": null,
"e": 1289,
"s": 1224,
"text": "Integers in each row are sorted in ascending from left to right."
},
{
"code": null,
"e": 1357,
"s": 1289,
"text": "Integers in each column are sorted in ascending from top to bottom."
},
{
"code": null,
"e": 1384,
"s": 1357,
"text": "So if the matrix is like −"
},
{
"code": null,
"e": 1453,
"s": 1384,
"text": "If target is 5, then return true, if target is 20, then return false"
},
{
"code": null,
"e": 1497,
"s": 1453,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1546,
"s": 1497,
"text": "len := number of columns, c1 := 0, c2 := len – 1"
},
{
"code": null,
"e": 1732,
"s": 1546,
"text": "while trueif matrix[c1, c2] = target, then return trueelse if matrix[c1, c2] > target, then c2 := c2 – 1, continuec1 := c1 + 1if c1 >= row count or c2 < 0, then return falsereturn false"
},
{
"code": null,
"e": 1777,
"s": 1732,
"text": "if matrix[c1, c2] = target, then return true"
},
{
"code": null,
"e": 1838,
"s": 1777,
"text": "else if matrix[c1, c2] > target, then c2 := c2 – 1, continue"
},
{
"code": null,
"e": 1851,
"s": 1838,
"text": "c1 := c1 + 1"
},
{
"code": null,
"e": 1899,
"s": 1851,
"text": "if c1 >= row count or c2 < 0, then return false"
},
{
"code": null,
"e": 1912,
"s": 1899,
"text": "return false"
},
{
"code": null,
"e": 1982,
"s": 1912,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 1993,
"s": 1982,
"text": " Live Demo"
},
{
"code": null,
"e": 2625,
"s": 1993,
"text": "class Solution:\n def searchMatrix(self, matrix, target):\n try:\n length = len(matrix[0])\n counter1, counter2 = 0, length-1\n while True:\n if matrix[counter1][counter2] == target:\n return True\n elif matrix[counter1][counter2]>target:\n counter2-=1\n continue\n counter1 = counter1 + 1\n if counter1 >= len(matrix) or counter2<0:\n return False\n except:\n return False\nob1 = Solution()\nprint(ob1.searchMatrix([[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], 5))"
},
{
"code": null,
"e": 2705,
"s": 2625,
"text": "[[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]]\n5"
},
{
"code": null,
"e": 2710,
"s": 2705,
"text": "True"
}
] |
Subsets and Splits